Best way to do dynamic routing with Express.js (node.js)

前端 未结 3 1973
时光取名叫无心
时光取名叫无心 2020-12-24 15:36

I\'m trying to create a simple CMS with express.js that dynamically creates routes. It gets a JSON from a database that looks like this:

pagesfromdb = {
             


        
3条回答
  •  [愿得一人]
    2020-12-24 15:51

    Adding routes can be done on the fly, as mentioned. Deleting can too, given this fuction:

    function deleteRoute(url) {
      for (var i = app.routes.get.length - 1; i >= 0; i--) {
        if (app.routes.get[i].path === "/" + url) {
          app.routes.get.splice(i, 1);
        }
      }
    }
    

    (stolen from Removing a specfic mapped route in Node.js at runtime removes static mapping?)

    Updating routes like this does make your app "stateful", and will probably lead to a problems if you need load balance.

提交回复
热议问题