Pre-routing with querystrings with Express in Node JS

前提是你 提交于 2019-11-29 07:13:29

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!