Token Authorization header with passport in vue.js

Where can i put the Authorization header token in axios after dispatching login action with laravel passport authentication in a seprated vue.js project?I tried with setting it in main.js like this and doesnt work properly. After dispatching, In the QuestionIndex component, the axios call dont have the authorization header automatically. And by refreshing the page, it has the authorization header. I can fix this by putting the token header in QuestionIndex Component. But I dont think this is a proper way to do it. Please help me with this problem.
In main.js

const token = localStorage.getItem('access_token');
if (token) {
  axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}

In login.vue
login(){
             this.$store
                .dispatch("login", this.form)
                .then(() => {
                    this.$router.push({ name: "QuestionIndex" });
                })
                .catch(err => {
                    
                    console.log(err);
                });
        }

In vuex store
  state: {
        token: localStorage.getItem('access_token') || null,
        user: {},
    },
    mutations: {
        setToken(state, data) {
            state.token = data.token;
            state.user = data.user;
        },
       
    },
    actions: {
       
        login({ commit }, credentials) {
            return axios.post("http://127.0.0.1:8000/api/login", credentials).then(( res ) => {
                localStorage.setItem('access_token', res.data.data.token);
                commit("setToken", res.data.data);
            });
        },
    },
    getters: {
        token: (state) => state.token,
    
    }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can set the Authorization header after initializing the axios instance like this:

axiosInstance.interceptors.request.use((config) => {
  const token = localStorage.getItem('access_token');
  config.headers.Authorization = `Bearer ${token}`

  return config
})

In your VUEX action, make sure to use the axiosInstance you created in your main.js (or whereever). If you just import axios in your VUEX store like this import axios from 'axios' it will not work, because it’s not the axios instance you set the header on.

Method 2

you can try this

axios.post("http://127.0.0.1:8000/api/login", credentials, { headers: { Authorization: 'Bearer ' + localStorage.getItem('access_token') } })


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x