JS Fetch to Spring>缺少必需的请求正文

时间:2017-03-26 10:07:21

标签: spring rest request fetch-api

我目前正在尝试将(HTTP put)简单数据放到我的Spring服务器上,但是我无法通过Javascript Fetch使其工作。它返回以下错误:

"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)"

我的JS代码:

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

春天方法:

@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";
}

我知道在服务器端应该没问题,因为我能够在Postman中正确执行请求,但是当通过fetch方法执行时...你看到了错误。我必须配置什么才能使提取工作?

1 个答案:

答案 0 :(得分:4)

根据fetch API,json应该以{{1​​}}发送,而不是body。标题也应与data一起发送。尝试修复它们:

new Headers()