简体   繁体   中英

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)

I am working on the login system using passport.js and express with pug templates. I am trying to render the login page with a message on failure, and if on success I want to redirect the user back to the last page they have been to, of which URL is passed as hidden input inside the pug template. I want to then take that value of that hidden input and put it inside the successRedirect<\/code> , however it says req is not defined<\/code> :

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' })
}

You can render a view with a get() request. With a post() request you should redirect and if you want to show a message to the user you could use the express-flash package.

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);
   }
});

This way you can have more details about what appened.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM