【发布时间】:2019-08-31 09:15:26
【问题描述】:
我正在设置一个 laravel、vue 项目,并且我正在为用户 authentication 使用 JWT auth。我正在尝试使用 Vue Router 保护路由,它正在从本地存储中获取令牌,并向真实用户提供对特定路由的访问权限,但是如果我单击任何其他路由或刷新它会将我重定向到的页面,则一旦在另一条路由上"/login" 页面。令牌始终保持不变,但它正在考虑令牌,因为用户不是真实的。请帮忙,因为我是 laravel 和 vue 的新手
我尝试过使用元信息,但效果不佳。此外,我尝试从本地存储中删除令牌并再次创建它,但对我没有任何作用。
routes.js 文件
export const routes = [
{
path: '/', component: Home, name: 'home'
},
{
path: '/dashboard', component: Dashboard, name: 'dashboard', meta:{requiresAuth: true}
},
{
path: '/login', component: Login, name: 'login'
}
];
App.js 文件
import VueRouter from 'vue-router';
import { routes } from './routes.js';
window.Vue = require('vue');
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
routes
});
router.beforeEach((to, from, next) => {
console.log(to)
if (to.meta.requiresAuth) {
const authUser = JSON.stringify(window.localStorage.getItem('usertoken'))
if(authUser && authUser.accessToken){
console.log("here")
next();
}else{
next({name: 'login'});
}
}
next();
});
const app = new Vue({
el: '#app',
router
});
我希望输出类似于当用户是真实的并且router.beforeEach 方法找到一个令牌时,用户可以到达任何路线,直到令牌被删除或更改。此外,每次单击<router-link> 或刷新页面时,不应将用户带到'/login'。
【问题讨论】:
-
你不应该在你的
beforeEach函数中使用JSON.parse而不是JSON.stringify吗? -
@DelenaMalan 我以前用过
JSON.parse,但它给了我SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data",但它没有运行。 -
听起来您没有正确存储
usertoken值。您能否将存储令牌的代码添加到您的问题中? -
@DelenaMalan 我只是想解决它,现在它正在工作......问题出在
if(authUser && authUser.accessToken)行。我添加了authUser.accessToken作为未满足的条件,因此每次点击都会重定向。我删除了该条件并留下了if(authUser),现在它运行良好。
标签: php laravel vue.js jwt vue-router