2

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

1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.