zoukankan      html  css  js  c++  java
  • 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 引入即可使用。

  • 相关阅读:
    第二十二节:类与对象后期静态绑定对象和引用
    WePHP的表单令牌验证
    第二十一节:类与对象对象的比较类型约束
    Windows下 C++ 实现匿名管道的读写操作
    Mongoose 利用实现HTTP服务
    C++ Qt 框架静态编译 操作记录
    使用Qt框架开发http服务器问题的记录
    把CMD下的color 方案遍历一遍
    C++学习笔记
    在1~10的整数范围随机5个不重复的整数
  • 原文地址:https://www.cnblogs.com/similar/p/10680228.html
Copyright © 2011-2022 走看看