1

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

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 }

只有我可以看到中间件的路由路径的部分是正则表达式,但它不容易提取......

知道如何从快递应用程序中获取路径

4

2 回答 2

0

查看构造函数,原始路径不会保留在任何地方。

于 2018-08-11T11:01:11.770 回答
0

应用程序.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;

希望你能得到你所有的注册路径

于 2019-11-29T12:07:11.617 回答