删除 NodeJS Express 中的路由映射
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10378690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove route mappings in NodeJS Express
提问by lostinplace
I have a route mapped as:
我有一条路线映射为:
app.get('/health/*', function(req, res){
res.send('1');
});
How can I remove / remap this route to an empty handler at runtime?
如何在运行时将此路由删除/重新映射到空处理程序?
回答by laggingreflex
This removes app.usemiddlewares and/or app.VERB(get/post) routes. Tested on [email protected]
这将删除app.use中间件和/或app.VERB(获取/发布)路由。在 [email protected] 上测试
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 requiresthat the middleware/route functions have names:
请注意,它要求中间件/路由功能具有名称:
app.use(function yourMiddlewareFunctionName(req, res, next) {
... ^ named function
});
It won't workif the function is anonymous:
如果函数是匿名的,它将不起作用:
app.get('/path', function(req, res, next) {
... ^ anonymous function, won't work
});
回答by Brad
Express (at least as of 3.0.5) keeps all of its routes in app.routes. From the documentation:
Express(至少从 3.0.5 开始)将其所有路由保存在app.routes. 从文档:
The app.routes object houses all of the routes defined mapped by the associated HTTP verb. This object may be used for introspection capabilities, for example Express uses this internally not only for routing but to provide default OPTIONS behaviour unless app.options() is used. Your application or framework may also remove routes by simply by removing them from this object.
app.routes 对象包含由关联的 HTTP 动词映射的所有路由。此对象可用于自省功能,例如 Express 在内部不仅将其用于路由,还用于提供默认的 OPTIONS 行为,除非使用 app.options()。您的应用程序或框架也可以通过简单地从该对象中删除路由来删除路由。
Your app.routesshould look similar to this:
你app.routes应该看起来像这样:
{ get:
[ { path: '/health/*',
method: 'get',
callbacks: [Object],
keys: []}]
}
So, you should be able to loop through app.routes.getuntil you find what you are looking for, and then delete it.
因此,您应该能够循环遍历,app.routes.get直到找到您要查找的内容,然后将其删除。
回答by Brennan Cheung
The above approach requires you have a named function for the route. I wanted to do this as well but didn't have named functions for routes so I wrote an npm module that can remove routes by specifying the routing path.
上述方法要求您为路由指定一个命名函数。我也想这样做,但没有为路由命名函数,所以我编写了一个 npm 模块,可以通过指定路由路径来删除路由。
Here you go:
干得好:
回答by kybernetikos
It is possible to remove mounted handlers (added with app.use) while the server is running, although there is no API to do this, so it isn't recommended.
可以在服务器运行时删除已安装的处理程序(通过 app.use 添加),尽管没有 API 可以执行此操作,因此不建议这样做。
/* Monkey patch express to support removal of routes */
require('express').HTTPServer.prototype.unmount = function (route) {
for (var i = 0, len = this.stack.length; i < len; ++i) {
if (this.stack[i].route == route) {
this.stack.splice(i, 1);
return true;
};
}
return false;
}
This is something I need, so it's a shame there isn't a proper api, but express is just mimicing what connect does here.
这是我需要的东西,所以很遗憾没有合适的 api,但 express 只是模仿 connect 在这里所做的事情。
回答by Jan ?wi?cki
app.get$ = function(route, callback){
var k, new_map;
// delete unwanted routes
for (k in app._router.map.get) {
if (app._router.map.get[k].path + "" === route + "") {
delete app._router.map.get[k];
}
}
// remove undefined elements
new_map = [];
for (k in app._router.map.get) {
if (typeof app._router.map.get[k] !== 'undefined') {
new_map.push(app._router.map.get[k]);
}
}
app._router.map.get = new_map;
// register route
app.get(route, callback);
};
app.get$(/awesome/, fn1);
app.get$(/awesome/, fn2);
And then when you go to http://...awesomefn2will be called :)
然后当你去的时候http://...awesomefn2会被调用:)
Edit: fixed the code
编辑:修复了代码
Edit2: fixed again...
编辑2:再次修复...
Edit3: Maybe simpler solution is to purge routes at some point and repopulate them:
Edit3:也许更简单的解决方案是在某个时候清除路由并重新填充它们:
// remove routes
delete app._router.map.get;
app._router.map.get = [];
// repopulate
app.get(/path/, function(req,res)
{
...
});
回答by Jan ?wi?cki
You can look into Express route middlewareand possibly do a redirect.
您可以查看 Express路由中间件并可能进行重定向。
回答by pdenes
As already mentioned above, the new Express API doesn't seem to support this.
如上所述,新的 Express API 似乎不支持这一点。
Is it really necessary to completely remove the mapping? If all you need is to stop serving a route, you can easily just start returning some error from the handler.
The only (very odd) case where this wouldn't be good enough is if dynamic routes were added all the time, and you wanted to completely get rid of old ones to avoid accumulating too many...
If you want to remap it (either to do something else, or to map it to something that always returns an error), you can always add another level of indirection:
var healthHandler = function(req, res, next) { // do something }; app.get('/health/*', function(req, res, next) { healthHandler(req, res, next); }); // later somewhere: healthHandler = function(req, res, next) { // do something else };In my opinion this is nicer/safer than manipulating some undocumented internals in Express.
真的有必要彻底删除映射吗?如果您只需要停止为路由提供服务,您可以轻松地开始从处理程序返回一些错误。
唯一(非常奇怪)的情况是,如果一直添加动态路由,并且您想完全摆脱旧路由以避免积累太多......
如果你想重新映射它(或者做其他事情,或者将它映射到总是返回错误的东西),你总是可以添加另一个间接级别:
var healthHandler = function(req, res, next) { // do something }; app.get('/health/*', function(req, res, next) { healthHandler(req, res, next); }); // later somewhere: healthHandler = function(req, res, next) { // do something else };在我看来,这比在 Express 中操作一些未记录的内部结构更好/更安全。

