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

查看:12
本文介绍了在 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?

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

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天全站免登陆