问题:使用 @RequestBody 接收前端 post 过来的 JSON 对象,对象转换失败为null。
框架:前端Vue.js使用 Axios 与后台交互,后台 SpringMVC 使用 @RequestBody 接收前台传输的 JSON 参数。
经使用 Jmeter模拟 post请求 和 F12 分析,系因使用 axios 传参时使用了错误的写法导致生成给后台的 JSON 错误:
错误写法:
this.$axios.post('http://localhost:1234/test/payAdd', {
params: {
user:'test',
ID:'1234',
}
}).then((response) => {
//TODO
}).catch(error => {
//TODO
})
这种带’params’关键字的写法只用于 get 请求,在 post 请求中,如果也这么写,
那么会导致 http 正文 payload 里的 JSON 字符串变为:
{params:{"user":"test","ID":"1234"}}
这样的 JSON 字符串,@RequestBody 无法解析。
而正确的写法:
this.$axios.post('http://localhost:55321/test/payAdd',
{
payTransId:'XNO',
rsnCd:'4512',
insPID:'01020000',
payTransAt:'101.23',
remark:'test',
}
这样生成出来的JSON串才是对的:
{"user":"test","ID":"1234"}
@RequestBody 也能够正常解析成对象。
针对 axios http 请求的写法,也可以使用 axios API 的写法:
axios API
Requests can be made by passing the relevant config to axios.
axios(config)
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
具体写法请参考:
axios–github
另外,网上一众帖子说的将 http 的 Content-Type 由 axios 默认的 application/json
修改为 form-data 使用的 application/x-www-form-urlencoded 形式,并非好的解决方案。
Restful 形式的请求交互,就应该使用 application/json
形式。