如何在Express App上找到中间件的路径

时间:2018-08-11 10:52:45

标签: node.js express routing middleware express-4

所以我的路由器看起来像这样:

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

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

当我管理.log该中间件时,我得到:

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 }

我只能看到中间件的路由路径的部分是regexp,但提取起来并不容易...

任何想法我该如何从Express应用程序获取路径

2 个答案:

答案 0 :(得分:0)

the constructor看,原始路径没有保留在任何地方。

答案 1 :(得分:0)

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;

希望您将获得所有注册路径