Vladimir Djukic
Vladimir Djukic

Reputation: 965

How to find path on express app for middleware

So my router looks like this:

const app = express();
app.use('/login', router);

app.listen(3000, () => {
    app._router.stack.forEach((middleware: any) => {
     console.log(middleware);
    })
})

when I console .log that middleware I get:

Layer {
  handle:
   { [Function: router]
     params: {},
     _params: [],
     caseSensitive: undefined,
     mergeParams: undefined,
     strict: undefined,
     stack: [ [Layer] ] },
  name: 'router',
  params: undefined,
  path: undefined,
  keys: [],
  regexp:
   { /^\/login\/?(?=\/|$)/i fast_star: false, fast_slash: false },
  route: undefined }

Only part where I can see route path for the middleware is regexp but it is not easy to extract...

Any idea how can I get path from express app

Upvotes: 2

Views: 878

Answers (2)

Muhammad Numan
Muhammad Numan

Reputation: 25353

app.js

const app = express();
const { getRoutes } = require('./utils/getRoutes');
getRoutes(app)

getRoutes.js

let counter = 0;
const getRoutes = (app) => {
    let routes = [];
    app._router.stack.forEach(function(middleware) {
        let regexp = middleware.regexp.toString();
        regexp = regexp.slice(3);
        const index = regexp.indexOf('/?(');
        regexp = regexp.slice(0, index - 1);

        if (middleware.route) {
            routes.push({ child: middleware.route.path, parent: regexp });
        } else if (middleware.name === 'router') {
            middleware.handle.stack.forEach(function(handler) {
                counter++;

                if (counter % 2 === 1) {
                    return;
                }
                route = handler.route;
                route && routes.push({ child: route.path, parent: regexp });
            });
        }
    });

    return routes
};

module.exports.getRoutes = getRoutes;

hope you will get all your register path

Upvotes: 0

robertklep
robertklep

Reputation: 203231

Looking at the constructor, the original path isn't retained anywhere.

Upvotes: 0

Related Questions