Express'te tüm kayıtlı rotaları nasıl alabilirim?


181

Node.js ve Express kullanılarak oluşturulmuş bir web uygulamam var. Şimdi tüm kayıtlı rotaları uygun yöntemlerle listelemek istiyorum.

Örneğin, idam etmiş olsaydım

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

Bir nesne (veya buna eşdeğer bir şey) gibi almak istiyorum:

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

Bu mümkün mü ve eğer mümkünse nasıl?


GÜNCELLEME: Bu arada, bu sorunu çözen belirli bir uygulamadan yolları ayıklayan get-route adında bir npm paketi oluşturdum . Şu anda, sadece Express 4.x desteklenmektedir, ancak sanırım şimdilik bu iyi. Sadece FYI.


Denediğim tüm çözümler, Yönlendiriciler tanımlandığında çalışmaz. Sadece rota başına çalışır - hangi benim app o rota için tüm url vermez ...
guy mograbi

1
@guymograbi bakmak isteyebilirsiniz stackoverflow.com/a/55589657/6693775
nbsamar

Yanıtlar:


230

ekspres 3.x

Tamam, kendim buldum ... sadece app.routes:-)

ekspres 4.x

Uygulamalar - ile oluşturulduexpress()

app._router.stack

Yönlendiriciler - dahiliexpress.Router()

router.stack

Not : Yığın ara katman yazılımı işlevlerini de içerir, yalnızca "yolları" almak için filtrelenmelidir .


0.10 düğümü kullanıyorum ve app.routes.routes- JSON.stringify (app.routes.routes) yapabileceğim anlamına geliyordu
adam mograbi

7
4.x için değil, yalnızca Express 3.x için çalışır. 4.x'te, kontrol etmelisinizapp._router.stack
avetisk

14
Bu benim için beklendiği gibi çalışmadı. app._router, app.use ('/ path', otherRouter) 'dan gelen yolları içermiyor gibi görünüyor;
Michael Cole

Bunun, bir web uygulamasını başlatmadan canlı uygulamanın yaptığıyla aynı rota dosyalarını çekecek bir komut satırı komut dosyasıyla entegre edilmesinin bir yolu var mı?
Lawrence I.Siden

5
En azından ifade 4.13.1 app._router.stacktanımsızdır.
levigroker

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

1
Express Router (veya başka bir ara katman yazılımı) gibi bir şey kullanıyorsanız, bu yaklaşımda genişleyen @Caleb'in biraz daha uzun yanıt görmesi gerektiğini unutmayın.
Iain Collins

31

Bu, doğrudan uygulamaya kaydedilen rotaları (app.VERB aracılığıyla) ve yönlendirici ara katman yazılımı olarak kaydedilen rotaları (app.use aracılığıyla) alır. Hızlı 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
Mükemmel, Express yönlendirici gibi ara katman yazılımı aracılığıyla ayarlanmış görüntü yollarının nasıl alınacağını gösteren bir örnek için teşekkürler.
Iain Collins

31

Artık ihtiyaç duyduğum çevrimiçi olmayan eski bir gönderiyi uyarladım. Express.Router () kullandım ve rotalarımı şöyle kaydettirdim:

var questionsRoute = require('./BE/routes/questions');
app.use('/api/questions', questionsRoute);

Document.js dosyasını apiTable.js'de yeniden adlandırdım ve şu şekilde uyarladım:

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

o zaman böyle benim server.js denir:

var server = app.listen(process.env.PORT || 5000, function () {
    require('./BE/utils/apiTable')('/api/questions', questionsRoute.stack);
});

Sonuç şuna benzer:

Sonuç örneği

Bu sadece bir örnek ama yararlı olabilir .. umarım ..


2
Bu, burada tanımlandığı gibi iç içe yollar için çalışmaz: stackoverflow.com/questions/25260818/…

2
Bu cevaptaki bağlantıya dikkat edin! Beni rastgele bir web sitesine yönlendirdi ve bilgisayarıma indirmeye zorladı.
Tyler Bell

29

İşte 4.x'te kayıtlı yolları elde etmek için kullandığım küçük bir şey

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}))
stand up75

app.js'de bunu nereye koyuyorsunuz ??
Juan

21

DEBUG=express:* node index.js

Uygulamanızı yukarıdaki komutla çalıştırırsanız, uygulamanızı DEBUGmodülle başlatır ve rotaları ve kullanımda olan tüm ara katman yazılımı işlevlerini verir.

