Ajax 对 Spring Boot 端点的请求无法读取 HTTP MSG



我有一个 ajax 请求将数据传递给 spring 引导端点。但是我收到以下错误:

Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.applicationName.controller.EventController.deleteCalendarEvents(com.applicationName.model.Vacation,javax.servlet.http.HttpSession)

这是我的Ajax请求:

$.ajax({
method: 'POST',
url: '/vacation/deleteEvents',
contentType: 'application/json; charset=utf-8;',
dataType: 'json',
data: JSON.stringify(vacation),
success: function (response) {
if (response !== "OK")
alert(response);
else
console.log(response);
},
error: function (e) {
console.log(e);
}
});

这是我的 Spring 启动端点:

@RequestMapping(value = "/vacation/deleteEvents", method = RequestMethod.GET)
public String deleteCalendarEvents (@RequestBody Vacation vacation, HttpSession session){
//code
}

如果我将其更改为 POST,它会给我一个错误,说我无法发布到 GET 并且在线阅读人们建议更改为 GET。如果您有任何建议,请告诉我。我有一种感觉,我在这里缺少一个核心概念。谢谢。我会尝试任何建议并发布更新。

基本上,您正在尝试将某些内容发布给准备接受 GET 的人。这就像和一个只说意大利语的人说英语......他们不能互相理解。

无论您的原因是什么,您都必须使您的客户端和服务器使用相同的语言,并使用相同的隧道......如果您的客户端开机自检,则您的服务器必须接受开机自检。如果您的客户端 GET,则您的服务器必须接受 GET。

$.ajax({
method: 'POST',
url: '/vacation/deleteEvents',
contentType: 'application/json; charset=utf-8;',
dataType: 'json',
data: JSON.stringify(vacation),
success: function (response) {
if (response !== "OK")
alert(response);
else
console.log(response);
},
error: function (e) {
console.log(e);
}
});
@RequestMapping(value = "/vacation/deleteEvents", method = RequestMethod.POST)
public String deleteCalendarEvents (@RequestBody Vacation vacation, HttpSession session){
//code
}

如果要接受 GET,则客户端必须发送 GET 请求:

$.ajax({
method: 'GET',
url: '/vacation/deleteEvents',
success: function (response) {
if (response !== "OK")
alert(response);
else
console.log(response);
},
error: function (e) {
console.log(e);
}
});
@RequestMapping(value = "/vacation/deleteEvents", method = RequestMethod.GET)
public String deleteCalendarEvents (HttpSession session){
//code
}

因此,如果您希望能够检索@RequestBody,则必须开机自检。

但是,以更面向 RESTFul 的方式,您可以发送一个 DELETE 请求:

$.ajax({
method: 'DELETE',
url: `/vacation/${vacation.id}`, // assuming your object vacation has an id field.
success: function (response) {
if (response !== "OK")
alert(response);
else
console.log(response);
},
error: function (e) {
console.log(e);
}
});
@RequestMapping(value = "/vacation/{vacationId}", method = RequestMethod.DELETE)
public String deleteCalendarEvents (@PathVariable int vacationId, HttpSession session){
//code
}

希望对您有所帮助

@RequestMapping(value = "/vacation/deleteEvents", method = RequestMethod.POST)
public String deleteCalendarEvents (@RequestBody Vacation vacation){
//code
}

最新更新