gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:02:04 25 4
gpt4 key购买 nike

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

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 Boot 端点:

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

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

最佳答案

基本上,您正在尝试将某些内容 POST 给准备接受 GET 的人。这就像和一个只会说意大利语的人说英语一样……他们无法理解对方。

无论你的原因是什么,你必须让你的客户端和服务器使用相同的语言,并使用相同的隧道...如果你的客户端 POST,你的服务器必须接受 POST。如果您的客户端 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,则必须 POST。

但是,以一种更面向 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
}

希望对你有帮助

关于javascript - 对 Spring Boot 端点的 Ajax 请求无法读取 HTTP MSG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60087913/

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