0

i want to return all registered route in my project.

i use this code for retur nall routes :

const app = require("express");
let routers = app._router.stack
  .filter((r) => r.route)
  .map((r) => {
    return {
      method: Object.keys(r.route.methods)[0].toUpperCase(),
      path: r.route.path,
    };
  });

but it not worked and show me this error :

(node:13092) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'stack' of undefined

Edit :

my routes :

    const express=require('express');
const router=express.Router();
const roleRouter=require('./role');
const userRouter=require('./user');
const managerRouter=require('./manager');
const accessRouter=require('./access');
const settingRouter=require('./setting');


router.use('/role',roleRouter);

router.use('/user',userRouter);

router.use('/manager',managerRouter);

router.use('/access',accessRouter);

router.use('/setting',settingRouter);

module.exports=router;

and use that in the main js file :

   app.use(require("./routes/index"));

how can i return all routes in my projects ???

kianoush dortaj
  • 411
  • 7
  • 24

1 Answers1

3

the app supposed to be created with express function

const express = require('express');
const app = express();

then you can get all of the registered routes, make sure to put this line after you register your app routes

console.log(app._router);

So the full code will look like this:

const express = require('express');
const app = express();
const port = 3000;

console.log(app._router); // undefined

app.get('/', (req, res) => res.send('Hello World!'))

console.log(app._router.stack); // showing routes

app.listen(port)

EDIT:

To return all of your routes from your API endpoint, you can do this (not sure why you want to do this though)

const express = require('express');
const app = express();
const port = 5000;

app.get('/', (req, res) => {
    res.json(app._router.stack);
})

app.get('/example', (req, res) => {
    // This route will also be listed when you call "/" 
    res.send();
})

app.listen(port)
Owl
  • 6,337
  • 3
  • 16
  • 30