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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26292267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:40:57  来源:igfitidea点击:

How do I check if query string has values in Express.js/Node.js?

javascriptnode.jsexpress

提问by blundin

How do I check if a query string passed to an Express.js application contains any values? If I have an API URL that could be either: http://example.com/api/objectsor http://example.com/api/objects?name=itemName, what conditional statements work to determine which I am dealing with?

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

My current code is below, and it always evaluates to the 'should have no string' option.

我当前的代码在下面,它总是评估为“应该没有字符串”选项。

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

回答by Ravi

All you need to do is check the length of keys in your Object, like this,

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

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


Sidenote: You are implying the if-else in wrong way,


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

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

回答by Pranav Shekhar Jha

If you want to check if there is no query string, you can do a regex search,

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

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

If you are looking for a single param try this

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

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

回答by Nikhil Vats

We can use underscore JS Library

我们可以使用下划线 JS

Which has built in function isEmpty(obj). This returns true/false.

其中有内置函数 isEmpty(obj)。这将返回真/假。

So, the code will look like :-

因此,代码将如下所示:-

const underscore = require('underscore');
console.log(underscore.isEmpty(req.query));

回答by pcodex

I usually check if the variable in the query string is defined. Using the url package in ExpressJS it would be so:

我通常检查查询字符串中的变量是否已定义。在 ExpressJS 中使用 url 包会是这样:

var aquery = require('url').parse(req.url,true).query;

if(aquery.variable1 != undefined){
  ...
  ....
  var capturedvariablevalue = aquery.variable1;
  ....
  ....

}
else{
  //logic for variable not defined
  ...
  ...
  //
}