Şunlara başvurabilirsiniz: ExpressJS - Hata ayıklama ve hata ayıklama .


3
Şimdiye kadar en iyi cevap ... bir env var!
Jeef

Gerçekten, en yararlı cevap. @nbsamar DEBUG=express:pathsDiğer tüm hata ayıklama iletilerini değil, yalnızca yol çıktısını görmek için kullanmak üzere bile genişletebilirsiniz . Teşekkürler!
Mark Edington

19

Hacky kopyalama / cevabı nezaket yapıştırın Doug Wilson üzerinde ekspres github konular . Kirli ama bir cazibe gibi çalışır.

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

üretir

screengrab


Rotalar neden farklı değil?
Vladimir Vukanac

1
Express 4.15 ile benim için çalışan tek kişi bu. Hiçbiri tam yolu vermedi. Tek uyarı, varsayılan kök yolunu geri vermemesidir / - hiçbiri yapmaz.
Shane

Neden argümanları bağladığınızı anlamıyorum print?
ZzZombo

@ZzZombo Doug Wilson'a sor, yazdı. İsterseniz muhtemelen tüm bunları temizleyebilirsiniz.
AlienWebguy

11

https://www.npmjs.com/package/express-list-endpoints gayet iyi çalışıyor.

Misal

Kullanımı:

const all_routes = require('express-list-endpoints');
console.log(all_routes(app));

Çıktı:

[ { path: '*', methods: [ 'OPTIONS' ] },
  { path: '/', methods: [ 'GET' ] },
  { path: '/sessions', methods: [ 'POST' ] },
  { path: '/sessions', methods: [ 'DELETE' ] },
  { path: '/users', methods: [ 'GET' ] },
  { path: '/users', methods: [ 'POST' ] } ]

2
Bu ile çalışmaz: server = express(); app1 = express(); server.use('/app1', app1); ...
Danosaure

8

Ekspres 4'teki tüm rotaları günlüğe kaydetme işlevi (v3 ~ için kolayca ayarlanabilir)

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

Günlük çıktısı:

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

Bunu bir NPM haline getirdi https://www.npmjs.com/package/express-list-routes


1
Bu benim için beklendiği gibi çalışmadı. app._router, app.use ('/ path', otherRouter) 'dan gelen yolları içermiyor gibi görünüyor;
Michael Cole

@MichaelCole Golo Roden'den aşağıdaki cevaba baktınız mı?
Labithiotis

@ Dazzler13 Bununla bir saat oynadım ve çalışamadım. Express 4.0. Yapılan uygulama, yapılan yönlendirici, app.use (yol, yönlendirici), yönlendirici yolları app._router'da görünmedi. Misal?
Michael Cole

Aşağıdaki @Caleb'den gelen örnek, express.Router gibi bir sorunla işlenmiş rotalar için iyi çalışır. Ara katman yazılımı (express.Router dahil) ile ayarlanan rotaların hemen görünmeyebileceğini ve app._router'da (@Caleb yaklaşımını kullanarak bile) kontrol etmeden önce kısa bir gecikme eklemeniz gerekebileceğini unutmayın.
Iain Collins

8

json çıkışı

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

buna benzer:

[
  {
    "method": "GET",
    "path": "/api/todos"
  },
  {
    "method": "POST",
    "path": "/api/todos"
  },
  {
    "method": "PUT",
    "path": "/api/todos/:id"
  },
  {
    "method": "DELETE",
    "path": "/api/todos/:id"
  }
]

dize çıktısı

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

buna benzer:

GET    /api/todos  
POST   /api/todos  
PUT    /api/todos/:id  
DELETE /api/todos/:id

Bu dayanmaktadır @ corvid en cevabı

Bu yardımcı olur umarım


5

Labithiotis'in ekspres liste rotalarından ilham aldım, ancak tek seferde tüm rotalarım ve kaba URL'lerime genel bir bakış istedim ve bir yönlendirici belirtmedim ve her seferinde öneki bulmaya çalıştım. Ben geldi bir şey sadece app.use işlevini baseUrl ve verilen yönlendirici depolayan kendi işlevi ile değiştirmek oldu. Oradan tüm rotalarımın herhangi bir tablosunu yazdırabilirim.

NOT bu benim için çalışır, çünkü uygulama nesnesinde geçen belirli bir rota dosyasında (fonksiyon) rotalarımı beyan ederim, şöyle:

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

