Working with axios interceptors when sending many ajax requests

I am using Larave + JWT and vue2 + vuex2 + axios

Therefore, when the user logs in, I save the authentication token in the vuex repository. When the token expires, I need to update it. To update it, I need to send the same token to the route /refreshand get a new token. At least the way I received it, and actually it works.

The problem is that the interceptor catches 401 responses and tries to update the token, but what if, say, in my component I send a lot of requests with an expired token? Because ajax requests are asynchronous, interceptor code is executed many times. So I got a lot of update requests. After updating the source token, it is considered invalid. When the interceptor tries to update the wrong token server, it responds to an error, and I am redirected to the login page.

Here is the code:

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);
});
+4
source share
1 answer

, , . , Auth0, .

SO, .

, - . , , - UX.

0

Source: https://habr.com/ru/post/1673447/


All Articles