相同点
Express 和 koa 本质上都是对 http.createServer(onRequest).listen(PORT) 的封装
不同点
1. 功能不同
- 路由处理Express是自身集成
- Koa需要引入中间件
2. Context
- Koa 新增了一个 Context 对象,用来代替 Express 中的 Request 和 Response,作为请求的上下文对象
- Express 使用的是原生的 req, res
3. 生命周期/中间件执行顺序
- Koa 的中间件是依次执行, 并且在执行完成之后才会返回
- Express 的执行顺序不确定, 并且用户随时可以调用 res 来进行返回
4. 中间件编写
-
Koa 因为是中间件执行完之后才会返回, 所以可以直接
await next() -
Express 的执行顺序不确定, 所以要借助
on-headers来实现JavaScript// 中间件,上面responseTime的核心实现,基于on-headers模块 function responseTime () { return function responseTime (req, res, next) { const startAt = process.hrtime() onHeaders(res, function onHeaders () { const diff = process.hrtime(startAt) const time = diff[0] * 1e3 + diff[1] * 1e-6 res.setHeader('X-Response-Time', time.toFixed(3) + 'ms') }) next() } } //使用中间件计算response Time app.use(responseTime());
5. 错误处理
- Koa 可以直接使用
try/catch await next() - Express 则只能自行处理, 没有统一的处理方法
Reference
jshttp/on-headers
Execute a listener when a response is about to write headers.
https://github.com/jshttp/on-headers
jshttp/on-finished
Execute a callback when a HTTP request closes, finishes, or errors.
https://github.com/jshttp/on-finished
Discussion
留言与讨论
想法、补充和不同意见都欢迎。