Reputation: 7145
I took the back-end response token and store it in store.js
as a state.
How do I pass that token value to the main.js
? I do want to attach it to the Authorization header. This is my code.
store.js
state:{
idToken:"a sample id token"
}
main.js
axios.defaults.headers.common['Authorization']=
How do I pass that token value to the Authorization header. Thank you.
Upvotes: 1
Views: 1699
Reputation: 348
@Shubham Patel You should watch changes of the returnToken. Then, do hearder reset in the watcher. The token refreshing should also be made with mutations. Maybe something like:
Main.js:
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters([
'returnToken'
])
},
watch: {
returnToken(newToken) {
this.$axios.defaults.headers.common['Authorization'] = newToken
}
}
}
Store.js:
export default new Vuex.Store({
state: {
idToken:"a sample id token"
},
getters: {
returnToken: state => {
return state.idToken
}
},
mutations: {
updateToken(state, {token}) {
state.idToken = token
}
}
})
Then somewhare else:
let token = await loadToken()
store.commit('updateToken', {token})
Upvotes: 1
Reputation: 3289
You can write a getter in Vuex which will return your current authentication token.
const store = new Vuex.Store({
state: {
idToken:"a sample id token"
},
getters: {
returnToken: state => {
return state.idToken
}
}
})
Then import the getter using
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters([
'returnToken'
])
}
}
Then write
axios.defaults.headers.common['Authorization']=this.returnToken()
Upvotes: 0