I try to delete an entity with a given id. However, when I try to fetch from my API, i get a 400 bad request error.
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:
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.
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;
}
CodePudding user response:
You are sending the data via body, but in the controller you are waiting that as a @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:
@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)