Vue-Router Guards返回404而不是重定向

时间:2019-06-19 20:47:21

标签: javascript vue.js vue-router

因此,我正在建立一个将authentificationtokens结合使用的网站。我使用beforeEach()中的vue-router函数来检查令牌是否有效。一切正常,直到我误删了package.json。我试着用我记得的所有依赖关系创建另一个(无论如何它们并没有太多),但是现在当我尝试LoginLogout时,而不是将我重定向到主页或注册页面,则会返回错误的404 Not Found页。

我观察到的一件事是它使我登录,我看到我一个人进入主页后。但是它应该重定向我..不会返回404错误。.

有人知道我可能遇到什么问题吗?

这是我的Vue-Router代码:

import Vue from "vue";
import Router from "vue-router";
import Home from "./components/Home.vue";

Vue.use(Router);

let router = new Router({
    mode: "history",
    base: process.env.BASE_URL,
    routes: [
        {
            path: "/",
            name: "home",
            component: Home
        },
        {
            path: "/login",
            name: "login",
            component: () =>
                import("./components/Login.vue"),
            meta: {
                requiresGuest: true
            }
        },
        {
            path: "/register",
            name: "register",
            component: () =>
                import("./components/Register.vue"),
            meta: {
                requiresGuest: true
            }
        },
        {
            path: "/add-match",
            name: "add-match",
            component: () =>
                import("./components/AddMatch.vue"),
            meta: {
                requiresAuth: true
            }
        },
        {
            path: "/show-matches",
            name: "show-matches",
            component: () =>
                import("./components/ShowMatches.vue"),
            meta: {
                requiresAuth: true
            }
        }
    ]
});

// Nav Guards

router.beforeEach((to, from, next) => {
    // Check for requiredAuth guard
    if(to.matched.some(record => record.meta.requiresAuth)) {
        // Check if NOT logged in
        if(!localStorage.token) {
            next({
                path: '/login',
                query: {
                    redirect: to.fullPath
                }
            })
        } else {
            next();
        }
    } else if(to.matched.some(record => record.meta.requiresGuest)) {
        // Check if logged in
        if(localStorage.token) {
            // Go to login
            next({
                path: '/',
                query: {
                    redirect: to.fullPath
                }
            })
        } else {
            next()
        }
    } else {
        // Proceed to route
        next()
    }
})

export default router;

谢谢。

0 个答案:

没有答案