我有一条路线映射为:
app.get('/health/*', function(req, res){ res.send('1'); });
如何在运行时删除/重新映射此路由到空处理程序?
这将删除app.use中间件和/或app.VERB(获取/发布)路由。在express@4.9.5上测试
app.use
app.VERB
var routes = app._router.stack; routes.forEach(removeMiddlewares); function removeMiddlewares(route, i, routes) { switch (route.handle.name) { case 'yourMiddlewareFunctionName': case 'yourRouteFunctionName': routes.splice(i, 1); } if (route.route) route.route.stack.forEach(removeMiddlewares); }
请注意,它 要求 中间件/路由功能具有 名称 :
app.use(function yourMiddlewareFunctionName(req, res, next) { ... ^ named function });
如果该函数是匿名的, 它将不起作用 :
app.get('/path', function(req, res, next) { ... ^ anonymous function, won't work });