加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 02:55:55 所属栏目:百科 来源:网络整理
导读:我使用Larave JWT和vue2 vuex2 axios 因此,当用户登录时,我将身份验证令牌存储在vuex存储中.当令牌过期时,我需要刷新它.为了刷新它,我需要将相同的令牌发送到/ refresh路由,并获得一个新令牌.至少我是如何得到的,实际上它是有效的. 问题是拦截器捕获401响应
我使用Larave JWT和vue2 vuex2 axios

因此,当用户登录时,我将身份验证令牌存储在vuex存储中.当令牌过期时,我需要刷新它.为了刷新它,我需要将相同的令牌发送到/ refresh路由,并获得一个新令牌.至少我是如何得到的,实际上它是有效的.

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

这是代码:

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);
});

解决方法

我认为你必须改变你刷新令牌的方法.像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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读