Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios Intercept not applying token from localStorage on first call

So I have a problem with my Vue application, where my axios intercept doesn't apply the authorization token.

axios.interceptors.request.use(config => {
  let token = localStorage.getItem("jwt_token")
  console.log("Token is: ", token)
  console.log(typeof token)
  if (token) {
    axios.defaults.headers.Authorization = `Bearer ${token}`
    }
  console.log(config)
  return config
});

As you can see I've console logged my Token, before applying it to the Auth header, however this is what I get in my console log.

On the first request the token prints just fine, but inside the header, it's set as null and I get a 422 response

on the second API request, my token applies just fine, and I receive data back.

like image 216
Ollie Avatar asked Nov 26 '18 05:11

Ollie


1 Answers

At this stage, the config object passed to your interceptor has already been merged with the defaults so assigning the token to axios.defaults.headers.Authorization isn't going to affect the current request's config.

With that in mind, all you need from your interceptor is...

config => {
  let token = localStorage.getItem("jwt_token")
  config.headers = Object.assign({
    Authorization: `Bearer ${token}`
  }, config.headers)
  return config
}

I've used Object.assign() with the current headers last so as not to overwrite any existing Authorization header.

like image 75
Phil Avatar answered Nov 06 '22 16:11

Phil