Axios 发送 POST请求,后端接收不到参数的解决方案
axios 发 post 请求,后端接收不到参数的解决方案,报错:
Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required Integer parameter 'title' is not present]
而换成get请求参数是可以接收到的。
解决方案:
第一种 @RequestBody
后端:
@PostMapping("/add")
public R add(@RequestBody String param) {
System.out.println("param = " + param);
}
输出
param = {"title":"123","remark":"1"}
前端:
let header = {
'content-type': 'application/json;charset=utf-8',
};
header: header,
data: JSON.stringify(data)
第二种 @RequestParam
后端:
@PostMapping("/add2")
public R add2(@RequestParam String title, @RequestParam String remark) {
System.out.println("title = " + title);
System.out.println("remark = " + remark);
return R.ok();
}
输出
title = 123
remark = 1222
前端:
let header = {
'content-type': 'application/x-www-form-urlencoded',
};
header: header,
data: Qs.stringify(data), // 使用 Qs.stringify() 格式化
transformRequest: [ // 或使用 transformRequest 方法进行数据格式转换
function (data) {
let ret = ''
for (let it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
ret = ret.substring(0, ret.lastIndexOf('&'));
return ret
}
],
或者前端拼接参数:
axios.post('/api/url',"title='title'&remark='remark'");
参考:
https://www.jianshu.com/p/482d61f96075
https://blog.csdn.net/qq_43183340/article/details/105759470
https://www.cnblogs.com/similar/p/10680228.html?ivk_sa=1024320u