Determine on which route from a list of routes an express middleware was called

  express, javascript, node.js

I have the following case:

There is a list of routes in the form

var lst = ["route1/:foo", "route2/:bar", "route3/:bar/route4/:baz", ..] // this list has like 200 entries

I have the following code

app.use(lst, function (req, res) {
  // here I want to know which route the middleware was invoked on
  // req.route.path doesn't work unless I use app.METHOD()
  // req.originalUrl would give me route1/200, instead of route1/:foo
})

What I tried so far:

  1. Using the router stack as in app._router.stack, my routes aren’t even registered there – I don’t see route1/:foo, route2/:bar and route3/:bar/route4/:baz
  2. Hook into the express router:
var Route = express.Route;

let defaultImplementation = Route.prototype.dispatch;

function foo(req, res) {
  console.log('Called route ', req.route.path); // still doesn't trigger on the routes in lst, only parent routes
}

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

By the way, I’m passing those routes and using them along with http-proxy-middleware https://github.com/chimurai/http-proxy-middleware, so if you have any clues on how do achieve that with that library as well, I’d be very grateful as I couldn’t find out.

Source: Ask Javascript Questions

LEAVE A COMMENT