先说明一下经历吧

需求:
有些时候使用application/x-www-form-urlencoded,也就是大家在项目经常用到的一种提交格式
有些时候使用application/json提交数据,也很常用
本人在开发过程中呢
一般使用application/x-www-form-urlencoded格式提交数据来查询
使用application/json格式来增加数据和修改数据
(不知道这两种格式的区别自行百度…emmmm…)

一开始呢,我天真的以为axios和jq 的ajax一样,通过修改header就能达到提交数据时候,自动根据我设置的header来进行数据的提交更改…
在不断的尝试中,我首先通过axios 初始化配置时候,我修改了它默认的header和加上了transformRequest ,结果是可以的

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.transformRequest = [function (data) {
  let ret = ''
  for (let it in data) {
    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
  }
  return ret
}]
Vue.prototype.$axios = axios;

我再一次尝试把transformRequest去除掉,只留下headers,结果就不行了,由此判断出,axios是根据数据的不同决定header的不同。

这时候呢,我百度出来另外一个解决办法,就是使用qs框架
由于axios默认使用application/json格式来提交数据的,但是我想用application/x-www-form-urlencoded来提交数据,就得用到qs框架咯…emmmm…

Qs使用步骤:
1.安装qs,首先cmd开起来,cd到你的项目根目录,执行以下命令

npm install qs

在这里插入图片描述
然后呢,静静等待安装完毕即可…

2.在main.js中进行导入qs,交给vue进行使用

import qs from 'qs'
Vue.prototype.$qs = qs;

3.开始使用测试咯…
application/x-www-form-urlencoded格式提交:

this.$axios.post("logistics/addressLibary/updateSalesReturnAddress",this.$qs.stringify({
            addressTheLibaryId: row.id
          })).then((rsp) => {
            
          });

在这里插入图片描述
完成提交…

application/json提交(无需使用qs进行处理)

let data = this.form;
        data.addressVOList = [];
        data.addressVOList.push({code: this.form.country});
        data.addressVOList.push({code: this.form.city});
        data.addressVOList.push({code: this.form.province});
        data.addressVOList.push({code: this.form.county});

        this.$axios({
          method: 'post',
          url: "logistics/addressLibary/add",
          data:data,
        }).then((rsp) => {

        });

在这里插入图片描述
完成提交…

示例中的提交数据自行更改…

Logo

前往低代码交流专区

更多推荐