dzm
dzm

Reputation: 23534

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.

Upvotes: 25

Views: 19749

Answers (6)

You can take a look at Router().stack, which has all the routes defined. In your middleware you need to manually compare the available routes with the one called to define actions.

Upvotes: 0

HagenAnuth
HagenAnuth

Reputation: 99

I know this is a little late, but for later Express/Node setups req.originalUrl works just fine!

Hope this helps

Upvotes: 3

Abdul Vajid
Abdul Vajid

Reputation: 1411

req.route.path will work to get the path for the given route. But if you want the complete path including the path of the parent route, use something like

let full_path = req.baseUrl+req.route.path;

Hope it helps

Upvotes: 0

DonGiovanni
DonGiovanni

Reputation: 61

This nasty trick using prototype override will help

   "use strict"
    var Route = require("express").Route;

    module.exports = function () {
        let defaultImplementation = Route.prototype.dispatch;

        Route.prototype.dispatch = function handle(req, res, next) {
            someMethod(req, res); //req.route is available here
            defaultImplementation.call(this, req, res, next);
        };
    };

Upvotes: 2

robertklep
robertklep

Reputation: 203231

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) { ... });

Upvotes: 15

gustavohenke
gustavohenke

Reputation: 41440

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.

Upvotes: 32

Related Questions