[英]400 Bad request when trying to fetch from SpringBoot using React
I try to delete an entity with a given id.我尝试删除具有给定 ID 的实体。 However, when I try to fetch from my API, i get a 400 bad request error.但是,当我尝试从我的 API 中获取时,我收到 400 bad request 错误。
async deleteFood(foodId) {
const params = {
'id' : foodId
}
const rawResponse = await fetch("food/delete", {
method:"POST",
headers: {'Content-Type': 'application/json'},
body: params,
});
const content = await rawResponse.json();
}
In my SpringBoot log, it shows me the id parameter is missing:在我的 SpringBoot 日志中,它显示缺少 id 参数:
WARN 7784 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'id' for method parameter type int is not present]
I already tried putting params into JSON.stringify(), but this doesn't change anything.我已经尝试将参数放入 JSON.stringify(),但这并没有改变任何东西。
Controller code:控制器代码:
@PostMapping(path = "/delete")
public @ResponseBody int deleteById(@RequestParam int id) {
if (foodRepository.existsById(id)) {
foodRepository.deleteById(id);
return Response.SC_ACCEPTED;
}
return Response.SC_BAD_REQUEST;
}
You are sending the data via body, but in the controller you are waiting that as a @RequestParam您正在通过正文发送数据,但在控制器中您正在等待 @RequestParam
@PostMapping(path = "/delete")
public @ResponseBody int deleteById(@RequestParam int id) {
if (foodRepository.existsById(id)) {
foodRepository.deleteById(id);
return Response.SC_ACCEPTED;
}
return Response.SC_BAD_REQUEST;
}
You need to either change the way you receive id param (@RequestBody instead of @RequestParam) some like:您需要更改接收 id 参数(@RequestBody 而不是@RequestParam)的方式,例如:
@PostMapping(path = "/delete")
public @ResponseBody int deleteById(@RequestBody int id) {
if (foodRepository.existsById(id)) {
foodRepository.deleteById(id);
return Response.SC_ACCEPTED;
}
return Response.SC_BAD_REQUEST;
}
or change the way you're sending from React (send it as a url param)或更改您从 React 发送的方式(将其作为 url 参数发送)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.