Vue.js 坚持使用拦截器 body

Vue.js Persist body with interceptors

你好,我正在使用拦截器获取刷新令牌,如果我收到 401 错误

这是代码:

httpClient.interceptors.response.use(
  (response) => {
    const end = Date.now()
    console.info(`Api Call ${response.config.url} took ${end - response.config.config.start}ms`)
    return response
  },
  async (error) => {
    const originalRequest = error.config
    if (error.response.status === 401 && originalRequest.url.includes('auth/token')) {
      // Do something
      store.commit('clearUserData')
      return Promise.reject(error)
    } else if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true
      await store.dispatch('auth/refreshToken')
      return httpClient(originalRequest)
    }
    return Promise.reject(error)
  }
)

我将 API 调用的行为发送到控制台(服务器端)以尝试更好地解释,此处输出:

01|appapi  | 2021-06-29T14:24:05: PATCH: /products/60db632ad91cfa6b2200145f
02|appapi  | 2021-06-29T14:24:05: {
03|appapi  |   product: 'test',
04|appapi  |   description: 'test description',
05|appapi  |   rate: 19,
06|appapi  |   image: '/products/JV2zwoZicGEAXJW4.jpg',
07|appapi  |   category: '5f6121c306e8bc0854d9ceb3',
08|appapi  |   active: true
09|appapi  | }
10|appapi  | 2021-06-29T14:24:05: Hostname: url.api.com, IP: 192.168.1.100
11|appapi  | 2021-06-29T14:24:05: POST: /auth/token
12|appapi  | 2021-06-29T14:24:05: { token: '67cqmmt6YUAgdP3w' }
13|appapi  | 2021-06-29T14:24:05: Hostname: url.api.com, IP: 192.168.1.100
14|appapi  | 2021-06-29T14:24:05: PATCH: /products/60db632ad91cfa6b2200145f
15|appapi  | 2021-06-29T14:24:05: {}

如您所见:

我请求一个带有负载的补丁(第 01 到 09 行)
当令牌过期时,拦截器使用有效载荷刷新令牌(第 10-12 行)
当拦截器再次请求原始请求时,body 消失了(第 13-15 行)

我做错了什么?为什么 body 内容丢失了?我会感谢所有的帮助

抱歉我的英语不好

经过这么多调试,我终于找到了解决方案。问题是在请求re-executing的时候,headers都丢失了,那我就把解决方法前后的代码放在一起:

之前

const httpClient = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL_API,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  timeout: 10000,
})

httpClient.interceptors.request.use((req) => {
  req.config = {
    ...(req.config ?? {}),
    start: Date.now(),
  }
  if (req.url.includes('productos')) {
    const token = store.getters['auth/accessToken']
    req.headers = {
      Authorization: `Bearer ${token}`,
    }
  }
  return req
})

之后

我在[=中添加了接受:'application/json','Content-Type':'application/json', 32=]object

httpClient.interceptors.request.use((req) => {
  req.config = {
    ...(req.config ?? {}), // preserve a given request.config object
    start: Date.now(),
  }
  if (req.url.includes('productos')) {
    const token = store.getters['auth/accessToken']
    req.headers = {
      Authorization: `Bearer ${token}`,
      Accept: 'application/json',
      'Content-Type': 'application/json',
    }
  }
  return req
})