解决axios传递参数后台无法接收问题
1.根据下面几个方法改变前台传递参数方式
这样后台就可以直接根据传递的参数获取数据,如下图用户登录时直接传递用户名和密码
2.不改变前台传递样式修改后台接收方式
以上为解决问题方案
以下是参考文章
===============================================================================================
-
理解性参考文章
Axios
:
1. 跨域: GET
请求不赘述,如下设置后台允许跨域便可使用 POST
请求时,被转换为 OPTIONS
,并且出现403 forbidden
2. 传参为null
一、 跨域问题的解决
1. 后台设置
response.setHeader( "Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
//response.addHeader( "Access-Control-Allow-Origin", "*" ); //可以访问此域资源的域。*为所有
response.setHeader("Access-Control-Allow-Origin","http://localhost:8080");
response.addHeader( "Access-Control-Allow-Methods", "POST,OPTIONS,GET" ); //可以访问此域的脚本方法类型
response.addHeader( "Access-Control-Max-Age", "1000" );
- 1
- 2
- 3
- 4
- 5
2. VUE 设置
proxyTable: {'/api': {
target: 'https://xxx',
bypass: function (req, res, proxyOptions) {
req.headers.referer = 'https://xxx/';
req.headers.host = 'xxx';
},
changeOrigin:true,//允许跨域
pathRewrite: {
'^/api': '/'
}
}},
3. 浏览器设置
chrome 浏览器 右键属性, 找到目标,在后面加上
--disable-web-security --user-data-dir=C:\MyChromeDevUserData
- 例如:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir=C:\MyChromeDevUserData、
我们后台要求传的参数格式必须为:
let data = {};
{param: JSON.stringify(data)}
- main.js 里的代码截图
下面送上我的axios调用方法:
this.$post('https://xxx.action',
this.$qs.stringify({param: JSON.stringify({a: '2'})})).then((response) => {
console.log(response)
this.$notify({
title: '成功',
message: response.errorCode,
type: 'success'
})
}).catch((response) => {
console.log(response)
let errorData = ''
if (response.response === undefined) {
errorData = response.errorMsg
} else {
errorData = response.errorMsg
}
this.$notify.error({
title: '失败',
message: errorData
})
})
* 题外话
post 传参数 有两种格式,一种是字符串,一种是json
- 字符串
let params = new URLSearchParams();
params.append('age', '24');
- 1
- 2
- JSON
由于axios默认发送数据时,数据格式是Request Payload,而并非我们常用的Form Data格式,后端未必能正常获取到,所以在发送之前,需要使用qs模块对其进行处理。
// 如上面axios用法里参数的处理一样
- 1
至此,数据返回成功