简体   繁体   中英

How to use vue-resource in navigation guard

I'm trying to use vue-resource inside my router to get info about the user by token to protect some routes:

router/index.js :

const router = new Router({
  mode: 'history',
  linkExactActiveClass: 'is-active',
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/board',
      name: 'Board',
      component: Board,
      meta: {
        requiresAuth: true
      }
    }
  ]
})

router.beforeEach((to, from, next) => {
  // check if rout requires auth
  if (to.matched.some(rec => rec.meta.requiresAuth)) {
    const token = localStorage.getItem('user-token')
    if (token == null) {
      next({ name: 'Login' })
    }
    else {
      this.$http.get('/rest-auth/user/', {headers: {"Authorization": "Token " + token}})
      .then(response => { next() }, response => { next({ name: 'Login' }) });
    }
  }
  else {
    next()
  }
})

But I'm getting error when I'm trying to log in: TypeError: Cannot read property 'get' of undefined , so I've tried to solve it like this to get access to vm instance:

router.beforeEach((to, from, next) => {
  // check if rout requires auth
  if (to.matched.some(rec => rec.meta.requiresAuth)) {
    const token = localStorage.getItem('user-token')
    if (token == null) {
      next({ name: 'Login' })
    }
    else {
      next(vm => {
        vm.$http.get('/rest-auth/user/', {headers: {"Authorization": "Token " + token}})
        .then(response => { next() }, response => { next({ name: 'Login' }) });
      })
    }
  }
  else {
    next()
  }
})

But it's not working also, so maybe i need to switch to axios to do it?

我很确定您需要import vue-resource from 'vue-resource'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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