如何检查查询字符串是否具有Express.js/Node.js中的值?

blu*_*din 10 javascript node.js express

如何检查传递给Express.js应用程序的查询字符串是否包含任何值?如果我有一个API URL,可以是:http://example.com/api/objects或者http://example.com/api/objects?name=itemName,条件语句用于确定我正在处理的是什么?

我当前的代码在下面,它总是评估为'should have no string'选项.

if (req.query !== {}) {
    console.log('should have no query string');
}
else {
    console.log('should have query string');
}
Run Code Online (Sandbox Code Playgroud)

Rav*_*avi 27

你需要做的就是检查你的钥匙长度Object,像这样,

Object.keys(req.query).length === 0
Run Code Online (Sandbox Code Playgroud)


旁注:你暗示if-else错误的方式,

if (req.query !== {})     // this will run when your req.query is 'NOT EMPTY', i.e it has some query string.
Run Code Online (Sandbox Code Playgroud)


Pra*_*Jha 5

如果要检查是否没有查询字符串,可以进行正则表达式搜索,

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

如果你正在寻找一个单一的参数试试这个

if (!req.query.name) {
    console.log('should have no query string');
}
else {
    console.log('should have query string');
}
Run Code Online (Sandbox Code Playgroud)