代码之家  ›  专栏  ›  技术社区  ›  Steven

使用登录名发送404的页面

  •  0
  • Steven  · 技术社区  · 7 年前

    我的问题是当我开始使用 router.beforeEach() 路由器。beforeach() 用于检查用户是否已登录。是缺少什么,还是出了什么问题?

    router.js

    let router = new Router({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [
        {
            path: '/',
            name: 'login',
            component: () => import('./views/Login.vue'),
            meta: {
                layout: "empty"
            },
        },
        {
            path: '/home',
            name: 'home',
            component: () => import('./views/Home.vue'),
            meta: {
                requiresAuth: true
            }
        },
        {
            path: '/404',
            name: '404',
            component: () => import('./views/404.vue'),
            meta: {
                layout: "empty"
            },
        },
        {
            path: '*',
            redirect: '/404'
        },
        {
            path: '/*',
            redirect: '/404'
        }
    ]
    });
    
    router.beforeEach((to, from, next) => {
        const isLoggedIn = JSON.parse(localStorage.getItem('UH'));
        console.log(isLoggedIn);
        const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
        if (isLoggedIn === null){
            if (requiresAuth && !isLoggedIn.user) {
                next('/');
            } else {
                next();
            }
        } else {
            next();
        }
    });
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Simon Arruti    7 年前

    如果我很理解你的问题,当一个用户在url中输入了错误的内容并且 ,此用户被重定向到“/”而不是404。

    这是因为beforeach钩子是在路由重定向之前使用的 {path: '*', redirect: '/404'} 如果页面requireAuth为true,则重定向未登录用户的条件。

    要解决此问题,请添加以下其他条件:

    if (isLoggedIn === null){
        if (requiresAuth && !isLoggedIn.user) {
            if (!to.matched.length) {
               next('/404');
            } else {
               next('/');
            }
        } else {
            next();
        }
    
    } else {
        next();
    }