我有一个使用Node.js和Express构建的web应用程序。现在,我想列出所有已注册的路由及其相应的方法。
例如,如果我执行了
app.get('/', function (...) { ... });
app.get('/foo/:id', function (...) { ... });
app.post('/foo/:id', function (...) { ... });
我想检索一个对象(或与之等效的对象),例如:
{
get: [ '/', '/foo/:id' ],
post: [ '/foo/:id' ]
}
这是可能的吗?如果可能,是如何实现的?
更新:同时,我创建了一个名为get-routes的npm包,它从给定的应用程序中提取路由,它解决了这个问题。目前,只支持Express 4.x,但我想现在还可以。仅供参考。
发布于 2013-02-18 19:11:56
express 3.x
好吧,我自己找到的.这只是app.routes
:-)
express 4.x
Applications -使用express()
构建
app._router.stack
Routers -使用express.Router()
构建
router.stack
注释:堆栈也包括中间件功能,应该对其进行过滤以仅获得“路由”。
发布于 2015-01-22 18:52:56
app._router.stack.forEach(function(r){
if (r.route && r.route.path){
console.log(r.route.path)
}
})
发布于 2015-01-29 02:34:56
这将获取直接在应用程序上注册的路由(通过app.VERB)和注册为路由器中间件的路由(通过app.use)。Express 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}}
https://stackoverflow.com/questions/14934452
复制相似问题