简体   繁体   中英

Node.js passport pass postdata on to failureRedirect

This is driving me crazy! I'm using Express 4, passport and local-passport to authenticate login and signup.

I'm using this example: https://github.com/tutsplus/passport-mongo

Problem: When the signup form does not validate (say you forgot one of the fields) and we redirect to the failureRedirect (which is the same signup page), all the entered values are gone. Not a very good user experience that you have to fill out the entire form because you messed up a single field.

How do I pass the already entered data on the the form?

I got these two routes handing the GET and POST of the form:

app.get('/signup', function(req, res){
    res.render('signup', {
        message: req.flash('message'),
    });
});

app.post('/signup', passport.authenticate('signup', {
    successRedirect: '/signup-complete',
    failureRedirect: '/signup', // need to pass the entered values (if any) back to the signup page
    failureFlash : true
}));

I have a nagging suspicion that the values are already there - I just don't know how to grab them.

I'm using Swig for the views btw.

Did you add connect-flash middleware to your app?

var flash = require('connect-flash');

app.use(flash());

Update:

When you define your local strategy, you should return the flash messages in the third parameter of the done function. Example:

passport.use(new LocalStrategy(
  function(username, password, done) {
      findByUsername(username, function(err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
        if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
        return done(null, user);
      })
    });
  }
));

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