简体   繁体   English

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

[英]Nuxt.js middleware redirect based on role

On login I want to redirect to different page based on role using the nuxt.js middleware.登录时,我想使用 nuxt.js 中间件根据角色重定向到不同的页面。

This is my notAuthenticated middleware这是我的未认证中间件

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('/')
    }
  }
}

Problem is it does not redirect to /admin and I don't know how to debug it.问题是它没有重定向到/admin并且我不知道如何调试它。 Debugger is not working here.调试器在这里不起作用。

Seems middleware didn't redirect me after login, so I had to use the router and redirect based on the role after the login has completed.登录后似乎中间件没有重定向我,所以我必须在登录完成后使用路由器并根据角色重定向。

EDIT: As asked I'm adding also the code solution.编辑:按要求,我还添加了代码解决方案。

In my login function, after logging in I check the role of the user (which in my case was saved in the JWT token).在我的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: You can check out my code and test it in my GitHub PS:您可以查看我的代码并在我的GitHub中进行测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM