Vue axios post传值到后台时获取不到

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36091581/article/details/80499150

Vue axios post传值到后台时获取不到

Axios post 参数为null

解决:

  1. 引用qs, 安装qs模块 (npm install –save qs)
  2. main.js 里的代码截图
    这里写图片描述
    同时要在main里加上这个head
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

下面送上我的axios调用方法:

this.$post('https://xxx.action',
        this.$qs.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

1.字符串

let params = new URLSearchParams();
params.append('age', '24');
  1. JSON
    由于axios默认发送数据时,数据格式是Request Payload,而并非我们常用的Form Data格式,后端未必能正常获取到,所以在发送之前,需要使用qs模块对其进行处理。
// 如上面axios用法里参数的处理一样

至此,数据返回成功

猜你喜欢

转载自blog.csdn.net/qq_36091581/article/details/80499150