您的位置:首页 > 移动开发 > IOS开发

解决axios发送post请求返回400状态码的问题

2018-08-11 15:38 946 查看

今天在用 axios 发送一个跨域的post请求时,遇到了一个坑:Uncaught (in promise) Error: Request failed with status code 400。

前台代码如下:

axios({
method: "post",
url: "http://localhost:8080/employee/testpost",
data: {
username: '234234',
password: '4565'
}
}).then((res) => {
console.log(res.data);
})

后台代码如下:

@CrossOrigin
@PostMapping("/employee/testpost")
@ResponseBody
public Result testpost(@RequestParam(value = "username", required = true) String username,
@RequestParam(value = "password", required = true) String password) {
System.out.println(username + " , " + password);
Result json = new Result();
json.setResult(1);
return json;
}

而当我在postman上发送post请求时就能成功获得返回数据。困扰了很久,才发现是请求头的问题。axios请求头的 Content-Type 默认是 application/json,而postman默认的是 application/x-www-form-urlencoded。我这里采取的解决办法是改变后台的接收方式:

@CrossOrigin
@PostMapping("/employee/testpost")
@ResponseBody
public Result testget(@RequestBody Map map) {
System.out.println(map.get("username") + " , " + map.get("password"));
Result json = new Result();
json.setResult(1);
return json;
}

这样数据就成功返回了!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  axios post 400