Pre-routing with querystrings with Express in Node JS

后端 未结 2 778
借酒劲吻你
借酒劲吻你 2020-12-19 06:35

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-ca

相关标签:
2条回答
  • 2020-12-19 07:05

    Ok, there is quite a logical flaw in here. Routing only uses the URL, and ignores the querystring.

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

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

    Explanation: As Express is ignoring the querystring for the routing, the only regular expression matching all URL's is "*". Once that is triggered, I can check if said querystring is existing, do my logic and continue the routing matching the next rule by using "next()".

    And yes: facepalm

    0 讨论(0)
  • 2020-12-19 07:11

    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
    });
    
    0 讨论(0)
提交回复
热议问题