[英]Nodejs - How to route by name in url with express and mongoose?
[英]NodeJS Express/Mongoose route confusion
我一定不能正確理解這里的內容。 我的路線看起來像這樣
function(req,res){
var thingId = validate.thingId(req.body) ? req.body.thingId : res.send(400,'Invalid Thing');
var newBlock = new Block({
thing : mongoose.Types.ObjectId(thingId)
}).save();
}
我在req.body.thingId中傳入一個空字符串以測試驗證功能。 它返回應有的false,服務器將返回應有的400錯誤,但是我收到錯誤“傳遞的參數必須是12個字節的單個字符串或24個十六進制字符的字符串”。 (它在談論模型ID)。
因此,顯然仍在創建newBlock並將thingId傳遞給mongoose.Types.ObjectId函數。
我(可能是錯誤的)印象是,調用res.send本質上就像是“返回”,並且在它無法運行之后進行編碼。 我看不到這可能是一個異步問題,有人能指出我正確的方向嗎?
問題是res.send()不會從函數返回執行。 您應該使用代碼塊,如果驗證失敗,則返回。
我做了user3334561所說的,這可行。
var thingId;
if (validate.thingId(req.body)) thingId = req.body.thingId;
else return res.send(400,'Invalid Thing');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.