在 Node JS 中使用 Express 预路由查询字符串 [英] Pre-routing with querystrings with Express in Node JS

查看:18
本文介绍了在 Node JS 中使用 Express 预路由查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use express to parse the querystring in case certain parameters are set and execute a little piece of code, before the actual routing is happening. The use-case is to grab a certain value, that could be set, independant of what link is being used. I use express' functionality to pass the stuff to the next possible rule using next().

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

So far, I tried - at the very top of all the 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);

还有:

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

app.get('/', site.index);

应该触发什么的例子:

URL: www.example.com/?something=10239
URL: www.example.com/superpage/?something=10239
URL: www.example.com/minisite/?anything=10&something=10239

不幸的是,我的解决方案都没有真正奏效,所发生的只是触发了下一个匹配规则,但从未执行过上面的小函数.任何人都知道如何做到这一点?

Unfortunately, none of my solutions actually worked, and all that happens is, that the next matching rule is triggered, but the little function above is never executed. Anybody have an idea, of how this can be done?

我明白,参数示例不起作用,因为我之后没有在任何其他路由规则中使用所述参数,并且只会在那时被触发.

I do understand, that the param-example wasn't working, as I'm not using said parameter within any other routing-rule afterwards, and it would only be triggered then.

我也明白,这个逻辑意味着,Express 会忽略查询字符串,并且在路由已经发生之后,它通常在一个函数中被解析.但正如前面提到的,我需要它是路由不可知的",并使用在此应用程序中处理的任何 URL.

I also do understand, that logic implies, that Express ignores the querystring and it is normally parsed within a function after the routing already happened. But as mentioned, I need this to be "route-agnostic" and work with any of the URL's that are processed within this application.

推荐答案

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

express does not allow you to route based on query strings. You could add some middleware which performs some operation if the relevant parameter is present;

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

这篇关于在 Node JS 中使用 Express 预路由查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