简体   繁体   中英

parse express app.js route

如何基于all.js文件获取所有可用路由的列表?

You can dig around inside the app.routes object, which is an instance of Router . The easiest way would probably be to load up your app in an interactive listener and just take a look at the various objects contained in app.routes .

If you want to be more methodical, you can read the source for the router and route objects, eg https://github.com/visionmedia/express/blob/master/lib/router/route.js

There's actually a better way of doing this, TJ Holowaychuck (the author of Express) made a gist with it:

app.routes.all().forEach(function(route){
  console.log('  \033[90m%s \033[36m%s\033[0m', route.method.toUpperCase(), route.path);
});
for(var type in app.routes.routes) {
  console.log(type+":");
  for(var rts in app.routes.routes[type]) {
    console.log(app.routes.routes[type][rts]);
  }
}

The routes object has verbs as properties. You can iterate over them and construct a list of all routes, methods etc.

I created a Gist creating a self describing rest-api. I'm sure it can be improved but if you want you can see how I iterate over the routes object there.

https://gist.github.com/morkeleb/5705647

Feedback is welcome on the Gist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM