I am writing a nuxt app that authenticates with a backend. I have a http plugin that intercepts all http requests. I need to add an auth token to all requests, the token is in the store. What I want to know is, how do I access the store from the plugin?
import axios from 'axios';
var api = axios.create({
baseURL: 'http://127.0.0.1:8000/api/'
});
api.interceptors.request.use(function (config) {
config.headers = {
'Authorization': 'Bearer' + **how do access store?**
}
return config;
}, function (error) {
return Promise.reject(error);
});
export default api;
Thanks
You can try to use app store from context in plugin. Your plugin need some changes:
import axios from 'axios';
var api = axios.create({
baseURL: 'http://127.0.0.1:8000/api/'
});
export default (context, inject) => {
api.interceptors.request.use(function (config) {
config.headers = {
'Authorization': 'Bearer' + context.app.$store.state.your_path_to_token
}
return config;
}, function (error) {
return Promise.reject(error);
});
return api;
}
One more way it's create store/index.js file and import them into plugin.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.