浅析router全局守卫之beforeEach可能导致的 infinite redirect in navigation guard 问题

1、问题背景

  路由加了全局守卫之后,报错:

2、原因:内部判断,导致路由产生了死循环

  错误代码

router.beforeEach((to, from, next) => {
    if (store.getters.token) {
      if (to.path === '/login') {
        next('/')
      } else {
        next()
      }
    } else {
        next('/login')
    }
})

3、修改后

const whiteList = ['/login']
router.beforeEach((to, from, next) => {
    if (store.getters.token) {
      if (to.path === '/login') {
        next('/')
      } else {
        next()
      }
    } else {
      if (whiteList.indexOf(to.path) > -1) {
        next()
      } else {
        next('/login')
      }
    }
})

  或者这样

router.beforeEach((to, from, next) => {
    if(Object.is(to.path,'/login')) {
        next();
        return
    }
    if (store.getters.token) {
        next()
    } else {
        next('/login')
    }
})

4、原理

  其实这算是 vue-router 的一个机制了,当我们在router.push( {‘name’ : 'login'} ) 时又重新进入了我们当前的这个router-beforEach事件里,此时又进行了tokne的判断,还是没有token,导致又走到了router.push({name:'login'}) 里,然后就是一直死循环。所以在判断之前,加了下面判断

if(Object.is(to.path,'/login')) {
  next();
  return
}

  使用全局前置守卫碰到死循环的问题,浏览器就报了 Infinite redirect in navigation guard

// 错误示范
router.beforeEach((to, from, next) => {
    next('/')
}

  这样的代码会使路由陷入死循环,不断地重复进入 根路径 又从根路径 出来的无限循环

  在实现跳转路由的时候,一定要以 next() 结尾

posted @ 2017-07-30 18:36  古兰精  阅读(1051)  评论(0)    收藏  举报