如何在Navigation Guard中使用Vue资源

时间:2019-01-27 13:29:01

标签: javascript vue.js vuejs2

我正尝试在路由器内部使用vue-resource来通过令牌获取有关用户的信息,以保护某些路由:

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

但是尝试登录TypeError: Cannot read property 'get' of undefined时出现错误,因此我尝试解决此问题以访问虚拟机实例:

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

但是它也不起作用,所以也许我需要切换到axios来完成它?

1 个答案:

答案 0 :(得分:0)

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