Node——express 中间件原理

  • 基本代码

    function express() {
        var funcs = []; // 待执行的函数数组
        var app = function (req, res) {
            var i = 0;
            function next() {
                var task = funcs[i++]; // 取出函数数组里的下一个函数
                if (!task) { // 如果函数不存在,return
                    return;
                }
                task(req, res, next); // 否则,执行下一个函数
            }
            next();
        }
        app.use = function (task) {
            funcs.push(task);
        }
    
        return app; // 返回实例
    }
    
    // 下面是测试case
    
    var app = express();
    http.createServer(app).listen('3000', function () {
        console.log('listening 3000....');
    });
    
    function middlewareA(req, res, next) {
        console.log('middlewareA before next()');
        next();
        console.log('middlewareA after next()');
    }
    
    function middlewareB(req, res, next) {
        console.log('middlewareB before next()');
        next();
        console.log('middlewareB after next()');
    }
    
    function middlewareC(req, res, next) {
        console.log('middlewareC before next()');
        next();
        console.log('middlewareC after next()');
    }
    
    app.use(middlewareA);
    app.use(middlewareB);
    app.use(middlewareC);
    
    app() //模拟一个http请求
    
  • express() 执行之后返回的是一个函数,函数作为对象也可以拥有属性,所以添加了 use 属性,use 的作用是往函数数组 funcs 中添加回调函数

  • 当我们用 app() 模拟一次 http 请求,程序会走 next(),当我们自定义的中间件中有 next 关键字,之后程序会一直处于递归状态,直到 return 或者执行到函数末尾,然后逐一跳出每层递归函数

  • 这样的递归结构,需要三个东西支撑:req、res、next,因为 req、res 保证了上下文一致,而 next 函数保证了中间件的往下执行

  • 帮助文档:https://www.jianshu.com/p/797a4e38fe77

posted @ 2018-08-06 14:53  cnloop  阅读(774)  评论(0编辑  收藏  举报