axios傳送post請求返回400狀態碼
阿新 • • 發佈:2018-10-31
今天在用 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;
}
這樣資料就成功返回了!