Node.js matching the url pattern

AtaurRehman Asad picture AtaurRehman Asad · Oct 1, 2013 · Viewed 12.7k times · Source

I need an equivalent of following express.js code in simple node.js that I can use in middleware. I need to place some checks depending on the url and want to do it in a custom middleware.

app.get "/api/users/:username", (req,res) ->
  req.params.username

I have the following code so far,

app.use (req,res,next)->
  if url.parse(req.url,true).pathname is '/api/users/:username' #this wont be true as in the link there will be a actual username not ":username" 
    #my custom check that I want to apply

Answer

robertklep picture robertklep · Oct 1, 2013

A trick would be to use this:

app.all '/api/users/:username', (req, res, next) ->
  // your custom code here
  next();

// followed by any other routes with the same patterns
app.get '/api/users/:username', (req,res) ->
  ...

If you only want to match GET requests, use app.get instead of app.all.

Or, if you only want to use the middleware on certain specific routes, you can use this (in JS this time):

var mySpecialMiddleware = function(req, res, next) {
  // your check
  next();
};

app.get('/api/users/:username', mySpecialMiddleware, function(req, res) {
  ...
});

EDIT another solution:

var mySpecialRoute = new express.Route('', '/api/users/:username');

app.use(function(req, res, next) {
  if (mySpecialRoute.match(req.path)) {
    // request matches your special route pattern
  }
  next();
});

But I don't see how this beats using app.all() as 'middleware'.