Home  >  Q&A  >  body text

javascript - vue routing navigation causes stack overflow, but I don't know where the infinite loop is. I'm asking for help from an expert to look at the code.

router.beforeEach((to, from, next) => {
  nProgress.start()
  console.log(store.getters.token)
  if (store.getters.token) {
    console.log(store.state.token)
    if (!store.getters.role) {
      console.log(store.getters.role)
      reqData.req({
        apiName: 'getUser'
      }).then(res => {
        res  = res.data
        if (res) {
          if (res.code === '200') {
            console.log(res)
            let data = res.data
            let routes = addRoutes[data.role]
            store.commit('SET_NAME', data.name)
            store.commit('SET_ROLE', data.role)
            store.commit('SET_AVATAR', data.avatar)
            router.addRoutes(routes)
            next(to.path)
          } else {
            this.$message({
              showClose: true,
              message: res.message,
              type: 'warning'
            })
          }
        }
      }).catch(err => {
        console.log(err)
      })
    } else {
      next()
    }
  } else {
    next('/login')
    nProgress.done()
  }
})

Error message:

The problem now is that the first time I enter, there is an endless loop. My token is null at first. I should go directly to the login page, but it is an endless loop. Please help me, experts. Thank you very much!

滿天的星座滿天的星座2686 days ago1472

reply all(3)I'll reply

  • 仅有的幸福

    仅有的幸福2017-06-12 09:32:11

    next('/login') will always be executed. For example, if you go to / and find that there is no token, then adjust to /login, and then enter your beforeEach and find that there is still no token, continue. login. It will keep logging in. . .

    reply
    0
  • 黄舟

    黄舟2017-06-12 09:32:11

    I guess this router.beforeEach also judges your '/' route, so that no matter which route you enter, a judgment will be triggered

    reply
    0
  • 学习ing

    学习ing2017-06-12 09:32:11

    I don’t have this route

    reply
    0
  • Cancelreply