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

微信扫一扫,分享到朋友圈

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?

Problem courtesy of: Killroy

Solution

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.

Solution courtesy of: Nate

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it’s original form on Stack Over Flow
.

微信扫一扫,分享到朋友圈

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

16、lnmp_mysql二进制安装

上一篇

Java并发读书笔记:如何实现线程间正确通信

下一篇

你也可能喜欢

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

长按储存图像,分享给朋友