Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Remove route while server is running

Currently I am trying to remove the route of a Node.js server application on runtime.

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

After this method is called there is no longer the route in the self.app.routes object. But after I try to access the currently removed route I get the following error:

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

Due to the documentation of express.js this must be the correct way of doing it.

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.

Does any body know how to correctly remove a route on runtime in Node.js?

Thanks a lot!

like image 367
Robert Weindl Avatar asked Sep 06 '25 03:09

Robert Weindl


1 Answers

The error you are getting is because the route is still there. delete won't remove the element, it will only set the element as undefined. To remove use splice(k,n) (from kth element ,remove n items)

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

Still your route function should handle this (choose which path/url to accept), which would be better.

like image 131
user568109 Avatar answered Sep 08 '25 00:09

user568109