【问题标题】:GET request always defaults to /(?:)/i - how can i make it 'undefined'?GET 请求始终默认为 /(?:)/i - 我怎样才能使其“未定义”?
【发布时间】:2020-09-01 22:04:58
【问题描述】:

如果我使用 RegExp,那么我的搜索小部件页面总是会得到: /(?:)/i

因此总是加载结果列表。我不希望这种情况发生。我只想加载我的页面,然后用户填写搜索框,然后执行 GET 请求。

app.get("/la_widget", function(req, res) {

  var test = new RegExp(req.query.search, 'i');
  console.log(test);

  Restaurant.find({
      LocalAuthorityName: test
    },
    null,
    {
      limit: 50
    },
    function(err, foundAuthority) {
      if (foundAuthority) {
        res.render("la_widget", {foundAuthority})
    } else {
      res.render("la_widget", "No local authority matching that input was found.");
    }
  });
});

【问题讨论】:

  • 允许用户输入定义正则表达式是不明智的*
  • @LawrenceCherone 感谢您的评论,我想了解更多有关执行此操作的最佳方法的信息。请问你有一个例子或一些额外的信息吗?当我更改数据库或向我的 MongoDb 添加额外文档时,在我填写搜索框并点击“搜索”按钮之前,我经常会再次出现这个问题,即自动搜索启动。

标签: node.js forms express get xregexp


【解决方案1】:

在设置搜索查询之前测试是否定义了req.query.search 字符串。

const test = (req.query.search) 
  ? new RegExp(req.query.search, 'i')
  : undefined

这使用ternary 运算符,相当于:

let test
if (req.query.search) {
   test = new RegExp(req.query.search, 'i')
}
else {
   test = undefined
}

【讨论】:

  • 嘿,马特 - 非常感谢,成功了!我对编程真的很陌生,所以我研究如何解决它。非常感谢!
  • 这称为ternery 语句,基本上是if/then/else 的另一种写法。
  • 我将它用于变量赋值,因此变量位于if 语句范围之外。
  • 我希望优化我的代码以在我的数据库中搜索 2 或 3 个字段,而不仅仅是一个。所以现在它只检查Restaurant.find({ LocalAuthorityName: test }, 但我喜欢它来检查一个字段数组。我试过:Restaurant.find({ $or:[{ AddressLine3: test3 }, { AddressLine4: test4 }]}, 但这只是给了我原来的问题,即在页面加载时自动执行搜索,而不是有一个空白的搜索框准备好进行新的搜索了。您有什么想法吗?
  • 不确定抱歉,可能在新问题中详细说明。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多