![](/img/trans.png)
[英]vue-router — Uncaught (in promise) Error: Redirected from "/login" to "/" via a navigation guard
[英]How to guard both '/login' or '/login/', and '/dashboard' or '/dashboard/' in vue-router
我正在使用 vue-router 在我的系統中設置 routeguard,如果用戶嘗試在 URL 中輸入 /login 或 /login/,則將用戶重定向回儀表板,反之亦然,如果他們沒有令牌。
路由器.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 這就是警衛失敗的原因。 已修復,謝謝!
您可以為您的路線命名並根據該名稱進行重定向。
額外的更改可能是向您的路由添加一些元數據,無論路由是否需要用戶進行身份驗證,從而更容易擴展,而無需在您的 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();
});
只需使用startsWith
而不是===
進行比較:
if (to.fullPath.startsWith('/dashboard') {...
這樣你就不用擔心尾部的斜杠等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.