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

新建中间件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

相关文章:

  • 2021-08-26
  • 2022-12-23
  • 2022-12-23
  • 2021-12-25
  • 2022-01-26
  • 2022-02-10
  • 2022-01-01
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-19
  • 2022-12-23
  • 2022-02-10
  • 2021-11-17
  • 2021-10-19
相关资源
相似解决方案