Node web 框架 - Koa2
刚刚写了一个简单的 Express 流程的实现,来理解 Express 的原理。
相比 Express,Koa2 更加的简单。
1、Koa2 也是通过 use 添加函数来处理请求,不过是一个异步函数,并且传入的是一个上下文
2、Koa2 在处理请求的时候,首先创建一个当前请求相关的上下文
3、传入的异步函数,所以用 await 来实现一层一层处理上下文后( 洋葱模式的形式 )
4、最后通过上下文的 body 来完成数据返回
简单的代码实现:
const http = require('http')class App {constructor() {this.middleware = []}use(fn) {this.middleware.push(fn)}// 链式模型compose() {const {middleware} = thisreturn async function (ctx) {let index = 0const next = async function () {let handle = nullwhile (!handle && index < middleware.length) {handle = middleware[index++]}if (handle) return await handle(ctx, next)if (!handle) Promise.resolve()}await next();}}listen() {const callback = async (req, res) => {const handle = this.compose()const context = {response: res,request: req,app: this}await handle(context)res.end(context.body)}const server = http.createServer(callback)server.listen.apply(server, arguments)}
}const app = new App()
app.use(async (ctx, next) => {ctx.body = 'one\n'await next()ctx.body += 'two\n'
})
app.use(async (ctx, next) => {ctx.body += 'three\n'await next()ctx.body += 'four\n'
})
app.listen(3300)
代码仅供理解!
博客园小结巴巴: https://www.cnblogs.com/jiebba