我使用节点js $ http来处理http post请求,通过邮件和密码使用DB(mongoDB)对用户进行身份验证。HTTP POST请求不与数据库请求同步
问题是数据库查询需要时间,因此不会与http调用同步。我用req == undefiend返回http,因为我没有等待(承诺或类似的东西,到数据库查询完成)。
由于我是新来的JS和节点JS,我会很感激,如果有人可以帮我修复我的代码。谢谢!
重要:如果我会直接从内部函数发送包含true或false值的req,它将起作用 - >我知道!但是..我希望它以更通用的方式写入 - 我希望http逻辑不涉及数据库逻辑。
app.post('/authenticate_user', function(req, res){
var mail = req.body.Mail;
var password = req.body.Password;
res.setHeader("Cache-Control", "private, no-cache, no-store, must-revalidate, max-age=0");
var isValid=authenticate_user(mail, password);
console.log("isValid-->"+isValid);
// I get undefiend since at this time the db did nor finish...
res.json(isValid);
});
var authenticate_user=function(mail, password){
var query = user_details.find({'Mail': mail});
query.exec(function(err, docs){
if (docs.length==0) {
return false;
}
else{
return(docs[0].Password==password);
}
});
}
是这个工作的回调方式是一样的使用时的承诺 - >则方法? – Matoy