Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get route definition in middleware

Does anyone know if it's possible to get the path used to trigger the route?

For example, let's say I have this:

app.get('/user/:id', function(req, res) {});

With the following simple middleware being used

function(req, res, next) {
     req.?
});

I'd want to be able to get /user/:id within the middleware, this is not req.url.

like image 658
dzm Avatar asked Oct 18 '13 23:10

dzm


People also ask

What is routing in middleware?

Routing defines the way in which the client requests are handled by the application endpoints. And when you make some routers in separate file, you can use them by using middleware.

Is a route handler middleware?

They are not middleware functions by definition. If such function is used on routing methods then they are only handler functions. We use such a handler function which is not a middleware when it is the only one callback function.

What are routes in Express?

A route is a section of Express code that associates an HTTP verb ( GET , POST , PUT , DELETE , etc.), a URL path/pattern, and a function that is called to handle that pattern. There are several ways to create routes.

What is a route node?

The route is a section of Express code that associates an HTTP verb (GET, POST, PUT, DELETE, etc.), an URL path/pattern, and a function that is called to handle that pattern. Node. js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside of a browser. Node.


2 Answers

What you want is req.route.path.

For example:

app.get('/user/:id?', function(req, res){
  console.log(req.route);
});

// outputs something like

{ path: '/user/:id?',
  method: 'get',
  callbacks: [ [Function] ],
  keys: [ { name: 'id', optional: true } ],
  regexp: /^\/user(?:\/([^\/]+?))?\/?$/i,
  params: [ id: '12' ] }

http://expressjs.com/api.html#req.route


EDIT:

As explained in the comments, getting req.route in a middleware is difficult/hacky. The router middleware is the one that populates the req.route object, and it probably is in a lower level than the middleware you're developing.

This way, getting req.route is only possible if you hook into the router middleware to parse the req for you before it's executed by Express itself.

like image 91
gustavohenke Avatar answered Oct 13 '22 10:10

gustavohenke


FWIW, two other options:

// this will only be called *after* the request has been handled
app.use(function(req, res, next) {
  res.on('finish', function() {
    console.log('R', req.route);
  });
  next();
});

// use the middleware on specific requests only
var middleware = function(req, res, next) {
  console.log('R', req.route);
  next();
};
app.get('/user/:id?', middleware, function(req, res) { ... });
like image 30
robertklep Avatar answered Oct 13 '22 11:10

robertklep