如何在Express中获取所有已注册的路线?


181

我有一个使用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,但我想现在可以了。仅供参考。


定义路由器后,我尝试过的所有解决方案均无法使用。它仅适用于每条路线-无法在我的应用中为我提供该路线的完整网址...
guy mograbi

1
@guymograbi,您可能想看看stackoverflow.com/a/55589657/6693775
nbsamar

Answers:


229

快递3.x

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

快递4.x

应用程序 -内置express()

app._router.stack

路由器 -内置express.Router()

router.stack

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


我正在使用节点0.10,它是app.routes.routes-这意味着我可以执行JSON.stringify(app.routes.routes)
guy mograbi 2014年

7
仅适用于Express 3.x,不适用于4.x。在4.x中,您应该检查app._router.stack
avetisk

14
这没有达到我的预期。app._router似乎不包括来自app.use('/ path',otherRouter);的路由;
Michael Cole

是否可以通过某种方式将其与命令行脚本集成在一起,以在不实际启动Web应用程序的情况下提取与实时应用程序完全相同的路由文件?
劳伦斯·西恩

4
至少在express 4.13.1 app._router.stack中未定义。
levigroker

54
app._router.stack.forEach(function(r){
  if (r.route && r.route.path){
    console.log(r.route.path)
  }
})

1
请注意,如果您使用的是Express Router(或其他中间件)之类的产品,则应该看到@Caleb稍长的答案,这种回答对此有所扩展。
伊恩·柯林斯

30

这将获取直接在应用程序上注册的路由(通过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}}

1
太好了,谢谢您的示例,该示例演示了如何通过中间件(如Express路由器)获取显示路由设置。
伊恩·柯林斯

30

我改编了一个旧帖子,不再满足我的需求。我已经使用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);
});

结果看起来像这样:

结果示例

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


2
这不适用于此处标识的嵌套路由:stackoverflow.com/questions/25260818/…–

2
当心此答案中的链接!它将我重定向到一个随机网站,并强制将其下载到我的计算机上。
泰勒·贝尔

29

这是我用来在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

console.log(server._router.stack.map(r => r.route).filter(r => r).map(r => ${Object.keys(r.methods).join(', ')} ${r.path}))
standup75年7

您将其放在app.js中的什么位置?
胡安

21

DEBUG=express:* node index.js

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

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


3
到目前为止最好的答案...一个环境变量!
杰夫

确实,最有用的答案。@nbsamar您甚至可以扩展它来表示DEBUG=express:paths仅用于查看路径输出,而不是所有其他调试消息。谢谢!
Mark Edington

19

hacky复制/粘贴回答道格·威尔逊Doug Wilson)github的特刊。肮脏但是像魅力。

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, []))

产生

屏幕抓取


为什么路线没有区别?
Vladimir Vukanac

1
这是唯一适用于Express 4.15的软件。没有其他人给出了完整的路径。唯一需要注意的是,它不会返回默认的根路径--它们都没有。
Shane

我不明白您为什么要绑定参数print
ZzZombo

@ZzZombo问道格·威尔逊(Doug Wilson),他写了它。如果需要,您可能可以清理所有这些。
AlienWebguy

11

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' ] } ]

2
这不适用于: server = express(); app1 = express(); server.use('/app1', app1); ...
Danosaure

8

记录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


1
这没有达到我的预期。app._router似乎不包括来自app.use('/ path',otherRouter);的路由;
Michael Cole

@MichaelCole您是否看过Golo Roden的以下回答?
Labithiotis 2014年

@ Dazzler13我玩了一个小时,但无法正常工作。Express 4.0。制造的应用,制造的路由器,app.use(path,router),路由器路由未出现在app._router中。例?
Michael Cole

以下@Caleb的示例非常适合使用express.Router之类的路由处理(如果这是您的问题)。请注意,使用中间件设置的路由(包括express.Router)可能不会立即显示,您可能需要在app._router中进行检查之前稍加延迟(即使使用@Caleb的方法)。
伊恩·柯林斯

8

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的答案

希望这可以帮助


5

我受到Labithiotis的express-list-routes的启发,但我想一口气概述所有路由和粗暴的url,而不是指定路由器,并且每次都要弄清楚前缀。我想到的是简单地用我自己的函数替换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 
└────────┴───────────────────────────────────┘

踢屁股。


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)

列出已安装的路由与此软件包一起使用:github.com/AlbertoFdzM/express-list-endpoints
jsaddwater

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", "..."]

编辑:代码改进


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

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

O / P:

[
    "get -> /posts/:id",
    "post -> /posts",
    "patch -> /posts"
]

2

初始化快递路由器

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": ....}

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

也许可以帮忙...


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


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"}
]

0

只需使用此npm软件包,它将以格式良好的表格视图形式提供Web输出以及终端输出。

在此处输入图片说明

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


2
这其他的包装有更多的接受。npmjs.com/package/express-list-endpoints。对于每周34次下载,我的得分为21.111。但是,express-routes-catalogue也将路径显示为HTML,而其他路径则不显示。
mayid

1
不错,软件包的文档与要求时的实际软件包名称有所不同,此软件包与提到的所有其他软件包一样,仅显示包含其中的单层路线
hamza khan

@hamzakhan ps感谢您的更新。我是作者,很快将在文档中进行更新。
维杰

0

您可以实现一个/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


-1

这是一个单行功能,用于在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();

-2

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

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

它打印出一种像这样的树:

- middleware 1
- middleware 2
- Route /thing/
- - middleware 3
- - controller (HTTP VERB)  
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.