Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
886 views
in Technique[技术] by (71.8m points)

regex - Pre-routing with querystrings with Express in Node JS

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().

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

and also:

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

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

Example of what should be triggered:

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?

EDIT: 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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...