【问题标题】:JS Fetch to Spring > Required request body is missingJS Fetch to Spring > 缺少所需的请求正文
【发布时间】:2017-08-19 00:56:24
【问题描述】:

我目前正在尝试将(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) )
    }

还有spring方法:

@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 方法执行时……你看到了错误。为了使 fetch 工作,我必须在这里配置什么?

【问题讨论】:

    标签: spring rest request fetch-api


    【解决方案1】:

    根据 fetch API,json 应该以body 发送,而不是data。并且标头也应该使用new Headers() 发送。尝试修复它们:

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

    【讨论】:

      猜你喜欢
      • 2021-09-24
      • 2022-11-11
      • 1970-01-01
      • 2020-04-01
      • 2019-03-29
      • 1970-01-01
      • 2019-09-09
      • 1970-01-01
      • 2017-08-01
      相关资源
      最近更新 更多