当前位置:   article > 正文

vue-axios系列:axios拦截器,配置请求头,配置请求参数_vue请求拦截-配置置请求头参数

vue请求拦截-配置置请求头参数

axios拦截器

配置请求头

request.interceptors.request.use(
  config => {
    /**
     * 处理请求头
     * 1.token 2.防刷短信
     */
    if(token){ config.headers.Authorization= JSON.parse(token) }
    //防刷短信(pdd)
    config.headers.AcceptParam = 'application/no-referrer-urlencoded';
    return config
  }, function (error) {
    return Promise.reject(error)
  }
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

在这里插入图片描述

拦截器添加参数-方法1

注意:post请求时需要QS数据格式化,否则报错

import QS from 'qs';

request.interceptors.request.use(
  config => {
    if (config.method == 'post') {
      config.data = {
        ...config.data,
        token: '1234'
      }
      // 需要将数据格式化,否则传到后台就错了
      config.data = QS.stringify(config.data)
    }else if (config.method == 'get') {
      config.params = {
        token: '1234',
        ...config.params
      }
    }
    return config
  }, function (error) {
    return Promise.reject(error)
  }
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

拦截器添加参数-方法2

import QS from 'qs';
request.interceptors.request.use(
  config => {
    if(config.method == 'post'){
      let defaultParams = {token: '123'};
      // 默认值与接口传来的参数进行合并(注:接口参数与默认值不可重复)
      config.data = Object.assign(defaultParams, config.data);
      config.data = QS.stringify(config.data)
    }
    return config
  }, function (error) {
    return Promise.reject(error)
  }
)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/283585
推荐阅读
相关标签
  

闽ICP备14008679号