zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    x32dbg之AttachHelper插件
    x32dbg插件之APIInfo
    x32dbg之Scylla脱壳插件
    x32dbg插件之strongOD(又名SharpOD)
    x32dbg新型插件之loli(萝莉)
    7 个超棒的监控工具
    成为程序员前需要做的10件事
    改良程序的11个技巧
    旧衣物捐献地址和注意事项
    一件衣服好不好,看看标签就知道
  • 原文地址:https://www.cnblogs.com/cnloop/p/9430190.html
Copyright © 2011-2022 走看看