'Axios is not being able to add/update header in the request interceptor

In the main.js of my Vue based SPA, I have the following snippet:

let token = localStorage.getItem('token');

if (token) {
Vue.prototype.$http.defaults.headers.common['Authorization'] = 'Bearer ' + token;

Vue.prototype.$http.interceptors.request.use(function (config) {
  if (! config.url.includes('/update')) {
    store.dispatch('auth/getToken').then(newToken => {
      token = newToken;
      config.headers.Authorization = 'Bearer ' + newToken;
      return config;
    });
  }
  return config;
}, function (error) {
      // Do something with request error
      return Promise.reject(error);
    });
}

In the snippet above, I check to see if there is a token and if so, I add the Authorization header globally.

And I also added a request interceptor that retrieves a new token and attempts to add the new token to the auth header for the intercepted request. But the intercepted request still has the old token in its header.

To give you a clear idea, here is what I am trying to achieve:

  • I make an HTTP request to endpoint /foo
  • I intercept that request
  • If the requested url is not /update then before hitting /foo I want to make an http request to /update and make some changes to the original headers that were intended for the intercepted request (/foo). Once the headers are modified, only then do I actually want to hit /foo.

But my interceptor is not working as I want it to. Modifications in the config are not affecting the intercepted request. What am I doing wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source