Nithyananth
Nithyananth

Reputation: 74

JavaScript fetch function for POST call, Required requestbody is missing error in rest api

I am trying to consume REST API from javascript fetch function. But I am always getting missing request body error in rest api. Below are my codes,

REST API:

@RequestMapping(value = "/register", method = RequestMethod.POST, produces = { "application/json" }, consumes = { "application/json"})
    public void registerUser(@RequestBody String userDetails) {

        System.out.println(userDetails);
    }

JS function:

const registerUser = async() => {

var userName = document.getElementById("userName").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;

    await fetch('http://localhost:8080/register', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            "userName" : userName,
            "email" : email,
            "password": password
        }) 
    })
    .then(res => {console.log(res);})
    .catch(error => {console.log(error);});

}

On doing this I dont see any errors logged in browser console. Only error getting in eclipse is,

2019-11-17 11:59:45.144  WARN 2440 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public void com.murugan.exp.controller.UserController.registerUser(java.lang.String)]

Is there anything Im missing on this? Thank you.

Upvotes: 1

Views: 583

Answers (1)

pavan kumar
pavan kumar

Reputation: 823

add mode as "no-cors" as mentioned below

await fetch('http://localhost:8080/register', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        mode:"no-cors",
        body: JSON.stringify({
            "userName" : userName,
            "email" : email,
            "password": password
        }) 
    })

it might be an issue with cross origin policy..., it worked for me try that out.

Upvotes: 1

Related Questions