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

2
  • 2
    possible duplicate of Pre-routing with querystrings with Express in Node JS Commented Aug 12, 2015 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? Commented Aug 12, 2015 at 11:55

2 Answers 2

8

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)

Sign up to request clarification or add additional context in comments.

1 Comment

My purpose is the 1st mentioned above. Your example is great though I need some time to understand the code, thanks very much.
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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.