我尝试删除具有给定id的实体。然而,当我试图从我的API获取,我得到一个400坏请求错误。
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();
}
在我的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]
我已经尝试将参数放入JSON.stringify()中,但这不会改变任何东西。
控制器代码:
@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;
}
您正在通过body发送数据,但在控制器中您正在等待@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;
}
你需要改变你接收id param的方式(@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;
}
或者改变你从React发送的方式(作为url参数发送)