Nuxt.js 基于角色的中间件重定向

Nuxt.js middleware redirect based on role

登录时,我想使用 nuxt.js 中间件根据角色重定向到不同的页面。

这是我的 notAuthenticated 中间件

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

中测试它