2016-04-03 32 views
0

我正在使用Node.js對來自UI的請求進行錯誤檢查。 UI有3個輸入字段 - 大小,顏色和樣式。用戶必須選擇顏色和尺寸,但不必選擇樣式。所以錯誤檢查應該確保他們選擇顏色和大小。在Node.js中檢查錯誤時,請求未定義

if (req.query.size == 'undefined' || req.query.color == 'undefined') { 
    console.log("Did not select size or color"); 
    res.json({ 
     Error: "Must pick size and color!" 
    }); 
} else { 
    console.log(req.query.color); 
    console.log(req.query.size); 
    var selection = 'api' + req.query.size + '/' + req.query.color; 
}; 

當用戶沒有選擇顏色和大小時,它不會捕獲這個,而是轉到'其他'。在這種情況下,控制檯將打印「未定義」的顏色和大小。對於如何解決這個問題,有任何的建議嗎?

需要注意的是,如果我做

req.query.size == undefined || req.query.color == undefined 

typeof req.query.size == 'undefined' || typeof req.query.color == 'undefined' 

我在控制檯中的錯誤說「錯誤:未定義是不是一個有效的URI或選擇對象。」我注意到,在index.js,裏面傳來與節點模塊,有以下代碼:

function request (uri, options, callback) { 
    if (typeof uri === 'undefined') { 
     throw new Error('undefined is not a valid uri or options object.') 
    } 
    .... 
    return new request.Request(params) 
} 

我應該拿這一點完全?

回答

0

似乎問題出在客戶端上。如果用戶沒有選擇大小或顏色,他們在請求中未定義,而不是'N/A'。你可以檢查undefined以及你的第一條語句

if (req.query.size === 'N/A' || req.query.size === undefined ... 
+0

謝謝你,我的問題不清楚,我更新了它。當我嘗試按照你的建議去做req.query.size == undefined時,我在控制檯中得到這個錯誤:「錯誤:undefined不是一個有效的uri或options對象。」 –

+0

嘗試typeof req.query.size =='undefined' – gabesoft

+0

謝謝,但這與我做req.query.size === undefined一樣。我得到正確的輸出,但控制檯有錯誤:「錯誤:undefined不是一個有效的uri或options對象」 –