使用Express在Node JS中预订路由 [英] Pre-routing with querystrings with Express in Node JS

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

问题描述

在实际路由发生之前,我正在尝试使用express来解析querystring,以防某些参数被设置并执行一小段代码。用例是获取一定值,可以设置,独立于正在使用的链接。我使用快速功能将内容传递给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忽略了querystring,它是通常在路由已经发生之后在函数内解析。但是如上所述,我需要这样做是路由不可知论,并且可以使用在此应用程序中处理的任何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
});

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

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