简体   繁体   中英

400 Bad request when trying to fetch from SpringBoot using React

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;
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM