解决axios传递参数后台无法接收问题

解决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、
  • 二、Axios post 参数为null

我们后台要求传的参数格式必须为:

let data = {};
{param: JSON.stringify(data)}
  • main.js 里的代码截图 

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

至此,数据返回成功 
这里写图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值