Proper way to remove middleware from the Express stack?

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

    No way of removing a middleware as far as I know. however, you can assign a boolean flag to 'deactivate' a middleware at anytime you want.

    let middlewareA_isActivate = true;
    // Your middleware code
    function(req, res, next) {
       if (!middlewareA_isActivate) next();
       // .........
    }
    // Deactivate middleware
    middlewareA_isActivate = false;
    

    EDIT :
    After reading through ExpressJs (4.x) code, I notice that you can access the middlewares stack via app._router.stack, manipulation goes from there I guess. Still, I think this 'trick' might not be able to work in future Express
    P/s: Not tested how Express behaves when manipulate the middlewares stack directly though

提交回复
热议问题