Alexxosipov
Alexxosipov

Reputation: 1244

How to update axios default header from interceptors?

I have the following code whitch refreshes JWT auth token:

axios.defaults.headers.common["Authorization"] = 'Bearer ' + jwt.getToken();

axios.interceptors.request.use((config) => {
  let originalRequest = config
  if (jwt.isTokenExpired() && api.unauthPaths.indexOf(config.url) == -1) {
    return api.refreshToken()
      .then(res => {
        if (res.data.error == 'TOKEN_BLACKLISTED' && res.headers.authorization) {
          let token = res.headers.authorization.slice(7)

          console.log(`Current token: ${ axios.defaults.headers.common["Authorization"]}`)
          axios.defaults.headers.common["Authorization"] = 'Bearer ' + token;
          //in this log token is new, but each next request uses the old token
          console.log(`New token: ${ axios.defaults.headers.common["Authorization"]}`)
          alert('token was refreshed')
          return Promise.resolve(originalRequest)
        } else {
          jwt.destroyToken()
          jwt.destroyExpiredTime()
          store.dispatch('auth/destroyToken')
          router.push({name: 'login'})
          return Promise.reject()
        }
      })
  }
  return config
}, (err) => {
  return Promise.reject(err)
})

I need to update the token when I get a new one from the server. But when I use

axios.defaults.headers.common["Authorization"] = 'Bearer ' + token; 

In code above, axios does not change the default token to new. Each next request comes with an old token. How to set a new token from the axios interceptors?

Upvotes: 2

Views: 1607

Answers (1)

TimeParadox
TimeParadox

Reputation: 318

You have probably already fixed this issue. But for people that also face this issue here is the solution:

if this is your original request. it also uses the original headers

const originalRequest = error.config

you have to change them when you receive your new token:

originalRequest.headers.Authorization = `Bearer ${res.token}`

however you also have to set the default headers again for future calls:

axios.defaults.headers.common["Authorization"] = `Bearer ${res.token}`

Upvotes: 3

Related Questions