8

I want to do something like this. I want to use different middleware if there is or isn't a certain query string.

app.get("/test?aaa=*", function (req, res) {
    res.send("query string aaa found");
});

app.get("/test", middleware, function (req, res) {
    res.send("no query string");
});

However, I failed. Can anyone help me? Thanks. EDIT: I only need to add the middleware, I dont care what the value of the query string is

wdetac
  • 2,712
  • 3
  • 20
  • 42
  • 2
    possible duplicate of [Pre-routing with querystrings with Express in Node JS](http://stackoverflow.com/questions/14909465/pre-routing-with-querystrings-with-express-in-node-js) – cviejo Aug 12 '15 at 11:40
  • how is duplicate? I just want to add middleware, not process the query string, or can you show me some code example? – wdetac Aug 12 '15 at 11:55

2 Answers2

7

If your intention is to run the same route handler and call the middleware depending on whether the query string matches, you can use some sort of wrapping middleware:

var skipIfQuery = function(middleware) {
  return function(req, res, next) {
    if (req.query.aaa) return next();
    return middleware(req, res, next);
  };
};

app.get("/test", skipIfQuery(middleware), function (req, res) {
  res.send(...);
});

If you want to have two route handlers, you could use this:

var matchQueryString = function(req, res, next) {
  return next(req.query.aaa ? null : 'route');
};

app.get("/test", matchQueryString, function (req, res) {
  res.send("query string aaa found");
});

app.get("/test", middleware, function (req, res) {
  res.send("no query string");
});

(these obviously aren't very generic solutions, but it's just to give an idea on how to solve this)

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • My purpose is the 1st mentioned above. Your example is great though I need some time to understand the code, thanks very much. – wdetac Aug 12 '15 at 12:20
4

You can do this:

app.get("/test", middleware, function (req, res) {
    res.send("no query string");
});


middleware = function(req, res, next) {
    if(!req.query.yourQuery) return next();

    //middleware logic when query present
}
manojlds
  • 290,304
  • 63
  • 469
  • 417