javascript 如何在Vue.js中保护客户端路由?

x4shl7ld  于 2023-08-02  发布在  Java
关注(0)|答案(3)|浏览(97)

我现在正在构建一个spa,它使用Vue.js作为前端框架,与使用jsonwebtokens的纯JSON后端对话。我更熟悉React生态系统。我目前不确定如何在Vue.js中保护客户端路由。(这不是我的决定。我是新来的。yay!)
作为回应,我会做这样的事情。在项目的index.js文件中。在安装应用之前,检查localstorage中是否有jsonwebtoken。如果有,将redux状态设置为logged in。如果未设置为注销。
然后,我将使用更高阶的组件来保护我的路由,以便每当用户尝试输入客户端保护的路由时,我将使用componentWillMount生命周期方法来检查登录状态。如果已登录,则渲染组件。否则重定向到登录页面。
看起来,vue中的高阶组件无法实现相同的行为。或者我只是找不到文档,告诉我如何实现它。有人能和我分享一下他们是如何解决这个问题的吗?

yx2lnoni

yx2lnoni1#

documentation中所述,您可以在所有要检查身份验证的路由上使用Meta字段
文档中提供的示例:

router.beforeEach((to, from, next) => { 
    if (to.matched.some(record => record.meta.requiresAuth)) { 
        // this route requires auth, check if logged in 
        // if not, redirect to login page. 
        if (!auth.loggedIn()) { 
            next({ 
                path: '/login', 
                query: { redirect: to.fullPath } 
            }) 
        } else { 
            next() 
        } 
    } else { 
        next() // make sure to always call next()! 
    } 
})

字符串
或者对于组件导航保护,您可以按照wostex提供的第二个链接。

9bfwbjaz

9bfwbjaz2#

我想我错过了路由Meta字段的文档。我做了一些愚蠢的事情,但我想我在工作。哈哈。

router.beforeEach((to, from, next) => {
    let web = ["home", "login", "verifyAccount", "resetPassword","forgotPassword","register"];
    if(web.includes(to.name)){
        next();
    }else{
        axios.post('/api/auth/verify-token',{
            token: localStorage.token
        }).then(response=>{
            if(response.data.verification === true){
                next();
            }else{
                router.push({
                    name:'home',
                    params:{
                        serverError:true,
                        serverMsg: 'Please login to continue.'
                    }
                });
            }
        }).catch(response=> {
            console.log(response);
        });
    }
});

字符串

b4lqfgs4

b4lqfgs43#

这是一个使用Vue.js实现auth的好例子:link
更具体地说,这里是关于导航手册。防护:link

相关问题