【问题标题】:How do I check if query string has values in Express.js/Node.js?如何检查查询字符串是否在 Express.js/Node.js 中有值?
【发布时间】:2014-12-05 04:49:30
【问题描述】:

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

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

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

【问题讨论】:

  • 不确定node是否支持这个,但也许你可以使用this answer来检查req.query的长度是否大于0。
  • 你用的是快递吗?

标签: javascript node.js express


【解决方案1】:

您需要做的就是检查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.

【讨论】:

  • 谢谢!是的,这个错误是我在转换我的真实代码时的错字。
【解决方案2】:

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

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

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

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

【讨论】:

    【解决方案3】:

    我们可以使用下划线JSLibrary

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

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

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

    【讨论】:

    • 老兄,下划线早就没有了。使用 lodash。
    【解决方案4】:

    我通常检查查询字符串中的变量是否已定义。在 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
      ...
      ...
      //
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-02
      • 1970-01-01
      • 2016-11-20
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      • 1970-01-01
      相关资源
      最近更新 更多