koa-洋葱模型

分析1、首先这是koa2最简单的入门例子,我将通过这个入门例子来演示koa2的洋葱模型 const Koa = require('koa');const app = new Koa();app.use((ctx,next)=>{ console.log("第一个中间件执行"); next() ;});// 第二个中间件app.use((ctx,next)=>{ console.log("第二个中间件");})let r = app.listen(8080);console.log("server run on 8080");在这里面,app首先是调用了两次use,然后就开始监听端口, listen(...args) { debug('listen'); // 当客户端发送请求将会调用callback const server = http.createServer(this.callback()); return server.listen(...args); }因此use是核心: use(fn) { // ... 一些判断代码 this.middleware.push(fn); return this; }从上面可以看出这里将外部use的函数通过内部的一个middleware变量记录下来,然后就没了。 OK,现在当客户端发送请求的时候,内部会创建上下文对象,然后处理请求: callback() { const fn = compose(this.middleware); if (!this.listenerCount('error')) this.on('error', this.onerror); const handleRequest = (req, res) => { // 创建上下文 const ctx = this.createContext(req, res); // 处理请求 return this.handleRequest(ctx, fn); }; return handleRequest; }处理请求 ...

May 25, 2019 · 2 min · jiezi