'Spring boot doesn't recognise 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
{"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.
Solution 1:[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
}
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yunus Batus |
Solution 2 | Diego Laucsen |