egg和koa洋葱模型

一个请求通过经过中间件最后生成响应

洋葱模型

基于koa2的demo

const Koa = require('koa');

const app = new Koa();
const PORT = 3000;

// #1

app.use(async (ctx, next)=>{
    console.log('wareA')
    await next();
    console.log('wareA')
});
// #2
// app.use和eggjs里配置config.middleware = []同理
app.use(async (ctx, next) => {
    console.log('wareB')
    await next();
    console.log('wareB')
})

app.use(async (ctx, next) => {
    console.log('wareC')
})

app.listen(PORT);

访问localhost:3000,控制台输出

wareA
wareB
wareC
wareB
wareA

当程序运行到await next()时,会进入到下一个中间件,处理完之后才会继续处理next之后的程序
可以非常方便的实现后置处理逻辑

原文地址:https://www.cnblogs.com/laine001/p/14659366.html