Ad
Add Header Token To Axios Requests After Login Action In Vuex
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 import
ing it:
// in any other component, child of app.js
axios.post("/api/login", {
email: user.email,
password: user.password
})
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms
Ad