登录时,我想使用 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
函数中,登录后我检查用户的角色(在我的情况下保存在 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上测试它