使用Node JS中的Express进行预查询

luc*_*lis 7 regex routing node.js express

我正在尝试使用express来解析查询字符串,以防设置某些参数并在实际路由发生之前执行一小段代码.用例是获取一个可以设置的特定值,与所使用的链接无关.我使用express'功能使用next()将内容传递给下一个可能的规则.

到目前为止,我尝试过 - 在所有app.get/post-rule-block的最顶层:

app.get('[?&]something=([^&#]*)', function(req, res, next) {
  var somethingID = req.params.something;
  // Below line is just there to illustrate that it's working. Actual code will do something real, of course.
  console.log("Something: "+somethingID);
  next();
})

app.get('/', site.index);
Run Code Online (Sandbox Code Playgroud)

并且:

app.param('something', function(req, res, next) {
  var somethingID = req.params.something;
  console.log("Something: "+somethingID);
  next();
})

app.get('/', site.index);
Run Code Online (Sandbox Code Playgroud)

应触发的示例:

URL: www.example.com/?something=10239
URL: www.example.com/superpage/?something=10239
URL: www.example.com/minisite/?anything=10&something=10239
Run Code Online (Sandbox Code Playgroud)

不幸的是,我的解决方案都没有真正起作用,而且所有发生的事情都是,触发了下一个匹配规则,但上面的小功能从未执行过.有人知道如何做到这一点?

编辑:我明白,param-example不能正常工作,因为我之后没有在任何其他路由规则中使用所述参数,而只会触发它.

我也明白,逻辑暗示,Express忽略了查询字符串,并且通常在路由已经发生之后在函数内解析.但如上所述,我需要将其视为"与路由无关",并与此应用程序中处理的任何URL一起使用.

Mat*_*att 21

express不允许您根据查询字符串进行路由.如果存在相关参数,您可以添加一些执行某些操作的中间件;

app.use(function (req, res, next) {
    if (req.query.something) {
        // Do something; call next() when done.
    } else {
        next();
    }
});

app.get('/someroute', function (req, res, next) {
    // Assume your query params have been processed
});
Run Code Online (Sandbox Code Playgroud)

  • 这比我自己的解决方案更优雅,更有效.非常感谢. (3认同)