如何在通行证策略中使用res.send?

How to use res.send in passport strategy?

我正在尝试使用 passport.js 进行 Node.js ajax 身份验证,我想在 /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上搜索了一些文档,人们通常在connect-flash模块中使用'flash()',但我认为这个模块需要重新加载页面,这不是我想要的,所以请帮助我,让我知道是否有更好的方法。谢谢。

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

您可以在路线中做类似的事情 handler/controller(这直接取自 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);
});