gpt4 book ai didi

java - Spring Controller 向来自 AngularJS 应用程序的请求返回 415

转载 作者:行者123 更新时间:2023-12-01 17:38:15 25 4
gpt4 key购买 nike

我有一段时间被一些看起来非常微不足道的事情困住了,但我就是无法让它工作。我有一个 AngularJS Controller ,它通过休息调用 backen Spring boot 应用程序。我可以确认,如果我通过 Postman 向后端发出请求,它工作得很好,只是当通过 html 页面完成时,它就不起作用,我得到了 415。

var survey = angular.module('survey', []);

var surveyDto = {
age:"",
sex:"",
status:"",
chronic:"",
keyWorker:""
};

survey.controller('surveyController', function($scope, $http) {

$scope.sendAnswers = function(surveyDto) {

$http(
{
method: 'POST',
url: 'http://localhost:8080/surveys/new',
data: angular.toJson(surveyDto),
headers: {'Content-Type': 'application/json'}
}
);
};
});

在后端我有一个非常简单的 Java Controller :

@RequestMapping(value = "/surveys/new", consumes = "application/json", produces = "application/json", method = RequestMethod.POST)
public ResponseEntity<NewSurveyResponse> newSurvey(HttpServletRequest request) {

//...
}

当网页使用 Controller 发送请求时,我收到 415(不支持的媒体类型)。

enter image description here

我不明白为什么。在我尝试在 Controller 中使用我自己的 dto 对象来表示数据之前,但也不起作用。我不确定缺少什么。我在某处读到我可以使用 HttpServletRequest,但也不起作用。有什么想法吗?

我正在使用以下版本的 Spring 和 AngularJS- GoogleApis Angular 1.7.9- Spring启动2.2.4

更新在调试调度程序 servlet 期间,我可以观察到使用的媒体类型是正确的。看图片: enter image description here

更新2尝试 Marco Behler 建议的代码,出现以下错误: enter image description here

更新3我尝试为上述错误添加导入,但我得到了这个 enter image description here

最佳答案

错误消息显示您的 Content-Type 为“”,为空,这让我相信您在 Angular 调用中指定了错误。

尝试这个 - 或其变体。

import { HttpHeaders } from '@angular/common/http';

let headers = new HttpHeaders({
'Content-Type': 'application/json'});
let options = { headers: headers };
$http.post("http://localhost:8080/surveys/new", surveyDto, options);

关于java - Spring Controller 向来自 AngularJS 应用程序的请求返回 415,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61008728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com