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

  • 相关阅读:
    洛谷P4113 [HEOI2012]采花
    洛谷P5159 WD与矩阵
    洛谷P1262 间谍网络
    洛谷P3038 牧草种植Grass Planting
    洛谷P3258 [JLOI2014]松鼠的新家
    洛谷P2294 [HNOI2005]狡猾的商人
    洛谷P4878 [USACO05DEC]layout布局
    【CF1132F】Clear the String (DP)
    [AH2017/HNOI2017]大佬(动态规划 搜索)
    「NOI2018」屠龙勇士(CRT)
  • 原文地址:https://www.cnblogs.com/cnloop/p/9430190.html
Copyright © 2011-2022 走看看