2016-09-16 161 views
0

我使用节点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); 
     } 
    }); 
} 

回答

0

至于你的代码去,这可能是最简单的方式 - 只需通过你的HTTP资源对象插入到DB承诺,一旦DB结果进来解决这个问题:

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"); 
    authenticate_user(res, mail, password); 
}); 
var authenticate_user = function(res, mail, password) { 
    var query = user_details.find({ 
    'Mail': mail 
    }); 
    query.exec(function(err, docs) { 
    var isValid = false; 
    if (docs.length == 0) { 
     isValid = false; 
    } 
    else { 
     isValid = (docs[0].Password == password); 
    } 
    res.json(isValid); 
    }); 
}; 
1

的“好的node.js/event driven“这样做的方式是不等

与事件驱动系统一样使用类似于几乎所有的其他功能,你的函数应该接受一个回调参数,当计算完成时它将被调用。调用者不应该等待通常意义上被“退回”的值,而是发送将处理结果值的程序:

function(query, callback) { 
    myApi.exec('SomeCommand', function(response) { 
    // other stuff here... 
    // bla bla.. 
    callback(response); // this will "return" your value to the original caller 
    }); 
} 

所以你不使用它是这样的:

var returnValue = myFunction(query); 

但是这样的:

myFunction(query, function(returnValue) { 
    // use the return value here instead of like a regular (non-evented) return value 
}); 
+0

是这个工作的回调方式是一样的使用时的承诺 - >则方法? – Matoy