我正在尝试从javascript fetch函数中使用REST API。但在rest api中,我总是收到缺少请求体的错误。下面是我的代码,
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函数:
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);});
}在执行此操作时,我没有在浏览器控制台中看到任何错误记录。在eclipse中唯一的错误是,
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)]我是不是漏掉了什么?谢谢。
发布于 2019-11-17 15:40:22
将mode添加为"no-cors“,如下所述
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
})
})这可能是跨源策略的一个问题……它对我来说很管用。
https://stackoverflow.com/questions/58898144
复制相似问题