Ad

Add Header Token To Axios Requests After Login Action In Vuex

- 1 answer

after building login system with laravel pasport i want to Add header token to axios requests but axios.defaults.headers.common["Authorization"]= "Barearnull" any help!!! What am I doing wrong? this the code in ProjectEmploye.vue :

created(){
  axios.defaults.headers.common["Authorization"] = "Bearer" + 
   localStorage.getItem("member_token");
  this.$store.dispatch('currentUser/getUser');
 }
computed:{
  currentUser:{
        get(){
return    this.$store.dispatch('currentUser/getUser');
  }
  }

 },

and this is CurrentUser.js:

import axios from "axios";

 const state ={
 user:{

 }

 };
 const getters= {};
  const actions = {
 getUser(){
    axios.post("api/userauth")
    .then(response=>{
  commit('setUser',response.data);
    });
 },
loginUser({},user){
   axios.post("/api/login",{
       email: user.email,

       password: user.password
   })
   .then(response=>{
       console.log(response.data);
      if( response.data.acces_token){
           //save token mte3na fi locoal storage
           localStorage.setItem(
               "membre_token",
               response.data.acces_token
           )

           window.location.replace("/home");
       }

   })
   }
};
const mutations={
setUser(state,data){
    state.user=data;
}
};

export default{
namespaced:true,
 state,
 getters,
 actions,
mutations
}
Ad

Answer

You're importing different instances of axios in different components. You should import a single one and stick to it. Better use it globally. Here's a demo:

// in your root app.js file

// import axios
window.axios = require('axios')

// then set it up; you can also set it when component is mounted within mounted() { ... } 
axios.defaults.headers.common["Authorization"] = "Bearer " + localStorage.getItem("member_token");

Then when you want to use it in another script access it without importing it:

// in any other component, child of app.js

axios.post("/api/login", {
    email: user.email,
    password: user.password
})
Ad
source: stackoverflow.com
Ad