Killroy
Killroy

Reputation: 931

How can I find the originally matched route at the time of a request in Express.Js

I need to recover the original route at the time of a request. Either the original one with the :Variable strings, or the regular expression. Basically I want to have some key that groups all requests that hit the same route in a generic, high-level pre-processor.

The problem is that my routes are fairly complex with nested apps and routers, so app.routes.map doesn't contain the routes.

Is there a way to reverse engineer the route from the request object, or is there a place where I can get a global list of routes that I could match and search agaisnt the current request?

Upvotes: 0

Views: 1113

Answers (1)

Nate
Nate

Reputation: 19030

The specific route should be available in req.route (docs). That contains several properties, including req.route.regexp (the compiled regular expression for the route), and req.route.params (array of matched parameters).

EDIT: The route isn’t going to be attached until the request is dispatched.

It sounds like you’re trying to predict the route before it’s dispatched. In that case, using app.routes might normally work. The problem is that you have sub-apps with their own routers. app.routes only contains routes for the top-level app and not for any sub-apps.

The answer is: There is no global view of routes. Your sub-apps look exactly like middleware to the parent app. It does not know or care that there is routing going on down there.

If you need to do this, you have to do it manually, e.g., create a global array where you register your sub-apps.

Upvotes: 1

Related Questions