我有一个使用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的npm包,它从给定的应用程序中提取路由,从而解决了这个问题。目前,仅支持Express 4.x,但我想现在这很好。仅供参考。
答案 0 :(得分:191)
好的,我自己找到了...它只是app.routes
: - )
Applications - 使用express()
app._router.stack
Routers - 使用express.Router()
router.stack
注意:堆栈也包含中间件功能,应该对其进行过滤以仅获取“路由”。
答案 1 :(得分:47)
app._router.stack.forEach(function(r){
if (r.route && r.route.path){
console.log(r.route.path)
}
})
答案 2 :(得分:29)
我已根据我的需要调整了一个不再在线的旧帖子。 我使用了express.Router()并注册了我的路线:
var questionsRoute = require('./BE/routes/questions');
app.use('/api/questions', questionsRoute);
我在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;
};
然后我在我的server.js中调用它:
var server = app.listen(process.env.PORT || 5000, function () {
require('./BE/utils/apiTable')('/api/questions', questionsRoute.stack);
});
结果如下:
这只是一个例子,但可能有用......我希望......
答案 3 :(得分:27)
这是我用来获取快递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
答案 4 :(得分:25)
这将获得直接在应用程序上注册的路由(通过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}}
答案 5 :(得分:8)
Hacky复制/粘贴答案由Doug Wilson express github issues提供。肮脏但却像魅力一样。
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, '$1').split('/')
: '<complex:' + thing.toString() + '>'
}
}
app._router.stack.forEach(print.bind(null, []))
制作
答案 6 :(得分:7)
记录快递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);
记录输出:
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
答案 7 :(得分:7)
https://www.npmjs.com/package/express-list-endpoints效果非常好。
示例强>
用法:
const all_routes = require('express-list-endpoints');
console.log(all_routes(app));
输出:
[ { path: '*', methods: [ 'OPTIONS' ] },
{ path: '/', methods: [ 'GET' ] },
{ path: '/sessions', methods: [ 'POST' ] },
{ path: '/sessions', methods: [ 'DELETE' ] },
{ path: '/users', methods: [ 'GET' ] },
{ path: '/users', methods: [ 'POST' ] } ]
答案 8 :(得分:7)
您可以实现/get-all-routes
API:
const express = require("express");
const app = express();
app.get("/get-all-routes", (req, res) => {
let get = app._router.stack.filter(r => r.route && r.route.methods.get).map(r => r.route.path);
let post = app._router.stack.filter(r => r.route && r.route.methods.post).map(r => r.route.path);
res.send({ get: get, post: post });
});
const listener = app.listen(process.env.PORT, () => {
console.log("Your app is listening on port " + listener.address().port);
});
答案 9 :(得分:4)
我受到了Labithiotis的快速列表路线的启发,但我想一次性概述我的所有路线和粗略的网址,而不是指定路由器,并且每次都找出前缀。我想到的是简单地用我自己的函数替换app.use函数,该函数存储baseUrl和给定的路由器。从那里我可以打印我所有路线的任何表格。
注意这对我有用,因为我在特定路由文件(函数)中声明我的路由,它在app对象中传递,如下所示:
// index.js
[...]
var app = Express();
require(./config/routes)(app);
// ./config/routes.js
module.exports = function(app) {
// Some static routes
app.use('/users', [middleware], UsersRouter);
app.use('/users/:user_id/items', [middleware], ItemsRouter);
app.use('/otherResource', [middleware], OtherResourceRouter);
}
这允许我使用假的使用函数传入另一个'app'对象,我可以获得所有路由。这对我有用(为了清楚起见,删除了一些错误检查,但仍然适用于该示例):
// In printRoutes.js (or a gulp task, or whatever)
var Express = require('express')
, app = Express()
, _ = require('lodash')
// Global array to store all relevant args of calls to app.use
var APP_USED = []
// Replace the `use` function to store the routers and the urls they operate on
app.use = function() {
var urlBase = arguments[0];
// Find the router in the args list
_.forEach(arguments, function(arg) {
if (arg.name == 'router') {
APP_USED.push({
urlBase: urlBase,
router: arg
});
}
});
};
// Let the routes function run with the stubbed app object.
require('./config/routes')(app);
// GRAB all the routes from our saved routers:
_.each(APP_USED, function(used) {
// On each route of the router
_.each(used.router.stack, function(stackElement) {
if (stackElement.route) {
var path = stackElement.route.path;
var method = stackElement.route.stack[0].method.toUpperCase();
// Do whatever you want with the data. I like to make a nice table :)
console.log(method + " -> " + used.urlBase + path);
}
});
});
这个完整的例子(带有一些基本的CRUD路由器)刚刚测试并打印出来:
GET -> /users/users
GET -> /users/users/:user_id
POST -> /users/users
DELETE -> /users/users/:user_id
GET -> /users/:user_id/items/
GET -> /users/:user_id/items/:item_id
PUT -> /users/:user_id/items/:item_id
POST -> /users/:user_id/items/
DELETE -> /users/:user_id/items/:item_id
GET -> /otherResource/
GET -> /otherResource/:other_resource_id
POST -> /otherResource/
DELETE -> /otherResource/:other_resource_id
使用cli-table我有这样的事情:
┌────────┬───────────────────────┐
│ │ => Users │
├────────┼───────────────────────┤
│ GET │ /users/users │
├────────┼───────────────────────┤
│ GET │ /users/users/:user_id │
├────────┼───────────────────────┤
│ POST │ /users/users │
├────────┼───────────────────────┤
│ DELETE │ /users/users/:user_id │
└────────┴───────────────────────┘
┌────────┬────────────────────────────────┐
│ │ => Items │
├────────┼────────────────────────────────┤
│ GET │ /users/:user_id/items/ │
├────────┼────────────────────────────────┤
│ GET │ /users/:user_id/items/:item_id │
├────────┼────────────────────────────────┤
│ PUT │ /users/:user_id/items/:item_id │
├────────┼────────────────────────────────┤
│ POST │ /users/:user_id/items/ │
├────────┼────────────────────────────────┤
│ DELETE │ /users/:user_id/items/:item_id │
└────────┴────────────────────────────────┘
┌────────┬───────────────────────────────────┐
│ │ => OtherResources │
├────────┼───────────────────────────────────┤
│ GET │ /otherResource/ │
├────────┼───────────────────────────────────┤
│ GET │ /otherResource/:other_resource_id │
├────────┼───────────────────────────────────┤
│ POST │ /otherResource/ │
├────────┼───────────────────────────────────┤
│ DELETE │ /otherResource/:other_resource_id │
└────────┴───────────────────────────────────┘
哪个踢屁股。
答案 10 :(得分:4)
DEBUG=express:* node index.js
如果使用上述命令运行您的应用,它将使用DEBUG
模块启动您的应用,并提供路由以及所有正在使用的中间件功能。
您可以参考:ExpressJS - Debugging和debug。
答案 11 :(得分:4)
给定带有端点和嵌套路由器的 Express 4 配置
const express = require('express')
const app = express()
const router = express.Router()
app.get(...)
app.post(...)
router.use(...)
router.get(...)
router.post(...)
app.use(router)
扩展@caleb答案可以递归获取并排序所有路由。
getRoutes(app._router && app._router.stack)
// =>
// [
// [ 'GET', '/'],
// [ 'POST', '/auth'],
// ...
// ]
/**
* Converts Express 4 app routes to an array representation suitable for easy parsing.
* @arg {Array} stack An Express 4 application middleware list.
* @returns {Array} An array representation of the routes in the form [ [ 'GET', '/path' ], ... ].
*/
function getRoutes(stack) {
const routes = (stack || [])
// We are interested only in endpoints and router middleware.
.filter(it => it.route || it.name === 'router')
// The magic recursive conversion.
.reduce((result, it) => {
if (! it.route) {
// We are handling a router middleware.
const stack = it.handle.stack
const routes = getRoutes(stack)
return result.concat(routes)
}
// We are handling an endpoint.
const methods = it.route.methods
const path = it.route.path
const routes = Object
.keys(methods)
.map(m => [ m.toUpperCase(), path ])
return result.concat(routes)
}, [])
// We sort the data structure by route path.
.sort((prev, next) => {
const [ prevMethod, prevPath ] = prev
const [ nextMethod, nextPath ] = next
if (prevPath < nextPath) {
return -1
}
if (prevPath > nextPath) {
return 1
}
return 0
})
return routes
}
用于基本字符串输出。
infoAboutRoutes(app)
/**
* Converts Express 4 app routes to a string representation suitable for console output.
* @arg {Object} app An Express 4 application
* @returns {string} A string representation of the routes.
*/
function infoAboutRoutes(app) {
const entryPoint = app._router && app._router.stack
const routes = getRoutes(entryPoint)
const info = routes
.reduce((result, it) => {
const [ method, path ] = it
return result + `${method.padEnd(6)} ${path}\n`
}, '')
return info
}
由于Express 4的内部限制,无法检索已安装的应用程序和已安装的路由器。例如,无法从此配置中获取路由。
const subApp = express()
app.use('/sub/app', subApp)
const subRouter = express.Router()
app.use('/sub/route', subRouter)
答案 12 :(得分:4)
需要一些调整,但应该适用于Express v4。包括添加有.use()
的那些路由。
function listRoutes(routes, stack, parent){
parent = parent || '';
if(stack){
stack.forEach(function(r){
if (r.route && r.route.path){
var method = '';
for(method in r.route.methods){
if(r.route.methods[method]){
routes.push({method: method.toUpperCase(), path: parent + r.route.path});
}
}
} else if (r.handle && r.handle.name == 'router') {
const routerName = r.regexp.source.replace("^\\","").replace("\\/?(?=\\/|$)","");
return listRoutes(routes, r.handle.stack, parent + routerName);
}
});
return routes;
} else {
return listRoutes([], app._router.stack);
}
}
//Usage on app.js
const routes = listRoutes(); //array: ["method: path", "..."]
编辑:代码改进
答案 13 :(得分:3)
初始化快速路由器
let router = require('express').Router();
router.get('/', function (req, res) {
res.json({
status: `API Its Working`,
route: router.stack.filter(r => r.route)
.map(r=> { return {"path":r.route.path,
"methods":r.route.methods}}),
message: 'Welcome to my crafted with love!',
});
});
导入用户控制器
var userController = require('./controller/userController');
用户路线
router.route('/users')
.get(userController.index)
.post(userController.new);
router.route('/users/:user_id')
.get(userController.view)
.patch(userController.update)
.put(userController.update)
.delete(userController.delete);
导出API路由
module.exports = router;
输出
{"status":"API Its Working, APP Route","route":
[{"path":"/","methods":{"get":true}},
{"path":"/users","methods":{"get":true,"post":true}},
{"path":"/users/:user_id","methods": ....}
答案 14 :(得分:2)
对@ prranay的回答略有更新和更实用的方法:
const routes = app._router.stack
.filter((middleware) => middleware.route)
.map((middleware) => `${Object.keys(middleware.route.methods).join(', ')} -> ${middleware.route.path}`)
console.log(JSON.stringify(routes, null, 4));
答案 15 :(得分:2)
这对我有用
[
"get -> /posts/:id",
"post -> /posts",
"patch -> /posts"
]
O / P:
{{1}}
答案 16 :(得分:1)
所以我一直在查看所有答案..不是最喜欢的..从几个中取了一些..这样做了
const resolveRoutes = (stack) => {
return stack.map(function (layer) {
if (layer.route && layer.route.path.isString()) {
let methods = Object.keys(layer.route.methods);
if (methods.length > 20)
methods = ["ALL"];
return {methods: methods, path: layer.route.path};
}
if (layer.name === 'router') // router middleware
return resolveRoutes(layer.handle.stack);
}).filter(route => route);
};
const routes = resolveRoutes(express._router.stack);
const printRoute = (route) => {
if (Array.isArray(route))
return route.forEach(route => printRoute(route));
console.log(JSON.stringify(route.methods) + " " + route.path);
};
printRoute(routes);
不是最漂亮的..而是嵌套的,并且可以解决问题
还要注意那里的20条路线...我只是假设不会有20条路线的正常路线..所以我推断这就是全部。
答案 17 :(得分:1)
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));
看起来像这样:
[
{
"method": "GET",
"path": "/api/todos"
},
{
"method": "POST",
"path": "/api/todos"
},
{
"method": "PUT",
"path": "/api/todos/:id"
},
{
"method": "DELETE",
"path": "/api/todos/:id"
}
]
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());
看起来像这样:
GET /api/todos
POST /api/todos
PUT /api/todos/:id
DELETE /api/todos/:id
这些基于@corvid's答案
希望这会有所帮助
答案 18 :(得分:0)
静态代码分析方法。
此工具无需启动服务器即可分析源代码并显示路由信息。
npx express-router-dependency-graph --rootDir=path/to/project
# json or markdown output
https://github.com/azu/express-router-dependency-graph
示例输出:
文件 | 方法 | 路由 | 中间件 | 文件路径 |
---|---|---|---|---|
用户/index.ts | ||||
得到 | /getUserById | requireView | user/index.ts#L1-3 | |
得到 | /getUserList | requireView | user/index.ts#L4-6 | |
发布 | /updateUserById | 需要编辑 | user/index.ts#L8-10 | |
发布 | /deleteUserById | 需要编辑 | user/index.ts#L12-20 | |
game/index.ts | ||||
得到 | /getGameList | requireView | game/index.ts#L1-3 | |
得到 | /getGameById | requireView | game/index.ts#L4-6 | |
发布 | /updateGameById | 需要编辑 | game/index.ts#L8-10 | |
发布 | /deleteGameById | 需要编辑 | game/index.ts#L12-20 |
答案 19 :(得分:0)
在/routes
的应用中显示您的快速路线名称
app.get('/routes', (req, res) => {
res.send(app._router.stack
.filter(r => r.route)
.map(r => r.route.path))
})
网址 http:// localhost:3000 / routes
答案 20 :(得分:0)
在所有服务器中,我都是这样做的
app.get('/', (req, res) => {
console.log('home')
})
app.get('/home', (req, res) => {
console.log('/home')
})
function list(id) {
const path = require('path');
const defaultOptions = {
prefix: '',
spacer: 7,
};
const COLORS = {
yellow: 33,
green: 32,
blue: 34,
red: 31,
grey: 90,
magenta: 35,
clear: 39,
};
const spacer = (x) => (x > 0 ? [...new Array(x)].map(() => ' ').join('') : '');
const colorText = (color, string) => `\u001b[${color}m${string}\u001b[${COLORS.clear}m`;
function colorMethod(method) {
switch (method) {
case 'POST':
return colorText(COLORS.yellow, method);
case 'GET':
return colorText(COLORS.green, method);
case 'PUT':
return colorText(COLORS.blue, method);
case 'DELETE':
return colorText(COLORS.red, method);
case 'PATCH':
return colorText(COLORS.grey, method);
default:
return method;
}
}
function getPathFromRegex(regexp) {
return regexp.toString().replace('/^', '').replace('?(?=\\/|$)/i', '').replace(/\\\//g, '/');
}
function combineStacks(acc, stack) {
if (stack.handle.stack) {
const routerPath = getPathFromRegex(stack.regexp);
return [...acc, ...stack.handle.stack.map((stack) => ({ routerPath, ...stack }))];
}
return [...acc, stack];
}
function getStacks(app) {
// Express 3
if (app.routes) {
// convert to express 4
return Object.keys(app.routes)
.reduce((acc, method) => [...acc, ...app.routes[method]], [])
.map((route) => ({ route: { stack: [route] } }));
}
// Express 4
if (app._router && app._router.stack) {
return app._router.stack.reduce(combineStacks, []);
}
// Express 4 Router
if (app.stack) {
return app.stack.reduce(combineStacks, []);
}
// Express 5
if (app.router && app.router.stack) {
return app.router.stack.reduce(combineStacks, []);
}
return [];
}
function expressListRoutes(app, opts) {
const stacks = getStacks(app);
const options = {...defaultOptions, ...opts };
if (stacks) {
for (const stack of stacks) {
if (stack.route) {
const routeLogged = {};
for (const route of stack.route.stack) {
const method = route.method ? route.method.toUpperCase() : null;
if (!routeLogged[method] && method) {
const stackMethod = colorMethod(method);
const stackSpace = spacer(options.spacer - method.length);
const stackPath = path.resolve(
[options.prefix, stack.routerPath, stack.route.path, route.path].filter((s) => !!s).join(''),
);
console.info(stackMethod, stackSpace, stackPath);
routeLogged[method] = true;
}
}
}
}
}
};
expressListRoutes(app)
}
list(1);
如果你运行它,就会发生这种情况
获取 C:
获取 C:\home
答案 21 :(得分:0)
我发布了一个打印所有中间件和路由的软件包,这在尝试审核快速应用程序时非常有用。您将该软件包安装为中间件,因此它甚至可以自行打印出来:
https://github.com/ErisDS/middleware-stack-printer
它打印出一种像这样的树:
- middleware 1
- middleware 2
- Route /thing/
- - middleware 3
- - controller (HTTP VERB)
答案 22 :(得分:0)
路线详细信息列出了“ express”的路线:“ 4.x.x”,
import {
Router
} from 'express';
var router = Router();
router.get("/routes", (req, res, next) => {
var routes = [];
var i = 0;
router.stack.forEach(function (r) {
if (r.route && r.route.path) {
r.route.stack.forEach(function (type) {
var method = type.method.toUpperCase();
routes[i++] = {
no:i,
method: method.toUpperCase(),
path: r.route.path
};
})
}
})
res.send('<h1>List of routes.</h1>' + JSON.stringify(routes));
});
简单的代码输出
List of routes.
[
{"no":1,"method":"POST","path":"/admin"},
{"no":2,"method":"GET","path":"/"},
{"no":3,"method":"GET","path":"/routes"},
{"no":4,"method":"POST","path":"/student/:studentId/course/:courseId/topic/:topicId/task/:taskId/item"},
{"no":5,"method":"GET","path":"/student/:studentId/course/:courseId/topic/:topicId/task/:taskId/item"},
{"no":6,"method":"PUT","path":"/student/:studentId/course/:courseId/topic/:topicId/task/:taskId/item/:itemId"},
{"no":7,"method":"DELETE","path":"/student/:studentId/course/:courseId/topic/:topicId/task/:taskId/item/:itemId"}
]
答案 23 :(得分:0)
在Express 3.5.x上,我在启动应用程序之前添加此内容以在我的终端上打印路由:
var routes = app.routes;
for (var verb in routes){
if (routes.hasOwnProperty(verb)) {
routes[verb].forEach(function(route){
console.log(verb + " : "+route['path']);
});
}
}
也许它可以帮助...
答案 24 :(得分:-1)
答案 25 :(得分:-1)
快递4。*
//Obtiene las rutas declaradas de la API
let listPathRoutes: any[] = [];
let rutasRouter = _.filter(application._router.stack, rutaTmp => rutaTmp.name === 'router');
rutasRouter.forEach((pathRoute: any) => {
let pathPrincipal = pathRoute.regexp.toString();
pathPrincipal = pathPrincipal.replace('/^\\','');
pathPrincipal = pathPrincipal.replace('?(?=\\/|$)/i','');
pathPrincipal = pathPrincipal.replace(/\\\//g,'/');
let routesTemp = _.filter(pathRoute.handle.stack, rutasTmp => rutasTmp.route !== undefined);
routesTemp.forEach((route: any) => {
let pathRuta = `${pathPrincipal.replace(/\/\//g,'')}${route.route.path}`;
let ruta = {
path: pathRuta.replace('//','/'),
methods: route.route.methods
}
listPathRoutes.push(ruta);
});
});console.log(listPathRoutes)
答案 26 :(得分:-1)
这个对我有用
// Express 4.x
function getRoutes(stacks: any, routes: { path: string; method: string }[] = [], prefix: string = ''): { path: string; method: string }[] {
for (const stack of stacks) {
if (stack.route) {
routes.push({ path: `${prefix}${stack.route.path}`, method: stack.route.stack[0].method });
}
if (stack && stack.handle && stack.handle.stack) {
let stackPrefix = stack.regexp.source.match(/\/[A-Za-z0-9_-]+/g);
if (stackPrefix) {
stackPrefix = prefix + stackPrefix.join('');
}
routes.concat(getRoutes(stack.handle.stack, routes, stackPrefix));
}
}
return routes;
}
答案 27 :(得分:-1)
const routes = {}
function routerRecursion(middleware, pointer, currentName) {
if (middleware.route) { // routes registered directly on the app
if (!Array.isArray(pointer['routes'])) {
pointer['routes'] = []
}
const routeObj = {
path: middleware.route.path,
method: middleware.route.stack[0].method
}
pointer['routes'].push(routeObj)
} else if (middleware.name === 'router') { // inside router
const current = middleware.regexp.toString().replace(/\/\^\\\//, '').replace(/\\\/\?\(\?\=\\\/\|\$\)\/\i/, '')
pointer[current] = {}
middleware.handle.stack.forEach(function (handler) {
routerRecursion(handler, pointer[current], current)
});
}
}
app._router.stack.forEach(function (middleware) {
routerRecursion(middleware, routes, 'main')
});
console.log(routes);
app._router.stack.forEach(函数(中间件){ routerRecursion(中间件,路由,'main') }); 控制台日志(路由);
答案 28 :(得分:-2)
这是一种单行功能,用于在Express app
中漂亮地打印路线:
const getAppRoutes = (app) => app._router.stack.reduce(
(acc, val) => acc.concat(
val.route ? [val.route.path] :
val.name === "router" ? val.handle.stack.filter(
x => x.route).map(
x => val.regexp.toString().match(/\/[a-z]+/)[0] + (
x.route.path === '/' ? '' : x.route.path)) : []) , []).sort();