Removing a specfic mapped route in Node.js at runtime removes static mapping?

前端 未结 1 1003
北恋
北恋 2021-01-23 04:28

Basing my function off of the answer to this question, I wrote this function to delete a route on a live site (using Express and Node).

function deleteRoute(url)         


        
相关标签:
1条回答
  • 2021-01-23 05:07

    delete is for removing keys from objects, not for removing entries from arrays. By calling delete, you are essentially setting the value of that array location to undefined, so Express will still try to process that route when it looks through the routes.

    Note your input before:

     { path: '/contact.html',
       method: 'get',
       callbacks: [Object],
       keys: [],
       regexp: /^\/contact\.html\/?$/i,
       params: [] },
     { path: '/a.html',
       method: 'get',
       callbacks: [Object],
       keys: [],
       regexp: /^\/a\.html\/?$/i,
       params: [] } ],
    

    vs after:

     { path: '/contact.html',
       method: 'get',
       callbacks: [Object],
       keys: [],
       regexp: /^\/contact\.html\/?$/i,
       params: [] },
      ],
    

    You erased the 'a.html' path, but note that there is still a , after the contact.html object. That is because the array entry is still there, it just has no value.

    You need to use splice to remove the entries.

    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);
        }
      }
    }
    

    This method is also pointed out in the second answer of the question you linked to in your question.

    0 讨论(0)
提交回复
热议问题