Proper way to remove middleware from the Express stack?

后端 未结 7 2067
时光说笑
时光说笑 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:32

    This is a useful functionality if you are inheriting some unwanted middleware from a framework built on express.

    Building on some of the answers that came before me: In express 4.x the middleware can be found in app._router.stack. Note that the middleware are invoked in order.

    // app is your express service
    
    console.log(app._router.stack)
    // [Layer, Layer, Layer, ...]
    

    Tip: You can search the individual layers for the one you want to remove/move

    const middlewareIndex = app._router.stack.findIndex(layer => {
     // logic to id the specific middleware
    });
    

    Then you can just move/remove them with standard array methods like splice/unshift/etc

    // Remove the matched middleware
    app._router.stack.splice(middlewareIndex, 1);
    

提交回复
热议问题