koa的洋葱圈模型

拿以下这段代码为例:

const Koa = require('koa');
const app = new Koa();

// x-response-time
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

// response
app.use(ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

每一个中间件就类似每一层洋葱圈,上面例子中的第一个中间件 "x-response-time" 就好比洋葱的最外层,第二个中间件 "logger" 就好比第二层,第三个中间件 "response" 就好比最里面那一层,所有的请求经过中间件的时候都会执行两次。

猜你喜欢

转载自www.cnblogs.com/amiezhang/p/9375885.html
koa