【问题标题】:How to redirect to variable link after authentication?身份验证后如何重定向到变量链接?
【发布时间】:2021-05-09 23:32:28
【问题描述】:

我正在开发一个笔记应用程序,人们可以在其中保存笔记(使用快递)。 我想添加谷歌身份验证,为此我正在使用护照。

我的失败是-

/notes/:userId  => for home page
http://localhost:8080/login/google/redirect => Authorized redirect URL

我还使用中间件isLoggedIn 来检查用户是否登录。 我的中间件代码 -

module.exports.isLoggedIn = (req, res, next) => {
if(!req.user ){
    req.flash('error', 'User must be signed-In');
    return res.redirect('/login');
}
next();

}

在此我正在检查 req 是否具有用户属性,该属性在使用 passport.autheticate() 登录时自动添加护照。 但是现在当我使用 Google 登录时,我需要使用固定的重定向 URL。那么我如何在身份验证后将用户重定向到notes/:userId。 我尝试在重定向 URL 中使用 req.redirect

router.get("/login/google/redirect", passport.authenticate('google', {failureRedirect: '/register'}), 
async (req, res) => {
    let userId = req.user._id;
    res.redirect(`/notes/${userId}`);
});

但无法通过我的中间件isLoggedIn。 我怎样才能做到这一点?

【问题讨论】:

    标签: node.js express google-cloud-platform


    【解决方案1】:

    使用 isLoggedIn 作为 /notes/:id 路由的中间件。

    router.get("/notes/:id" , isLoggedIn, async (req, res) => {
        // your logics code
    });
    

    【讨论】:

    • 我在 /notes/:id 路由本身中使用 isLoggedIn 我的问题是在固定重定向 URL 的路由中添加用户属性,我无法在其他路由中访问,即 /notes/:身份证
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 2017-11-01
    • 1970-01-01
    • 2016-05-13
    相关资源
    最近更新 更多