zoukankan      html  css  js  c++  java
  • koa2中间件学习笔记

    洋葱模型
    整个洋葱就是服务端程序app,每层洋葱皮都是一个中间件,传入requrest,经过各个中间件处理之后传出response。
    中间件洋葱模型

    新建中间件m1.js,m2.js

    koa-learn/middleware/m1.js

    function m1(ctx) {
      global.console.log('m1 ing')
    }
    module.exports = function () {
      return async function (ctx, next) {
        global.console.log('m1 start')
        m1(ctx)
        //next的作用是进入下一个中间件,如果没next则不进入下一个中间件,直接跳出
        await next() 
        global.console.log('m1 end')
      }
    }
    

    koa-learn/middleware/m2.js

    function m2(ctx) {
      global.console.log('m2 ing')
    }
    module.exports = function () {
      return async function (ctx, next) {
        global.console.log('m2 start')
        m2(ctx)
        //next的作用是进入下一个中间件,如果没next则不进入下一个中间件,直接跳出
        await next()
        global.console.log('m2 end')
      }
    }
    

    在app.js里使用m1.js,m2.js中间件

    koa-learn/app.js

    ...
    const m1 = require('./middleware/m1');
    const m2 = require('./middleware/m2');
    ...
    app.use(m1())
    app.use(m2())
    ...
    

    控制台打印出来的结果

    m1 start
    m1 ing
    m2 start
    m2 ing
    m2 end
    m1 end
    
  • 相关阅读:
    Python生成器表达式
    Python列表解析
    Python迭代器(Iterator)
    Python set 集合
    python eval 函数妙用
    Python字典 (dict)
    Python序列之元组 (tuple)
    Python序列之列表 (list)
    递归和反射
    常用标准库
  • 原文地址:https://www.cnblogs.com/superlizhao/p/12017670.html
Copyright © 2011-2022 走看看