2016-09-16 163 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