删除 NodeJS Express 中的路由映射 [英] Remove route mappings in NodeJS Express

查看:43
本文介绍了删除 NodeJS Express 中的路由映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个映射为:

app.get('/health/*', function(req, res){
    res.send('1');
});

如何在运行时删除/重新映射此路由到空处理程序?

How can I remove / remap this route to an empty handler at runtime?

推荐答案

这会删除 app.use 中间件和/或 app.VERB (get/post) 路由.在 express@4.9.5 上测试

This removes app.use middlewares and/or app.VERB (get/post) routes. Tested on express@4.9.5

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);
}

请注意,它要求中间件/路由功能具有名称:

Note that it requires that the middleware/route functions have names:

app.use(function yourMiddlewareFunctionName(req, res, next) {
    ...          ^ named function
});

如果函数是匿名的,它将不起作用:

It won't work if the function is anonymous:

app.get('/path', function(req, res, next) {
    ...          ^ anonymous function, won't work                    
});

这篇关于删除 NodeJS Express 中的路由映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