validationcaptcha以及passport.js

是否有可能在调用passport.jsvalidationfunction之前validationgoogle recaptcha是否成功?

我之间select一个或另一个之间卡住,因为都使用asynchronouscallback来validation,我不能在他们之间相互。

function verifyRecaptcha(key, rq, rs, pa, callback) { https.get('https://www.google.com/recaptcha/api/siteverify?secret=' + SECRET + '&response=' + key, function (res) { var data = ''; res.on('data', function (chunk) { data += chunk.toString(); }); res.on('end', function () { try { var parsedData = JSON.parse(data); // return true; callback(parsedData.success, rq, rs, pa); } catch (e) { // return false; callback(false, rq, rs, pa); } }); }); } app.post('/auth/signin', can_access.if_not_logged_in(), passport.setupLocalStrategy(), function (req, res) { console.log('HERE'); verifyRecaptcha(req.body['g-recaptcha-response'], function (success) { if (success) { // find a way to signal captcha succeeded. return true; } else { res.end('Captcha failed, sorry.'); // TODO: take them back to the previous page // and for the love of everyone, restore their inputs return false; } }); }, passport.authenticate('local', { successRedirect: '/', failureRedirect: 'auth/signin', failureFlash: true })); 

我想在validation码成功后进行validation

Express中间件或路由处理程序的工作方式是,它们是一个接一个地执行,只要前一个调用next()

所以你只需要从你的validation码validation中间件中调用next() ,这样你的passport.authenticate下一个中间件就可以执行了。

另外,如果你调用next(err) (即传递一个错误),它将跳过所有的中间件,直接进入具有4个参数签名(err, req, res, next)的下一个中间件,error handling程序放置在您的路由/中间件的末端或附近。

所以简单地尝试改变你的代码:

 app.post('/auth/signin', can_access.if_not_logged_in(), passport.setupLocalStrategy(), function (req, res, next) { // <<-- 1. have next passed here console.log('HERE'); verifyRecaptcha(req.body['g-recaptcha-response'], function (success) { if (success) { // find a way to signal captcha succeeded. return next(); // <<-- 2. call next(); } else { res.end('Captcha failed, sorry.'); // TODO: take them back to the previous page // and for the love of everyone, restore their inputs return false; } }); }, // this will only be invoked if next() was called from previous middleware passport.authenticate('local', { successRedirect: '/', failureRedirect: 'auth/signin', failureFlash: true }));