232

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

例如,如果我执行了

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

我想检索一个对象(或与之等效的对象),例如:

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

这可能吗?如果可以,怎么做?

4

30 回答 30

282

快递 3.x

好的,我自己找到的......它只是app.routes:-)

快递 4.x

应用程序- 用express()

app._router.stack

路由器- 内置express.Router()

router.stack

注意:堆栈也包括中间件功能,它应该被过滤以仅获取“路由”

于 2013-02-18T11:11:55.607 回答
69
app._router.stack.forEach(function(r){
  if (r.route && r.route.path){
    console.log(r.route.path)
  }
})
于 2015-01-22T10:52:56.137 回答
45

DEBUG=express:* node index.js

如果您使用上述命令运行您的应用程序,它将使用DEBUG模块启动您的应用程序并提供路由,以及所有正在使用的中间件功能。

您可以参考:ExpressJS - 调试调试

于 2019-04-09T09:38:07.167 回答
44

这将获取直接在应用程序上注册的路由(通过 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}}
于 2015-01-28T18:34:55.817 回答
38

这是我用来获取 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
于 2016-01-29T16:12:34.083 回答
36

我已经根据我的需要改编了一篇不再在线的旧帖子。我使用了 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);
});

结果如下所示:

结果示例

这只是一个例子,但可能有用..我希望..

于 2015-02-20T10:24:58.553 回答
31

由Doug Wilsonexpress 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, '$1').split('/')
      : '<complex:' + thing.toString() + '>'
  }
}

app._router.stack.forEach(print.bind(null, []))

生产

抓屏

于 2017-09-25T05:10:08.867 回答
18

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' ] } ]
于 2017-06-06T17:45:55.380 回答
14

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));

看起来像这样:

[
  {
    "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 的回答

希望这可以帮助

于 2019-03-08T22:52:21.890 回答
12

您可以实现一个/get-all-routesAPI:

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);
});

这是一个演示:https ://glitch.com/edit/#!/get-all-routes-in-nodejs

于 2020-07-06T09:55:27.660 回答
10

在 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);

日志输出:

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

把它做成一个 NPM https://www.npmjs.com/package/express-list-routes

于 2014-10-09T09:51:29.303 回答
6

我受到 Labithiotis 的 express-list-routes 的启发,但我想一次性了解我所有的路由和粗略的 url,而不是指定路由器,并且每次都找出前缀。我想出的办法是简单地用我自己的函数替换 app.use 函数,该函数存储 baseUrl 和给定的路由器。从那里我可以打印我所有路线的任何表格。

注意这对我有用,因为我在应用程序对象中传递的特定路由文件(函数)中声明了我的路由,如下所示:

// 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);
}

这允许我传入另一个具有虚假使用功能的“应用程序”对象,并且我可以获得所有路由。这对我有用(为了清楚起见删除了一些错误检查,但仍然适用于示例):

// 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 │
└────────┴───────────────────────────────────┘

哪个踢屁股。

于 2015-07-19T13:00:41.347 回答
5

在您的应用程序中/routes显示您的快速路线名称

app.get('/routes', (req, res) => {
    res.send(app._router.stack
        .filter(r => r.route) 
        .map(r => r.route.path))
})

http://localhost:3000/routes

于 2020-09-30T20:31:30.967 回答
4

快递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
}

更新1:

由于 Express 4 的内部限制,无法检索已安装的应用程序和已安装的路由器。例如,无法从此配置中获取路由。

const subApp = express()
app.use('/sub/app', subApp)

const subRouter = express.Router()
app.use('/sub/route', subRouter)
于 2018-03-07T12:29:42.407 回答
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", "..."]

编辑:代码改进

于 2018-07-16T18:25:39.927 回答
3

@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));
于 2017-12-13T23:35:35.117 回答
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": ....}
于 2020-02-01T06:26:09.860 回答
2

这对我有用

let routes = []
app._router.stack.forEach(function (middleware) {
    if(middleware.route) {
        routes.push(Object.keys(middleware.route.methods) + " -> " + middleware.route.path);
    }
});

