axios发送post请求返回400状态码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/transformer_WSZ/article/details/80273815

今天在用 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;
}

这样数据就成功返回了!

猜你喜欢

转载自blog.csdn.net/transformer_WSZ/article/details/80273815