如何获取Express的所有注册路线? [英] How to get all registered routes in Express?

查看:94
本文介绍了如何获取Express的所有注册路线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Node.js和Express构建的Web应用程序。现在我想使用适当的方法列出所有注册的路线。



例如,如果我执行了

  app.get('/',function(...){...}); 
app.get('/ foo /:id',function(...){...});
app.post('/ foo /:id',function(...){...});

我想要检索一个对象(或类似的东西),如:

  {
get:['/','/ foo /:id'],
post:[' foo /:id']
}

这是可能吗?






更新:同时,我创建了一个名为 get-routes ,它从一个给定的应用程序中提取路由,从而解决了这个问题。目前,只支持Express 4.x,但是我猜想现在是没问题的。只是FYI。

解决方案

express 3.x



它自己...它只是 app.routes : - )



express 4.x



应用程序 - 使用 express()


app._router.stack


路由器 - 用 express.Router()


router.stack


注意:堆栈还包含中间件功能,应将其过滤到仅获取路线


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?


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

Okay, found it myself ... it's just app.routes :-)

express 4.x

Applications - built with express()

app._router.stack

Routers - built with express.Router()

router.stack

Note: The stack includes the middleware functions too, it should be filtered to get the "routes" only.

这篇关于如何获取Express的所有注册路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