简体   繁体   English

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

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

How do I check if a query string passed to an Express.js application contains any values?如何检查传递给 Express.js 应用程序的查询字符串是否包含任何值? If I have an API URL that could be either: http://example.com/api/objects or http://example.com/api/objects?name=itemName , what conditional statements work to determine which I am dealing with?如果我有一个 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');
}

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.

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');
}

We can use underscore JS Library我们可以使用下划线 JS

Which has built in function isEmpty(obj).其中有内置函数 isEmpty(obj)。 This returns true/false.这将返回真/假。

So, the code will look like :-因此,代码将如下所示:-

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

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
  ...
  ...
  //
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM