Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios interceptor in vue 2 JS using vuex

I store token after success login call in vuex store like this:

axios.post('/api/auth/doLogin.php', params, axiosConfig)     .then(res => {         console.log(res.data); // token         this.$store.commit('login', res.data);     }) 

axiosConfig is file where I only set baseURL export default { baseURL: 'http://localhost/obiezaca/v2' } and params is just data sent to backend.

My vuex file looks is:

import Vue from 'vue'; import Vuex from 'vuex';  Vue.use(Vuex);  export const store = new Vuex.Store({     state: {         logged: false,         token: ''     },     mutations: {         login: (state, response) => {             state.logged = true;             state.token = response;             console.log('state updated');             console.log('state.logged flag is: '+state.logged);             console.log('state.token: '+state.token);         },         logout: (state) => {             state.logged = false;             state.token = '';         }     } }); 

It is working correctly, I can re-render some of content in my SPA basing on v-if="this.$store.state.logged" for logged user. I'm able to access this.$store.state.logged from any component in my entire app.

Now I want to add my token to every request which call my rest API backend. I've created basic axios http interceptor which looks like this:

import axios from 'axios';  axios.interceptors.request.use(function(config) {     const token = this.$store.state.token;     if(token) {         config.headers.Authorization = `Bearer ${token}`;     }     return config; }, function(err) {     return Promise.reject(err); }); 

Now I have 2 problems/questions about it.

  1. I know that it is available to use this.$store.state.logged or this.$store.state.token across every component but can I use it same way in single javascript file?
  2. Where should I execute/start my interceptor javascript file? It is independent file which lays in my app main folder but I am not calling it anywhere, in angularJS which I was working before, I had to add $httpProvider.interceptors.push('authInterceptorService'); in config but I don't know how to do same thing in vue architecture. So where should I inject my interceptor?

EDIT

I followed GMaiolo tips I added

import interceptor from './helpers/httpInterceptor.js'; interceptor(); 

to my main.js file and I refactor my interceptor to this:

import axios from 'axios'; import store from '../store/store';  export default function execute() {     axios.interceptors.request.use(function(config) {         const token = this.$store.state.token;         if(token) {             config.headers.Authorization = `Bearer ${token}`;         }         return config;     }, function(err) {         return Promise.reject(err);     }); } 

Result of this changes is that every already existing backend calls ( GET ) which don't need token to work stopped working but it is logical because I didn't clarified to which request it should add token so it is trying to add it everywhere and in my interceptor something is still wrong and that is why every already exisitng request stopped working.

When I try to do backend POST call in browser console I still get this error:

TypeError: Cannot read property '$store' of undefined

Although I import store to my interceptor file. Any ideas? I can provide some more information if any needed.

I additionally add screenshot of this main, store and interceptor tree structure so you can see that I'm importing fron correct path:

path

like image 835
BT101 Avatar asked Dec 22 '17 19:12

BT101


1 Answers

1.

First of all I'd use a Vuex Module as this Login/Session behavior seems to be ideal for a Session module. After that (which is totally optional) you can set up a Getter to avoid accessing the state itself from outside Vuex, you'd would end up with something like this:

state: {   // bear in mind i'm not using a module here for the sake of simplicity   session: {     logged: false,     token: ''   }  }, getters: {   // could use only this getter and use it for both token and logged   session: state => state.session,   // or could have both getters separated   logged: state => state.session.logged,   token: state => state.session.token }, mutations: {   ... } 

With those getters set, you can get the values a bit easier from components. With either using this.$store.getters.logged (or the one you'd want to use) or using the mapGetters helper from Vuex [for more info about this you can check the getters docs]:

import { mapGetters } from 'vuex' export default {   // ...   computed: {     ...mapGetters([       'logged',       'token'     ])   } } 

2.

I like to run Axios' interceptors along with Vue instantation in main.js creating, importing and executing an interceptors.js helper. I'd leave an example so you get an idea, but, then again, this is my own preference:

main.js

import Vue from 'vue'; import store from 'Src/store'; import router from 'Src/router'; import App from 'Src/App';  // importing the helper import interceptorsSetup from 'Src/helpers/interceptors'  // and running it somewhere here interceptorsSetup()  /* eslint-disable no-new */ new Vue({     el: '#app',     router,     store,     template: '<App/>',     components: { App } }); 

interceptors.js

import axios from 'axios'; import store from 'your/store/path/store'  export default function setup() {     axios.interceptors.request.use(function(config) {         const token = store.getters.token;         if(token) {             config.headers.Authorization = `Bearer ${token}`;         }         return config;     }, function(err) {         return Promise.reject(err);     }); } 

And there you'd end up having all the behavior cleanly encapsulated.

like image 111
GMaiolo Avatar answered Sep 27 '22 20:09

GMaiolo