Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express js routing with query string

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

like image 824
wdetac Avatar asked Aug 12 '15 11:08

wdetac


2 Answers

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)

like image 58
robertklep Avatar answered Nov 11 '22 08:11

robertklep


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
}
like image 45
manojlds Avatar answered Nov 11 '22 08:11

manojlds