【问题标题】:How do I render a pug template on success and failure of authentication(passport.js) with variables from the pug template? (express, passport.js, pug)如何使用哈巴狗模板中的变量在身份验证(passport.js)成功和失败时呈现哈巴狗模板? (快递,passport.js,哈巴狗)
【发布时间】:2022-02-07 10:55:01
【问题描述】:

我正在使用 passport.js 开发登录系统,并使用 pug 模板进行表达。我正在尝试使用失败消息呈现登录页面,如果成功,我想将用户重定向回他们去过的最后一页,其中的 URL 作为隐藏输入传递到 pug 模板中。然后我想取那个隐藏输入的值并将它放在successRedirect中,但是它说req is not defined

router.post("/login", body('backurl').trim().escape(), passport.authenticate("local", {
    successRedirect: (req.body.backurl),
    failWithError: true
}), function(err, req, res, next) {
    return res.render('login', { message: 'Unable to login, the password or the username are wrong' })
}

据我了解,这是因为它没有 req,因为 req, res, next 没有功能,所以我尝试用一​​个有它的函数来包装它:

router.post("/login",
    body('backurl').trim().escape(),
    function(req, res, next) {
        passport.authenticate("local", {
            successRedirect: (req.body.backurl),
            failWithError: true
        }), function(err, req, res, next) {
            return res.render('login', {message: 'Unable to login, the password or the username are wrong'})
        }
    }
);

但它只是不断重新加载并且不起作用并且不会转到任何 URL。

任何人都可以帮我解决这个问题并将用户从隐藏的输入移动到 URL,同时使用变量渲染一个 pug 模板失败吗?

谢谢!

【问题讨论】:

    标签: javascript node.js express passport.js


    【解决方案1】:

    您可以使用 get() 请求呈现视图。 使用 post() 请求,您应该重定向,如果您想向用户显示消息,您可以使用 express-flash 包。

    router.post("/login", (req, res, next) => {
       passport.authenticate("local", (err, user) => {
            if (!user) {
              req.flash('error', { msg: 'Unable to login, the password or the username are wrong')
              return res.redirect('/login');
            }
            res.redirect(req.body.backurl);
       }
    });
    

    通过这种方式,您可以获得有关附加内容的更多详细信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 2020-04-17
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      相关资源
      最近更新 更多