Send data back with the Passport js failureRedirect method

你。 提交于 2019-12-11 01:35:09

问题


I have a Passport js local signup strategy that makes use of the successRedirect and failureRedirect methods. The problem is, if there is an error with the signup process, Passport will simply redirect back to the signup form, with no data in the form.

app.post('/signup', passport.authenticate('local-signup', {
        successRedirect: '/signup/avatar', // redirect to the secure profile section
        failureRedirect: '/signup', // redirect back to the signup page if there is an error
        failureFlash: true // allow flash messages
    }));

I have the following condition inside my local signup strategy that will send a failure message to the user if the two provided passwords do not match.

if(req.body.password != req.body.confirm_password){
                                console.log('Passwords do not match');
                                return done(null, false, req.flash('signupMessage', 'Your passwords do not match'));
                            }

Along with the flash message, I want to send data back to the /signup route and re-populate the form with the data the user has provided.

Is there a way to send the form data back to the browser on failure?


回答1:


The answer was much simpler than I expected.

The validation should happen before the data is sent to Passport js, then if the data is not valid, the /signup template can be re-rendered and the data passed back.

The solution was in this question: NodeJS express-validator with passport




回答2:


Sorry, after our comments I understand what you're asking a little better now. You need to make use of a custom callback in your passport code. The passport site gives this example:

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});

Through a closure here, your callback has access to both the request and the response, so when you deal with your error state, you can invoke code to update the response from the originating request (e.g. pulling in the specified username or whatever it is you wish to re-populate the sign-up screen with).

http://passportjs.org/docs/authenticate



来源:https://stackoverflow.com/questions/39223723/send-data-back-with-the-passport-js-failureredirect-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!