如何在护照策略中使用res.send?

我正在尝试使用passport.js进行Node.js ajax身份validation,我想在/login页面中显示消息。 我应该在我的护照策略中使用res.send ,然后ajax调用成功结束将显示成功数据到其页面。 但我无法猜测如何使用res。 在战略。 请看下面的代码,

login.ejs

 <div id="messages"></div> <!-- and there is a form, when form submitted, the ajax call executed.--> <!-- ...ajax method : POST, url : /login, data: {}, success:... --> <!-- If ajax call success, get 'result' data and display it here --> 

app.js

 // and here is ajax handler // authentication with received username, password by ajax call app.post('/login', passport.authenticate('local'), function(req, res, next){ res.redirect('/'); }); // and here is passport strategy passport.use(new passportLocal.Strategy(function(userid, password, done) { Members.findOne({'user_id' : userid}, function(err, user){ // if user is not exist if(!user){ // *** I want to use 'res.send' here. // *** Like this : // *** res.send('user is not exist'); // *** If it is possible, the login.ejs display above message. // *** That's what I'm trying to it. How can I do it? return done(null, null); } // if everything OK, else { return done(null, {id : userid}); } }) })); 

我在google上search了一些文档,人们通常在连接flash模块中使用'flash()',但是我认为这个模块需要重新加载页面,这不是我想要的,所以请帮助我,让我知道如果有更好的方法。 谢谢。

您可以使用自定义callback来将req, res, next对象传递给Passport函数req, res, next而不是直接插入Passport中间件。

您可以在路由处理程序/控制器中执行类似的操作(直接从Passport文档中获取):

 app.post('/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); });