当前位置: 移动技术网 > IT编程>脚本编程>vue.js > 解决axios发送post请求返回400状态码的问题

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

2018年08月18日  | 移动技术网IT编程  | 我要评论

陆丰市,儿歌简谱两只老虎,李开复学习网

今天在用 发送一个跨域的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状态码的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网