[英]Nuxt.js middleware redirect based on role
登錄時,我想使用 nuxt.js 中間件根據角色重定向到不同的頁面。
這是我的未認證中間件
export default function({ store, redirect }) {
// If the user is authenticated redirect to home page
if (store.state.auth) {
debugger
if (store.state.auth.role === 'admin') {
return redirect('/admin')
} else {
return redirect('/')
}
}
}
問題是它沒有重定向到/admin
並且我不知道如何調試它。 調試器在這里不起作用。
登錄后似乎中間件沒有重定向我,所以我必須在登錄完成后使用路由器並根據角色重定向。
編輯:按要求,我還添加了代碼解決方案。
在我的login
function 中,登錄后我檢查了用戶的角色(在我的情況下,它保存在 JWT 令牌中)。
login(data) {
const self = this
this.$axios.post('/auth/login', data).then(function(response) {
const tkData = self.parseJwt(response.data.Token)
const auth = {
accessToken: response.data.Token,
email: tkData.email,
role: tkData.role
}
self.$store.commit('setAuth', auth)
Cookie.set('auth', auth)
if (tkData.role === 'admin') {
self.$router.push('/admin')
} else {
self.$router.push('/')
}
})
}
PS:您可以查看我的代碼並在我的GitHub中進行測試
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.