axios发送header请求+参数,并转化为formdata格式

axios({
   method: 'post',
   url: 'http://localhost:8080/login',
   data: {
      username: obj.username,
      password: obj.passwd
   },
   transformRequest: [
      function (data) {
         let ret = ''
         for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
         }
         ret = ret.substring(0, ret.lastIndexOf('&'));
         return ret
      }
    ],
    headers: {
       'Content-Type': 'application/x-www-form-urlencoded'
    }
})

全局使用:

import axios from 'axios'
import qs from 'qs'
 
// 实例对象
let instance = axios.create({
  timeout: 3000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
 
// 请求拦截器
instance.interceptors.request.use(
  config => {
    config.data = qs.stringify(config.data) // 转为formdata数据格式
    return config
  },
  error => Promise.error(error)
)


版权声明:本文为weixin_46972395原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。