VUE axios 发送 form data 数据请求

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'
 
一、设置单个的POST请求为 Form Data 格式
axios({
   method: 'post',
   url: 'http://localhost:8080/login',
   data: {
      username: this.loginForm.username,
      password: this.loginForm.password
   },
   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'
    }
})

主要配置两个地方,transformRequest 方法进行数据格式转换, Content-Type 值改为 'application/x-www-form-urlencoded'

二、全局设置POST请求为 Form Data 格式

因为像上面那样每个请求都要配置 transformRequest 和 Content-Type 非常的麻烦,重复性代码也很丑陋,所以通常都会进行全局设置。具体代码如下

import axios from 'axios'
import qs from 'qs'

// 实例对象
let instance = axios.create({
  timeout: 6000,
  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)
)

就是我们在封装 axios 的时候,设置请求头 Content-Type 为 application/x-www-form-urlencoded。 然后在请求拦截器中,通过 qs.stringify() 进行数据格式转换,这样每次发送的POST请求都是 Form Data 格式的数据了。 其中 qs 模块是安装 axios 模块的时候就有的,不用另行安装,通过 import 引入即可使用。

猜你喜欢

转载自www.cnblogs.com/similar/p/10680228.html