Home > Back-end >  Spring boot doesn't recognise react fetch body
Spring boot doesn't recognise react fetch body

Time:02-16

Spring boot is not getting the params in the request body. The controller is defined like:

    @PostMapping("/login")
    public @ResponseBody User login(@RequestBody String username, @RequestBody String password) {
            return userService.login(username,password);
    }

And the fetch in React

 const LogFunc = async () => {
        let url = new URL("http://localhost:8080/user/login");
        let params = {
            username: username,
            password: password
        }
        console.log(JSON.stringify(params));
        return fetch(url, {
            method: 'POST',
            headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
            body: JSON.stringify(params)

When i console.log it, it prints it like

{"username":"allanosi","password":"cap"}

which is correct but when Spring receive it, it prints:

Required request body is missing: public com.formacion.back.entities.User com.formacion.back.controllers.UserController.login(java.lang.String,java.lang.String)]

On the network part it says that it's a bad Request but I have no idea why it is.

Thanks in advance.

CodePudding user response:

Can you try this? Just replace the annotation with this.

@RequestMapping(
      value = "/login",
      method = RequestMethod.POST,
      produces = MediaType.APPLICATION_JSON_VALUE)

Another guess, spring boot is waiting string not object that's why you might getting request body is missing error. You can try this:

public @ResponseBody User login(@RequestBody Map<String, String> userData) {
            // your code
    }
  • Related