目前我正在尝试删除一个 运行时的 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 对象中不再有路由。但是在我尝试访问当前删除的路由后,出现以下错误:
TypeError: Cannot call method 'match' of undefined at Router.matchRequest (/var/lib/root/runtime/repo/node_modules/express/lib/router/index.js:205:17)
根据 express.js 的文档,这一定是正确的做法。
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 中正确删除运行时的路由吗?
非常感谢!
最佳答案
您收到的错误是因为路线仍然存在。 delete
不会删除元素,它只会将元素设置为 undefined
。删除使用 splice(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),这样会更好。
关于javascript - Node.js 在服务器运行时删除路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15027514/