Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring boot doesnt recognice react fetch body

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

which is correct but when Spring recieve 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 says that its a bad Request but i have no idea why is it.

Thanks in advance.

>Solution :

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
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading