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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With