背景
我想统计出 Express 的Web项目中已注册的路由,即统计出有哪些可调用的接口
示例项目:
const express = require("express");
const app = express();
const api = express();
api.all('/api/*',express.json());
api.get('/api/get',function (req,res){
res.send(req.route);})
api.post('/api/post/:id',function (req,res){
res.send(req.route);})
api.route('/api/route')
.get(function (req,res){
res.send(req.route);})
.post(function (req,res){
res.send(req.route);})
app.use('/test',api);
app.listen(8899,'localhost',function (){
console.log('Express server listening at http://localhost:8899');})
统计要求
[
{
"method": "GET","path": "/test/api/get"},
{
"method": "POST","path": "/test/api/post/:id"},
{
"method": "GET","path": "/test/api/route"},
{
"method": "POST","path": "/test/api/route"},
{
"method": "GET","path": "/test/get_all_routes"}
]
要求:
- path中要包含挂载点路径,如上 app.use(“/test”,api),路径要包含 /test
- 不需要 api.all() 中的路由,该方法实际上只是对匹配到指定路由的HTTP方法,触发回调
- 对于挂载到api应用的路由也给统计出来,如 express.Router() 创建的路由里的path
获取已注册路由
测试项目
先给出用来测试获取已注册路由的项目
.
├── app.js
├── routes
│ ├── users
│ │ ├── index.js
│ │ ├── user_v1.js
│ │ └── user_v2.js
│ └── orders
│ │ ├── index.js
│ │ ├── order_v1.js
│ │ └── order_v2.js
给出各文件的主要代码
app.js 主应用启动文件
const express = require("express");
const app = express();
const api = express();
const cookieParser = require('cookie-parser');
const userapi = require("./routes/users");
const orderapi = require("./routes/orders");
const orderv2 = require("./routes/orders/order_v2");
api.use('/userapi', userapi);
api.use('/orderapi', orderapi);
api.use('/orderapi', orderv2);
api.use(cookieParser());
api.all('/api/*',express.json());
api.get('/api/get',function (req,res){
res.send(req.route);})
api.post('/api/post/:id',function (req,res){
res.send(req.route);})
api.route('/api/route')
.get(function (req,res){
res.send(req.route);})
.post(function (req,res){
res.send(req.route);})
app.use('/test',api);
app.listen(8899,'localhost',function (){
console.log('Express server listening at http://localhost:8899');
})
/routes/users 相关路由文件
// /routes/users/index.js 文件
const express = require('express');
const userapi = ex