2

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.

Jens
  • 69,818
  • 15
  • 125
  • 179
Jose
  • 25
  • 1
  • 5
  • Hi @Aitor, instead of RequestBody annotation use RequestParam. – Raushan Kumar Feb 15 '22 at 11:36
  • Hi @RaushanKumar even with RequestParam it says Bad Request. Thanks for your answer – Jose Feb 15 '22 at 11:39
  • Hi @Aitor Please follow this, I think you missed updating the content type. https://stackoverflow.com/questions/28039709/what-is-difference-between-requestbody-and-requestparam – Raushan Kumar Feb 15 '22 at 11:43
  • Thanks for your answe Raushan, but it wasnt that problem, the controller was expecting an entity but how it was the json i had to put that it received a map. But thank you, i appreciated your help. – Jose Feb 15 '22 at 11:54

2 Answers2

1

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

Maybe you can try this:

const fdata = new FormData();
fdata.append('username', 'diego');
fdata.append('password', '1242342');

fetch(url, {
  method: 'POST',
  headers: ...,
  body: fdata,
});

I had the same problemas as you and this approach has fixed my problem.

Diego Laucsen
  • 61
  • 1
  • 7