console.log(JSON.stringify(routes, null, 4));

输出/输出:

[
    "get -> /posts/:id",
    "post -> /posts",
    "patch -> /posts"
]
于 2017-10-31T20:32:42.777 回答
2

在所有服务器中,我就是这样做的

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

于 2021-05-17T16:53:03.667 回答
1

在 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']);
      });
    }
}

也许它可以帮助...

于 2014-07-21T14:37:25.093 回答
0

所以我在看所有的答案..最不喜欢..从一些..做了这个:

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 种方法的正常路线..所以我推断这就是全部..

于 2018-08-27T20:51:52.740 回答
0

路线详情为 "express": "4.xx",

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"}
]
于 2018-10-03T15:51:15.840 回答
0

只需使用这个 npm 包,它将以格式良好的表格视图提供 Web 输出和终端输出。

在此处输入图像描述

https://www.npmjs.com/package/express-routes-catalogue

于 2019-10-13T09:25:54.890 回答
0

对于快递 4.x

这是一个总 1 班轮,适用于添加到的app路线和添加到的路线express.Router()

它返回这个结构。

[
    {
        "path": "/api",
        "methods": {
            "get": true
        }
    },
    {
        "path": "/api/servermembers/",
        "methods": {
            "get": true
        }
    },
    {
        "path": "/api/servermembers/find/:query",
        "methods": {
            "get": true
        }
    }
]

使用的模块express.Router()需要像这样导出:

module.exports = {
  router,
  path: "/servermembers",
};

并像这样添加:

app.use(`/api${ServerMemberRoutes.path}`, ServerMemberRoutes.router);
app.get(
  "/api",
  /**
   * Gets the API's available routes.
   * @param {request} _req
   * @param {response} res
   */
  (_req, res) => {
    res.json(
      [app._router, ServerMemberRoutes]
        .map((routeInfo) => ({
          entityPath: routeInfo.path || "",
          stack: (routeInfo?.router?.stack || routeInfo.stack).filter(
            (stack) => stack.route
          ),
        }))
        .map(({ entityPath, stack }) =>
          stack.map(({ route: { path, methods } }) => ({
            path: entityPath ? `/api${entityPath}${path}` : path,
            methods,
          }))
        ).flat()
    );
  }
);

当然,/api如果需要,基本 url 前缀也可以存储在变量中。

于 2022-01-13T21:00:20.037 回答
-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)
于 2020-07-18T19:14:17.807 回答
-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;
}
于 2021-02-16T05:20:15.800 回答
-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(function (middleware) { routerRecursion(middleware, routes, 'main') }); console.log(路由);

于 2021-03-23T20:46:15.843 回答
-1

静态代码分析方法。

该工具无需启动服务器即可分析源代码并显示路由信息。

npx express-router-dependency-graph --rootDir=path/to/project
# json or markdown output

https://github.com/azu/express-router-dependency-graph

示例输出:

文件 方法 路由 中间件 文件路径
用户/index.ts
得到 /getUserById 需要查看 用户/index.ts#L1-3
得到 /getUserList 需要查看 用户/index.ts#L4-6
邮政 /updateUserById 要求编辑 用户/index.ts#L8-10
邮政 /deleteUserById 要求编辑 用户/index.ts#L12-20
游戏/index.ts
得到 /getGameList 需要查看 游戏/index.ts#L1-3
得到 /getGameById 需要查看 游戏/index.ts#L4-6
邮政 /updateGameById 要求编辑 游戏/index.ts#L8-10
邮政 /deleteGameById 要求编辑 游戏/index.ts#L12-20
于 2021-04-20T12:17:39.563 回答
-2

我发布了一个打印所有中间件和路由的包,在尝试审核快速应用程序时非常有用。您将包安装为中间件,因此它甚至会自行打印:

https://github.com/ErisDS/middleware-stack-printer

它打印一种树,如:

- middleware 1
- middleware 2
- Route /thing/
- - middleware 3
- - controller (HTTP VERB)  
于 2018-11-20T16:33:18.093 回答
-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();
于 2020-04-29T03:10:14.130 回答