使用axios interceptors后无法修改header的坑与解决方法

一、问题描述

最近需要修改vue项目的一个调用后台接口的方法,增加header参数。

样例如下:


//引入了一个自己封装的发送请求方法

import http from '@utils/http'

//header多传一个userId

  return http.get(`/xxx/user`, {
    headers: {
      userId: `${userId}`,
    },
  }).then(res => {
    return res.data
  })

结果,按F12查看,请求头header里就是没有带上userId,很奇怪。

二、排查过程

1.查看自己写的那个项目名/src/utils/http.js文件,发现里面用到了axios interceptors,如下:

import axios from 'axios'

const instance = axios.create({})

instance.interceptors.request.use(
  config => {

    console.log("修改前",config.headers)

    config.headers = {
      language: 'zh',
    }

    console.log("修改后",config.headers)

    return config
  },
  error => Promise.reject(error)
)

2.可以看到,这个拦截器方法对header进行了处理;于是本人想到先加2个console.log,看看传入的userId在哪里,能不能想办法写到这个方法里。

3.结果发现,修改前修改后这2个console.log的结果居然一样,并且都没有我传入的userId,就很奇怪。

4.测试,把这个注释掉:

   // config.headers = {
   //   language: 'zh',
   // }

再用F12看,发现,这样就能找到自己传入的userId了。

三、解决方法

找到了传入的userId,然后就好办了。
把上方代码修改如下:

    config.headers = {
    ...config.headers,
      language: 'zh',
    }

这样发送给后台的参数,就可以带上自己传入的header了。

四、总结

1.axios interceptors方法中,console.log打印位置不分先后,不能只看console.log。

2.需要注意header的覆盖顺序,key相同的话不会累加、会覆盖。

(1)如果这样写:

  return http.get(`/xxx/user`, {
    headers: {
      userId: `abc`,
    },
  })
    config.headers = {
    //这个放第一个
    ...config.headers,
    
      userId: 'interceptors',
    }

这样,最终header传的是userId:interceptors

(2)如果这样写:

  return http.get(`/xxx/user`, {
    headers: {
      userId: `abc`,
    },
  })
    config.headers = {
      userId: 'interceptors',
      
      //这个放第二个
    ...config.headers,
    }

这样,最终header传的是userId:abc

猜你喜欢

转载自blog.csdn.net/BHSZZY/article/details/129161254
今日推荐