护照节点validation成功

我正在执行护照authentication到我的节点应用程序,我不明白为什么需要redirect之前,我可以访问响应(res)属性?

app.get('/api/loginFailure', function(req, res) { res.status(401).json({message: 'Login Failed', success: true}); }); app.get('/api/loginSuccess', function(req, res) { res.status(200).json({message:'Welcome!', success: true}); }); // process the login form app.post('/api/login', passport.authenticate('local-login', { successRedirect: '/api/loginSuccess', failureRedirect: '/api/loginFailure'})); 

正如你所看到的,我使用successRedirect来访问不同的路由,以发回一个JSON响应。 我不希望节点apiredirect实际的应用程序,因为它的意图是不可知的前端。

本地login策略如下。 我怀疑我的困难可能在于我如何从方法中回来;

  passport.use('local-login', new LocalStrategy({ // by default, local strategy uses username and password, we will override with email usernameField: 'email', passwordField: 'password', passReqToCallback: true // allows us to pass back the entire request to the callback }, function(req, email, password, done) { // callback with email and password from our form // find a user whose email is the same as the forms email // we are checking to see if the user trying to login already exists User.findOne({ 'local.email': email }, function(err, user) { // if there are any errors, return the error before anything else if (err) return done(err); // if no user is found, return the message if (!user) { return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash } // if the user is found but the password is wrong if (!user.validPassword(password)) { return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata } // all is well, return successful user return done(null, user); }); })); 

我打算删除所有的Flash数据,什么不是,但现在只要能够将2个额外的APIpath折叠到/ api /login将是伟大的。

我无法理解为什么在访问响应(res)属性之前需要redirect?

如果您检查了护照文档 ,而不是从本指南中复制您的代码(这是另一种使用types),那么您将发现它并不总是需要redirect。

您也可以按以下方式使用它:

 app.post('/login', passport.authenticate('local'), function(req, res) { // If this function gets called, authentication was successful. // `req.user` contains the authenticated user. res.redirect('/users/' + req.user.username); } );