Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js matching the url pattern

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
like image 941
AtaurRehman Asad Avatar asked Dec 26 '22 19:12

AtaurRehman Asad


2 Answers

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'.

like image 125
robertklep Avatar answered Dec 28 '22 10:12

robertklep


You can use node-js url-pattern module.

Make pattern:

var pattern = new UrlPattern('/stack/post(/:postId)');

Match pattern against url path:

pattern.match('/stack/post/22'); //{postId:'22'}
pattern.match('/stack/post/abc'); //{postId:'abc'}
pattern.match('/stack/post'); //{}
pattern.match('/stack/stack'); //null

For more information, see: https://www.npmjs.com/package/url-pattern

like image 41
kapil joshi Avatar answered Dec 28 '22 11:12

kapil joshi