2014-10-10 46 views
5

如何檢查傳遞給Express.js應用程序的查詢字符串是否包含任何值?如果我有一個API URL可以是:http://example.com/api/objectshttp://example.com/api/objects?name=itemName,什麼條件語句可以確定我正在處理的是哪一個?如何檢查查詢字符串是否在Express.js/Node.js中有值?

我目前的代碼在下面,它總是評估爲'should have no string'選項。

if (req.query !== {}) { 
    console.log('should have no query string'); 
} 
else { 
    console.log('should have query string'); 
} 
+1

不知道的'node'的支持這一點,但也許你可以使用[這個答案](HTTP://計算器.com/a/5533226/2708970)檢查'req.query'的長度是否大於0. – 2014-10-10 05:08:31

+0

您使用快遞嗎? – JME 2014-10-10 05:11:30

回答

15

所有你需要做的就是檢查你的Object中的鑰匙長度,像這樣,

Object.keys(req.query).length === 0 


旁註:你暗示的if-else中走錯了路,

if (req.query !== {})  // this will run when your req.query is 'NOT EMPTY', i.e it has some query string. 
+0

謝謝!是的,那個錯誤是在爲我的問題轉換我的真實代碼時出現錯誤。 – blundin 2014-10-10 12:54:02

1

如果您要檢查,如果沒有查詢字符串,你可以做一個正則表達式搜索,

if (!/\?.+/.test(req.url) { 
    console.log('should have no query string'); 
} 
else { 
    console.log('should have query string'); 
} 

如果你正在尋找一個PARAM試試這個

if (!req.query.name) { 
    console.log('should have no query string'); 
} 
else { 
    console.log('should have query string'); 
} 
相關問題