[英]Remove route mappings in NodeJS Express
我的路線映射為:
app.get('/health/*', function(req, res){
res.send('1');
});
如何在運行時刪除/重新映射此路由到空處理程序?
這將刪除app.use
中間件和/或app.VERB
(get / post)路由。 在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);
}
請注意,它要求中間件/路由功能具有名稱 :
app.use(function yourMiddlewareFunctionName(req, res, next) {
... ^ named function
});
如果函數是匿名的, 它將無法工作 :
app.get('/path', function(req, res, next) {
... ^ anonymous function, won't work
});
Express(至少從3.0.5開始)將所有路由保存在app.routes
。 從文檔 :
app.routes對象包含由關聯的HTTP謂詞映射的所有路由。 此對象可用於內省功能,例如,Express在內部使用此功能不僅用於路由,還提供默認的OPTIONS行為,除非使用app.options()。 您的應用程序或框架也可以通過從這個對象中刪除它們來刪除路由。
你的app.routes
看起來應該類似於:
{ get:
[ { path: '/health/*',
method: 'get',
callbacks: [Object],
keys: []}]
}
因此,您應該能夠遍歷app.routes.get
直到找到您要查找的內容,然后將其刪除。
在服務器運行時可以刪除已安裝的處理程序(添加了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;
}
這是我需要的東西,所以很遺憾沒有合適的api,但express只是模仿connect在這里做什么。
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);
然后當你去http://...awesome
fn2
將被調用:)
編輯:修復代碼
Edit2:再次修復......
編輯3:也許更簡單的解決方案是在某個時刻清除路線並重新填充它們:
// remove routes
delete app._router.map.get;
app._router.map.get = [];
// repopulate
app.get(/path/, function(req,res)
{
...
});
上述方法要求您為路徑指定一個命名函數。 我也想這樣做,但沒有路由的命名函數,所以我編寫了一個npm模塊,可以通過指定路由路徑來刪除路由。
干得好:
您可以查看Express 路由中間件並可能進行重定向。
如上所述,新的Express API似乎不支持這一點。
是否真的有必要徹底刪除映射? 如果您只需停止提供路由,則可以輕松地從處理程序返回一些錯誤。
唯一(非常奇怪)這種情況不夠好的情況是,如果一直添加動態路線,並且你想徹底擺脫舊的路線,以避免積累太多......
如果要重新映射它(要么執行其他操作,要么將其映射到始終返回錯誤的內容),您始終可以添加另一級別的間接:
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中操縱一些未記錄的內部更好/更安全。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.