我正在尝试使用 Passport.js 进行 Node.js ajax 身份验证,我想在 /login
页面中显示消息。我应该在我的 Passport 策略中使用 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 中间件。
您可以在路由处理程序/ 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);
});
我是一名优秀的程序员,十分优秀!