ajax - 发送许多ajax请求时处理axios拦截器

标签 ajax vue.js vuejs2 axios vuex

我使用 Larave+JWT 和 vue2 + vuex2 + axios

因此,当用户登录时,我将身份验证 token 存储在 vuex 存储中。当 token 过期时,我需要刷新它。为了刷新它,我需要将相同的 token 发送到 /refresh 路由,并获得一个新 token 。至少我是这样得到它的,而且它确实有效。

问题是拦截器捕获了 401 响应并尝试刷新 token ,但是如果在我的组件中我发送了许多带有过期 token 的请求怎么办?由于 ajax 请求是异步的,因此拦截器代码会运行多次。所以我收到了很多刷新请求。一旦初始 token 被刷新,它就被认为是无效的。当拦截器尝试刷新无效 token 时,服务器响应错误,我重定向到登录页面。

代码如下:

axios.interceptors.response.use((response) => {
  return response;
}, (error) => {
  const originalRequest = error.config;

  if (error.response.status === 401 && !originalRequest._retry) {
    originalRequest._retry = true

    axios.post('auth/refresh').then((response) => {
      let token = response.data.token

      store.dispatch('auth/setAuthToken', token)

      let authorizationHeader = `Bearer ${token}`

      axios.defaults.headers = { 'Authorization': authorizationHeader }
      originalRequest.headers['Authorization'] = authorizationHeader

      return axios(originalRequest)
    }, (error) => {
      store.dispatch('auth/clearAuthInfo')
      router.push({ name: 'login' })
    })
  }

  return Promise.reject(error);
});

最佳答案

我认为您必须改变刷新 token 的方法。 Auth0 等领导建议主动定期刷新以解决此问题。

Here is a SO answer他们谈论它的地方。

Set the token expiration to one week and refresh the token every time the user open the web application and every one hour. If a user doesn't open the application for more than a week, they will have to login again and this is acceptable web application UX.

关于ajax - 发送许多ajax请求时处理axios拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43081175/

相关文章:

javascript - 如何在asp.net c#中使用javascript从ajax组合框中获取选定的值

php - 通过 javascript ajax 将多个值发布到 php

javascript - $.ajax/$.get/$.POST/.load() 有什么区别?

javascript - 检测 UIWebView 中的 Javascript/Ajax 更改

javascript - 使用 vue-router 将查询绑定(bind)到 props

vue.js - Vue过滤器和 "Do not mutate vuex store state outside mutation handlers"

javascript - 如何查找多个音频文件的持续时间?

javascript - Vue.js - 如何正确有条件地设置点击处理程序代码

vue.js - vee 验证 "required"验证仅在更改字段时有效

javascript - for循环javascript中的异步数据获取