Proper way to remove middleware from the Express stack?

后端 未结 7 2108
时光说笑
时光说笑 2020-12-18 18:41

Is there a canonical way to remove middleware added with app.use from the stack? It seems that it should be possible to just modify the app.stack array directl

7条回答
  •  春和景丽
    2020-12-18 19:12

    Following from the hints above, I've add success with the following on express 4.x. My use case was logging what was coming in with Slack Bolt, so I could capture and then mock it:

    // Define a handy function for re-ordering arrays
    Array.prototype.move = function(from, to) {
      this.splice(to, 0, this.splice(from, 1)[0]);
    };
    
    // Use the normal use mechanism, so that 'extra' stuff can be done
    // For example, to log further up the order, use app.use(morgan("combined"))
    app.use([my-middleware]); 
    
    // Now adjust the position of what I just added forward
    const numElements = app._router.stack.length;
    app._router.stack.move(numElements - 1, 1);
    

    You can use console.log("Stack after adjustment", app._router.stack) to confirm the new order is what you want. (For Slack Bolt, I had to use app.receiver.app because the Bolt app wraps the express app.)

提交回复
热议问题