400问题报错,原因分析
请求网址:http://api.gshop.com/api/item/brand
请求方法:POST
远程地址:127.0.0.1:80
状态码:
400
版本:HTTP/1.1
Referrer 政策:no-referrer-when-downgrade
Accept
application/json, text/plain, */*
Accept-Encoding
gzip, deflate
Accept-Language
zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Cache-Control
no-cache
Connection
keep-alive
Content-Length
62
Content-Type
application/json;charset=utf-8
Host
api.gshop.com
Origin
http://manage.gshop.com
Pragma
no-cache
Referer
http://manage.gshop.com/
User-Agent
Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/75.0
返回结果:
{"name":"Vimi(薇迷)","image":"","cids":"871","letter":"V"}
** 请求的数据格式是JSON格式**
原因分析:
axios处理请求体的原则会根据请求数据的格式来定:
- 如果请求体是对象:会转为JSON发送
- 如果请求体是String:会作为普通表单请求发送,但是需要我们自己保证String格式是键值对;
例如:“name:igo&age=1"
QS工具
QS是一个第三方库,我们可以用npm install qs --save来安装。不过 我们在项目中已经集成,
"dependencies": {
"axios": "^0.18.0",
"echarts": "^4.1.0",
"element-ui": "^2.3.2",
"iview": "^2.11.0",
"qs": "^6.9.3",
"vue": "^2.5.2",
"vue-quill-editor": "^3.0.5",
"vue-router": "^3.0.1",
"vuetify": "^1.0.11"
}
main.js
import qs from 'qs'
Vue.prototype.$qs = qs;
this.$http({
method: this.isEdit ? 'put' : 'post',
url: '/item/brand',
data: this.$qs.stringify(params)
}).then(() => {
// 关闭窗口
this.$emit("close");
this.$message.success("保存成功!");
})
.catch(() => {
this.$message.error("保存失败!");
});
}
},
data: this.$qs.stringify(params)
返回结果:
name=Dior&image=&cids=471&letter=D
后台
@PostMapping
public ResponseEntity<Void> saveBrand(Brand brand, @RequestParam(value = "cids") List<Long> cids) {
brandService.saveBrand(brand, cids);
return ResponseEntity.status(HttpStatus.CREATED).build();
}