如何在 Express 中获取所有已注册的路由? [英] How to get all registered routes in Express?
问题描述
我有一个使用 Node.js 和 Express 构建的 Web 应用程序.现在我想用适当的方法列出所有已注册的路由.
I have a web application built using Node.js and Express. Now I would like to list all registered routes with their appropriate methods.
例如,如果我已经执行了
E.g., if I have executed
app.get('/', function (...) { ... });
app.get('/foo/:id', function (...) { ... });
app.post('/foo/:id', function (...) { ... });
我想检索一个对象(或类似的东西),例如:
I would like to retrieve an object (or something equivalent to that) such as:
{
get: [ '/', '/foo/:id' ],
post: [ '/foo/:id' ]
}
这可能吗,如果可能,怎么做?
Is this possible, and if so, how?
更新: 同时,我创建了一个名为 get-的 npm 包routes 从给定的应用程序中提取路由,解决了这个问题.目前,只支持 Express 4.x,但我想现在这很好.仅供参考.
UPDATE: Meanwhile, I have created an npm package called get-routes that extracts the routes from a given application, which solves this issue. Currently, only Express 4.x is supported, but I guess for now this is fine. Just FYI.
推荐答案
express 3.x
好的,我自己找到的……它只是 app.routes
:-)
应用程序 - 使用 express()
app._router.stack
路由器 - 使用 express.Router()
router.stack
注意:堆栈也包含中间件功能,应该过滤以仅获取路由".
Note: The stack includes the middleware functions too, it should be filtered to get the "routes" only.
这篇关于如何在 Express 中获取所有已注册的路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!