Medardas
Medardas

Reputation: 540

JS Fetch to Spring > Required request body is missing

I'm currently trying to put(HTTP put) simple data to my Spring server however I can not get it to work via Javascript Fetch. It return following error:

"status" : 400,
"error" : "Bad Request",
"exception" : "org.springframework.http.converter.HttpMessageNotReadableException",
"message" : "Required request body is missing: public java.lang.String org.mypackage.security.controller.fcm.FCMController.saveFCMToken(javax.servlet.http.HttpServletRequest,java.lang.String)"

My JS Code:

saveTokenToDB(token){
        fetch(Constants.server_endpoint + "/savefcmtoken", {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': Constants.token
            },
            data: JSON.stringify({token:token})
        })
            .then(response => {
                console.log("saveTokenToDB response: " + response._bodyText);
            })
            .catch( (error) => console.log(" ERROR > saveTokenToDB: " + error.message) )
    }

And spring method:

@RequestMapping(value = "/savefcmtoken", consumes = "application/json", method = RequestMethod.PUT)
public @ResponseBody
String saveFCMToken(HttpServletRequest request, @RequestBody String data){
    JwtUser user = (JwtUser) getUser(request);
    FCMData dataObj = new Gson().fromJson(data, FCMData.class);
    fcmTokenService.insertIfNotExists(new FCMToken((int)user.getId(),dataObj.getToken()));
    return "OK";
}

I know It should be fine on server side, because I'm able to properly carry out request in Postman, but when doing it via fetch method...well you saw the error. What is here I have to configure in order for the fetch to work?

Upvotes: 1

Views: 3883

Answers (1)

Monzurul Shimul
Monzurul Shimul

Reputation: 8396

According to fetch API, json should be send as body, not data. And also headers should be send with new Headers(). Try with fixing them:

saveTokenToDB(token){
        fetch(Constants.server_endpoint + "/savefcmtoken", {
            method: 'PUT',
            headers: new Headers({
                'Content-Type': 'application/json',
                'Authorization': Constants.token
            }),
            body: JSON.stringify({token:token})
        })
            .then(response => {
                console.log("saveTokenToDB response: " + response._bodyText);
            })
            .catch( (error) => console.log(" ERROR > saveTokenToDB: " + error.message) )
    }

Upvotes: 4

Related Questions