我使用vue-路由器在我的系统中设置路由保护,如果用户尝试输入/login或/login/在URL中输入令牌,则将用户重定向回仪表板,如果用户没有令牌,反之亦然。
router.js
router.beforeEach((to, from, next) => {
if (to.fullPath === '/dashboard/') {
if (!store.state.authToken) {
next('/login');
}
}
if (to.fullPath === '/login/') {
if (store.state.accessToken) {
next('/dashboard');
}
}
next();
});我的问题是,如果我键入'/login‘或'/dashboard’(最后没有反斜杠),它就会绕过我的保护,所以我尝试在代码中执行(to.fullPath === '/login/' || '/login')和(to.fullPath === '/dashboard/' || '/dashboard'),这在4个小时前是成功的。
然后我现在回来了,现在它给了我错误,每当我通过URL更改视图时都会说[vue-router] uncaught error during route navigation。
我不知道它为什么停止工作,请帮帮忙。
谢谢!
编辑:我做了一个错误,并调用accessToken而不是authToken,这就是守卫失败的原因。修好了,谢谢!
发布于 2019-10-16 09:59:16
你可以给你的路线一个名称和重定向的基础上,而不是。
一个额外的更改可能是在路由中添加一些元,不管路由是否需要对用户进行身份验证,这样可以更容易地进行扩展,而不必在beforeEach中指定每个受保护的路由。
路线
{
path: '/login',
name: 'login',
component: () => import('./views/Login.vue'),
meta: { requiresAuth: false }
},
{
path: '/dashboard',
name: 'dashboard',
component: () => import('./views/Dasboard.vue'),
meta: { requiresAuth: true }
}守卫
router.beforeEach((to, from, next) => {
/* Both '/login' and '/login/' should share the same route name even if their path is different */
if (to.name === 'login') {
if (store.state.accessToken) {
next('/dashboard');
}
}
//Redirect to login if the route requires auth and no token is set
if(to.meta.requiresAuth) {
if (!store.state.accessToken) {
next('/login');
}
}
next();
});发布于 2019-10-15 17:59:43
只需使用startsWith而不是===进行比较:
if (to.fullPath.startsWith('/dashboard') {...这样你就不用担心后面的斜线,等等。
https://stackoverflow.com/questions/58400151
复制相似问题