I've created axios interceptor which is responsible for adding token before every request is send to my rest API.
import axios from 'axios';
import { store } from '../store/store';
export default function execute() {
axios.interceptors.request.use(function(config) {
const token = store.state.token;
if(token) {
config.headers.Authorization = `Bearer ${token}`;
console.log(config);
return config;
} else {
console.log('There is not token yet...');
return config;
}
}, function(err) {
return Promise.reject(err);
});
}
As you can see in line 2 I'm importing vuex storage and this is actually place where my token is deposited. In line 8 I'm actually adding this token to config
object and then in next line I'm consoling it out.
It is executed in my main.js file like so:
import interceptor from './helpers/httpInterceptor.js';
interceptor();
The token is present in config object which I see in my console (because i consoled config
object):
It runs every time that I make some request to rest API as expected. If token exist (after login) it should add token header to every request. Unfortunately it doesn't add it although it is present on config object which makes me a bit confused.
It doesn't actually add token to real request as I can see in network tab:
This screenshot is of course taken after login so the token is already in vuex storage and it consoled out config (part of interceptor) after I executed logout function (which call rest API).
In result I have 400 (Bad request) status in response from my rest API because I didn't sent token.
EDIT!!!
I was thinking what can I add to this question to make it better. I think that this is impossible to create demo plunker so I decided to create little repository demo which you can download and see issue for your eyes. I hope it'll help to solve the problem!