Bu sahte kullanım fonksiyonu ile başka bir 'app' nesnesini geçmek için izin verir ve ben TÜM yolları alabilirsiniz. Bu benim için çalışıyor (netlik için bazı hata denetimlerini kaldırdı, ancak yine de örnek için çalışıyor):

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

Bu tam örnek (bazı temel CRUD yönlendiricileriyle) yeni test edilmiş ve yazdırılmıştır:

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 kullanarak böyle bir şey var:

┌────────┬───────────────────────┐
         => 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 
└────────┴───────────────────────────────────┘

Hangi eşek başladı.


4

Hızlı 4

Uç noktaları ve iç içe yönlendiriciler içeren bir Express 4 yapılandırması verilir

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 cevabını genişleterek, tüm rotaları özyineli ve sıralı olarak elde etmek mümkündür.

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
}

Temel dize çıktısı için.

infoAboutRoutes(app)

Konsol çıkışı

/**
* 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
}

Güncelleme 1:

Express 4'ün dahili sınırlamaları nedeniyle, bağlı uygulamayı ve bağlı yönlendiricileri almak mümkün değildir. Örneğin, bu konfigürasyondan rota elde etmek mümkün değildir.

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

const subRouter = express.Router()
app.use('/sub/route', subRouter)

Takılı güzergahların listelenmesi şu paketle çalışır: github.com/AlbertoFdzM/express-list-endpoints
jsaddwater

4

Bazı ayarlamalar gerekir, ancak Express v4 için çalışmalıdır. İle eklenen bu rotalar dahil .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", "..."]

düzenleme: kod geliştirmeleri


3

@ Prranay'ın cevabına biraz güncellenmiş ve daha işlevsel bir yaklaşım:

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

Bu benim için çalıştı

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

Ekspres yönlendiriciyi başlat

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

Kullanıcı denetleyicisini içe aktar

var userController = require('./controller/userController');

Kullanıcı yolları

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 rotalarını dışa aktarma

module.exports = router;

Çıktı

{"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'te, terminalime rotaları yazdırmak için uygulamaya başlamadan önce bunu ekliyorum:

var routes = app.routes;
for (var verb in routes){
    if (routes.hasOwnProperty(verb)) {
      routes[verb].forEach(function(route){
        console.log(verb + " : "+route['path']);
      });
    }
}

Belki yardımcı olabilir ...


1

Bir /get-all-routesAPI uygulayabilirsiniz :

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

İşte bir demo: https://glitch.com/edit/#!/get-all-routes-in-nodejs


Obs: Bu ekspres 'Router ()
Gustavo Morais

0

Yani tüm cevaplara bakıyordum .. en çok hoşuma gitmedi .. birkaçını aldı .. bunu yaptı:

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

güzel değil .. ama iç içe, ve hile yapar

Ayrıca orada 20 not edin ... Ben sadece 20 yöntem ile normal bir rota olmayacağını varsayalım .. bu yüzden hepsi olduğunu düşünüyorum ..


0

Güzergah bilgileri "express" için güzergah listesi: "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));
});

KODUN BASİT ÇIKIŞI

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

Sadece bu npm paketini kullanın, web çıktısının yanı sıra terminal çıktısını güzel biçimlendirilmiş tablo görünümünde verecektir.

resim açıklamasını buraya girin

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


2
Bu diğer paket tonlarca kabul görüyor. npmjs.com/package/express-list-endpoints . 34 haftalık indirmelere karşı 21.111 tane. Ancak, express-routes-cataloguerotaları HTML olarak görüntüler, diğeri bunu yapmaz.
mayid

1
fena değil, paketin belgelendirilmesi gerektiğinde gerçek paket adından farklıdır ve bahsedilen tüm diğer paketler gibi sadece paketin dahil olduğu tek katmanlı yolları gösterir
hamza khan

@hamzakhan ps güncelleme için teşekkürler. ben yazarım, yakında belgelerde güncellenecektir.
Vijay

-1

Express'teki rotaları güzel yazdırmak için tek satırlık bir işlev 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();

-1

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

-2

Hızlı bir uygulamayı denetlemeye çalışırken gerçekten yararlı olan tüm ara katman yazılımlarını ve rotaları basan bir paket yayınladım. Paketi ara katman yazılımı olarak bağlarsınız, böylece kendini yazdırır:

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

Bir çeşit ağaç basar:

- middleware 1
- middleware 2
- Route /thing/
- - middleware 3
- - controller (HTTP VERB)  
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.