当我将用户 key 存储在本地存储中并在成功登录后将用户重定向到仪表板时,我的应用程序直到刷新后才使用存储的 key 。
这是设置 key 的代码。
axios.post(url, creds)
.then((response) => {
if (response.data.code === 401) {
context.error = response.data.data
} else {
Vue.ls.set('id_token', response.data.data.key, 60 * 60 * 1000)
this.user.authenticated = true
}
}).catch((err) => {
context.error = err.data
})
有趣的是我在 beforeEach 中有一个路由守卫,这实际上在登录后立即使用正确的值,没有刷新。
router.beforeEach((to, from, next) => {
const r = axios.create({
baseURL: env.api_url,
timeout: 25000,
headers: {
'Authorization': 'Bearer ' + Vue.ls.get('id_token'),
'X-Requested-With': 'XMLHttpRequest'
}
})
if (to.name === 'Login') {
r.get('user').then(() => {
next({name: 'Dashboard'})
}).catch(() => {
next({name: 'Login'})
})
}
if (to.name !== 'Login') {
r.get('user').then(() => {
next()
}).catch(error => {
console.log(error)
next({name: 'Login'})
})
} else next()
})
这可能是什么原因造成的?
最佳答案
感谢 JacobGoh 的评论,我设法找到了问题所在。我在 main.js 文件中创建了 axios 实例。这是我设置授权 header 的地方。当用户登录时,这不会更新。
我改为执行以下操作:
router.beforeEach((to, from, next) => {
if (Vue.ls.get('id_token') === null && to.name !== 'Login' && to.name !== 'Register') {
router.push('/login')
} else {
next()
}
})
Vue.$http.interceptors.request.use(
config => {
config.headers.Authorization = 'Bearer ' + Vue.ls.get('id_token')
return config
},
error => Promise.reject(error)
)
像魅力一样工作。
关于javascript - 登录后 Vue 应用程序不使用本地存储(vue 路由器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49463032/