node.js 如何在 Express 中获取所有已注册的路线?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14934452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get all registered routes in Express?
提问by Golo Roden
I have a web application built using Node.js and Express. Now I would like to list all registered routes with their appropriate methods.
我有一个使用 Node.js 和 Express 构建的 Web 应用程序。现在我想用适当的方法列出所有已注册的路线。
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-routesthat 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.
更新:同时,我创建了一个名为get-routes的 npm 包,它从给定的应用程序中提取路由,从而解决了这个问题。目前,只支持 Express 4.x,但我想现在这很好。仅供参考。
回答by Golo Roden
express 3.x
快递 3.x
Okay, found it myself ... it's just app.routes:-)
好吧,我自己找到了……只是app.routes:-)
express 4.x
快递 4.x
Applications- built with express()
应用程序- 内置express()
app._router.stack
app._router.stack
Routers- built with express.Router()
路由器- 内置express.Router()
router.stack
router.stack
Note: The stack includes the middleware functions too, it should be filtered to get the "routes"only.
注意:堆栈也包含中间件功能,应过滤以仅获取“路由”。
回答by eychu
app._router.stack.forEach(function(r){
if (r.route && r.route.path){
console.log(r.route.path)
}
})
回答by Caleb
This gets routes registered directly on the app (via app.VERB) and routes that are registered as router middleware (via app.use). Express 4.11.0
这将获取直接在应用程序上注册的路由(通过 app.VERB)和注册为路由器中间件的路由(通过 app.use)。快递 4.11.0
//////////////
app.get("/foo", function(req,res){
res.send('foo');
});
//////////////
var router = express.Router();
router.get("/bar", function(req,res,next){
res.send('bar');
});
app.use("/",router);
//////////////
var route, routes = [];
app._router.stack.forEach(function(middleware){
if(middleware.route){ // routes registered directly on the app
routes.push(middleware.route);
} else if(middleware.name === 'router'){ // router middleware
middleware.handle.stack.forEach(function(handler){
route = handler.route;
route && routes.push(route);
});
}
});
// routes:
// {path: "/foo", methods: {get: true}}
// {path: "/bar", methods: {get: true}}
回答by marco.marinangeli
I have adapted an old post that is no longer online for my needs. I've used express.Router() and registered my routes like this:
我已经根据我的需要改编了不再在线的旧帖子。我使用了 express.Router() 并像这样注册了我的路线:
var questionsRoute = require('./BE/routes/questions');
app.use('/api/questions', questionsRoute);
I renamed the document.js file in apiTable.js and adapted it like this:
我在 apiTable.js 中重命名了 document.js 文件并像这样修改了它:
module.exports = function (baseUrl, routes) {
var Table = require('cli-table');
var table = new Table({ head: ["", "Path"] });
console.log('\nAPI for ' + baseUrl);
console.log('\n********************************************');
for (var key in routes) {
if (routes.hasOwnProperty(key)) {
var val = routes[key];
if(val.route) {
val = val.route;
var _o = {};
_o[val.stack[0].method] = [baseUrl + val.path];
table.push(_o);
}
}
}
console.log(table.toString());
return table;
};
then i call it in my server.js like this:
然后我像这样在我的 server.js 中调用它:
var server = app.listen(process.env.PORT || 5000, function () {
require('./BE/utils/apiTable')('/api/questions', questionsRoute.stack);
});
The result looks like this:
结果如下所示:


