2013-02-22 68 views
3

當前我正試圖在運行時刪除一個 Node.js服務器應用程序的路由。Node.js在服務器運行時刪除路由

for (k in self.app.routes.get) { 
    if (self.app.routes.get[k].path + "" === route + "") { 
    delete self.app.routes.get[k]; 
    break; 
    } 
} 

調用此方法後,不再有self.app.routes對象中的路由。但之後,我嘗試訪問當前刪除路線,我得到以下錯誤:由於express.js的文檔

TypeError: Cannot call method 'match' of undefined at Router.matchRequest (/var/lib/root/runtime/repo/node_modules/express/lib/router/index.js:205:17)

這一定是這樣做的正確方法。

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.

是否有任何機構知道如何在Node.js中的運行時正確刪除路由?

非常感謝!

+0

你能確認你的Express版本嗎? – Brad 2013-02-22 15:30:20

+0

對不起。我的版本是:「3.1.0」 – 2013-02-22 15:32:49

回答

8

你得到的錯誤是因爲路線仍然存在。 delete不會刪除元素,它只會將元素設置爲undefined。要刪除使用拼接(K,N)(從第k個元素,去掉n個項目)

for (k in self.app.routes.get) { 
    if (self.app.routes.get[k].path + "" === route + "") { 
    self.app.routes.get.splice(k,1); 
    break; 
    } 
} 

還是你的路由功能應對此進行處理(選擇接受哪條路徑/ URL),這將是更好的。

相關問題