2016-02-13 63 views
1

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

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}); 
    } 

    }) 


})); 

我搜索对谷歌某些文档,人们通常在连接使用 '闪光()' -flash模块,但我认为这个模块需要重新加载页面,这不是我想要的,所以请帮助我,让我知道是否有更好的方法。谢谢。

回答

2

而不是直接插入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); 
}); 
+1

+1(我认为这种分离值得关注的是最好在具有护照中间件处理响应直接) – robertklep

+0

如果我将代码更改为喜欢你的代码,我认为我不能使用不同的故障处理程序。不是吗?如果邮件是2种('错误密码'),('该ID不存在'),我无法使用它。但是只能处理('用户不存在'),因为它确定存在或不存在通过护照策略的“用户对象”。对? – Juntae