我正尝试在路由器内部使用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
来完成它?
答案 0 :(得分:0)
我很确定您需要import vue-resource from 'vue-resource'