axios发送formdata请求

发布于 2 年前 作者 phonegap100 540 次浏览 来自 分享

axios 默认是 Payload格式数据请求,但有时候后端接收参数要求必须是 Form Data 格式的,所以我们就得进行转换。

Payload和Form Data的主要设置是根据请求头的 Content-Type 的值来的

Payload    Content-Type: ‘application/json; charset=utf-8’

Form Data   Content-Type: ‘application/x-www-form-urlencoded’

实现方法:

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)
)
回到顶部