Reputation: 7195
Whenever I try to load / refresh my app via a deeplink the router code fires first. And fails because the authetication token has not been set yet... I assume that the beforeCreate
of the app should be the first thing to be executed.
The browser console displays:
router beforeEnter
app beforeCreate
Router code:
...
const router = new VueRouter({
routes: [{
path: '/article/:articleId',
name: 'article',
component: Article,
beforeEnter (to, from, next) {
console.log('router beforeEnter')
// Load stuff from backend with axios
}
}]
}
Application startup code
...
Vue.use(VueRouter)
import router from './router'
new Vue({
el: '#app',
store: store,
router: router,
beforeCreate: function() {
console.log('app beforeCreate')
// get authentication token from localStorage and put in axios header
},
render: h => h(App),
})
What am I missing here? How can I make sure the app creation code is executed first?
Upvotes: 3
Views: 777
Reputation: 2536
I think the behaviour is intended and correct. Before something get's rendered the router decides what to render.
But how to solve your problem?
First i have a persistent auth module like this:
export default {
name: 'auth',
namespaced: false,
state: {
token: undefined,
payload: undefined
},
mutations: {
clearAuth (state) {
state.token = undefined
state.payload = undefined
},
setToken (state, token) {
let payload
try {
payload = JSON.parse(atob(token.split('.')[1]))
} catch (e) {
payload = undefined
token = undefined
}
state.token = token
state.payload = payload
}
},
getters: {
token: state => state.token,
isAuthenticated: state => !!state.token,
hasRenewToken: state => !!state.payload && state.payload.renewable
}
}
Then i use vuex-persistedstate to initialise the vuex module.
import createPersistedState from 'vuex-persistedstate'
const store = new Vuex.Store({
modules: {
auth,
... // other modules
},
plugins: [
createPersistedState({
paths: ['auth']
})
]
})
Now whenever the store is created all auth informations are in the store.
And at the end i use a little wrapper for axios like this (request.js):
import axios from 'axios'
import store from '@/store'
const requestHandler = config => {
config.headers = {
'Authorization': store.getters.token
}
config.crossDomain = true
config.method = 'POST'
return config
}
const request = axios.create()
request.interceptors.request.use(requestHandler)
export default request
Now i do not import axios but request.js whereever i want to make a request.
I hope this approach helps you. At least it works for me
Upvotes: 1
Reputation: 3
Have you tried loading it before the router? AFAIK the Vue object loads everything synchronous.
new Vue({
el: '#app',
store: store,
beforeCreate: function() {
console.log('app beforeCreate')
// set authentication token in axios header
},
router: router,
render: h => h(App),
})
Upvotes: 0