我正在探索fetch api并希望将一些日期发送到spring引导方法,但是它会抛出400
错误
JS代码
let fetchConfig = {
method : params.method || 'GET',
body : params.body
};
return fetch(_url,fetchConfig).then(function (response) {
if (!response.ok) {
throw Error(response.statusText);
}
else {
return response.json();
}
}).then(function (data) {
return data;
}).catch(function (error) {
return error;
})
Spring引导方法
@RequestMapping(value = "/validate",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ValidateUserModel validateUser(@RequestParam("userName") String userName, @RequestParam("password") String pass){
System.out.println("--- test");
ValidateUserModel validateUserModel = new ValidateUserModel();
validateUserModel.setUserName("Test");
validateUserModel.setPassWord("Test 2");
return validateUserModel;
}
这就是fetchConfig
的样子
body:{userName: "awdaw", password: "awdawd"}
method:"POST"
password:"test"
url:"test"
userName:"awdaw"
__proto__:Object
预览从java类发送的值
error:"Bad Request"
exception:"org.springframework.web.bind.MissingServletRequestParameterException"
message:"Required String parameter 'userName' is not present"
path:"/validate"
status:400
timestamp:1504771336175
错误显示为Required String parameter 'userName' is not present
,但fetchConfig
具有所需的密钥
答案 0 :(得分:0)
您的Java代码需要请求参数,因此预期的网址应该类似于.../validate?username=<someValue>&password=<otherValue>
,但您的js是在正文中发送的(这是一个更好的选择,发送用户和密码作为URL的一部分是根本不安全。)
您可以将Java代码更改为
@RequestMapping(value = "/validate",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ValidateUserModel validateUser(@RequestBody User user){
System.out.println("--- test");
ValidateUserModel validateUserModel = new ValidateUserModel();
validateUserModel.setUserName(user.getUserName());
validateUserModel.setPassWord(user.getPassword());
return validateUserModel;
}
User
只是一个以password
和userName
为属性的bean。
答案 1 :(得分:0)
尝试使用@RequestBody注释。
@RequestMapping(value = "/validate",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ValidateUserModel validateUser(@RequestBody User user){
System.out.println("--- test");
ValidateUserModel validateUserModel = new ValidateUserModel();
validateUserModel.setUserName(user.getUserName());
validateUserModel.setPassWord(user.getPassword());
return validateUserModel;
}
,请求应如下所示:
let data = {userName: "awdaw", password: "awdawd"};
fetch{ url, {
body: JSON.stringfy(data)
method:"POST"
headers: {
"Content-Type": "application/json",
},
}).then(
response => {
return response.json();
}