Proper way to remove middleware from the Express stack?

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

    You can use the express-dynamic-middleware to make this.

    https://github.com/lanbomo/express-dynamic-middleware

    Use it like this

    const express = require('express');
    
    // import express-dynamic-middleware
    const dynamicMiddleware = require('express-dynamic-middleware');
    
    
    // create auth middleware
    const auth = function(req, res, next) {
        if (req.get('Authorization') === 'Basic') {
            next();
        } else {
            res.status(401).end('Unauthorization');
        }
    };
    
    // create dynamic middleware
    const dynamic = dynamicMiddleware.create(auth);
    
    // create express app
    const app = express();
    
    // use the dynamic middleware
    app.use(dynamic.handle());
    
    // unuse auth middleware
    dynamic.unuse(auth);
    
    0 讨论(0)
提交回复
热议问题