It's just an example but might be of use.. i hope..
这只是一个例子,但可能有用..我希望..
回答by corvid
Here's a little thing I use just to get the registered paths in express 4.x
这是我用来获取 express 4.x 中注册路径的小东西
app._router.stack // registered routes
.filter(r => r.route) // take out all the middleware
.map(r => r.route.path) // get all the paths
回答by nbsamar
DEBUG=express:* node index.js
DEBUG=express:* node index.js
If you run your app with the above command, it will launch your app with DEBUGmodule and gives routes, plus all the middleware functions that are in use.
如果您使用上述命令运行您的应用程序,它将使用DEBUG模块启动您的应用程序并提供路由,以及所有正在使用的中间件功能。
You can refer: ExpressJS - Debuggingand debug.
可以参考:ExpressJS - 调试和调试。
回答by AlienWebguy
Hacky copy/paste answer courtesy of Doug Wilsonon the express github issues. Dirty but works like a charm.
由Doug Wilson 提供关于express github 问题的Hacky 复制/粘贴回答。脏,但效果很好。
function print (path, layer) {
if (layer.route) {
layer.route.stack.forEach(print.bind(null, path.concat(split(layer.route.path))))
} else if (layer.name === 'router' && layer.handle.stack) {
layer.handle.stack.forEach(print.bind(null, path.concat(split(layer.regexp))))
} else if (layer.method) {
console.log('%s /%s',
layer.method.toUpperCase(),
path.concat(split(layer.regexp)).filter(Boolean).join('/'))
}
}
function split (thing) {
if (typeof thing === 'string') {
return thing.split('/')
} else if (thing.fast_slash) {
return ''
} else {
var match = thing.toString()
.replace('\/?', '')
.replace('(?=\/|$)', '$')
.match(/^\/\^((?:\[.*+?^${}()|[\]\\/]|[^.*+?^${}()|[\]\\/])*)$\//)
return match
? match[1].replace(/\(.)/g, '').split('/')
: '<complex:' + thing.toString() + '>'
}
}
app._router.stack.forEach(print.bind(null, []))
Produces
生产
回答by aercolino
https://www.npmjs.com/package/express-list-endpointsworks pretty well.
https://www.npmjs.com/package/express-list-endpoints效果很好。
Example
例子
Usage:
用法:
const all_routes = require('express-list-endpoints');
console.log(all_routes(app));
Output:
输出:
[ { path: '*', methods: [ 'OPTIONS' ] },
{ path: '/', methods: [ 'GET' ] },
{ path: '/sessions', methods: [ 'POST' ] },
{ path: '/sessions', methods: [ 'DELETE' ] },
{ path: '/users', methods: [ 'GET' ] },
{ path: '/users', methods: [ 'POST' ] } ]
回答by Labithiotis
A function to log all routes in express 4 (can be easily tweaked for v3~)
在 express 4 中记录所有路由的功能(可以轻松调整 v3~)
function space(x) {
var res = '';
while(x--) res += ' ';
return res;
}
function listRoutes(){
for (var i = 0; i < arguments.length; i++) {
if(arguments[i].stack instanceof Array){
console.log('');
arguments[i].stack.forEach(function(a){
var route = a.route;
if(route){
route.stack.forEach(function(r){
var method = r.method.toUpperCase();
console.log(method,space(8 - method.length),route.path);
})
}
});
}
}
}
listRoutes(router, routerAuth, routerHTML);
Logs output:
日志输出:
GET /isAlive
POST /test/email
POST /user/verify
PUT /login
POST /login
GET /player
PUT /player
GET /player/:id
GET /players
GET /system
POST /user
GET /user
PUT /user
DELETE /user
GET /
GET /login
Made this into a NPM https://www.npmjs.com/package/express-list-routes
把它变成一个 NPM https://www.npmjs.com/package/express-list-routes
回答by ezekills
json output
json 输出
function availableRoutes() {
return app._router.stack
.filter(r => r.route)
.map(r => {
return {
method: Object.keys(r.route.methods)[0].toUpperCase(),
path: r.route.path
};
});
}
console.log(JSON.stringify(availableRoutes(), null, 2));
looks like this:
看起来像这样:
[
{
"method": "GET",
"path": "/api/todos"
},
{
"method": "POST",
"path": "/api/todos"
},
{
"method": "PUT",
"path": "/api/todos/:id"
},
{
"method": "DELETE",
"path": "/api/todos/:id"
}
]
string output
字符串输出
function availableRoutesString() {
return app._router.stack
.filter(r => r.route)
.map(r => Object.keys(r.route.methods)[0].toUpperCase().padEnd(7) + r.route.path)
.join("\n ")
}
console.log(availableRoutesString());
looks like this:
看起来像这样:
GET /api/todos
POST /api/todos
PUT /api/todos/:id
DELETE /api/todos/:id
these are based on @corvid'sanswer
这些基于@corvid 的回答
hope this helps
希望这可以帮助

