Pre-routing with querystrings with Express in Node JS

I am trying to use an expression to parse a request if certain parameters are set and a small piece of code is executed before the actual routing. A use case is to capture a specific value that can be set no matter which link is used. I use the express' function to pass stuff to the next possible rule using next ().

So far I have tried - at the very top of the whole app.get / post-rule-block block:

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

and:

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

An example of what should be called:

 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 following matching rule is triggered, but the little function above is never executed. Does anyone have an idea how to do this?

EDIT: I understand that the param example did not work, since I do not use the specified parameter in any other routing rule after that, and it will only run then.

I also understand that the logic implies that Express ignores the request and is usually parsed inside the function after routing has already occurred. But, as already mentioned, I need this to be a β€œroute agnostic” and work with any URL processed in this application.

+6
source share
2 answers

express does not allow you to route based on query strings. You can add some middleware that performs some operation if the corresponding 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 }); 
+21
source

Well, there is a pretty logical flaw here. Routing uses only a URL and ignores the request.

The solution (or better "A") is actually:

 app.get('*', function(req, res, next) { if (req.query.something) { console.log("Something: "+req.query.something); }; next(); }) 

Explanation: Because Express ignores the request for routing, the only regular expression matching all URLs is "*". After this is called, I can check if the specified initialization exists, execute my logic and continue with the routing matching the next rule using "next ()".

And yes: facepalm

+1
source

All Articles