Express 和 Koa 的比较

节选自 loopback4-improves-inbound-http-processing


Traditionally in Express (and Connect), functions implementing request handling logic have the following signature:

function (req, res, next);

While it’s amazing how powerful this simple signature is, it comes with major flaws too:

  1. Because the list of arguments is given, it’s difficult to pass additional data between different handlers. The convention is to attach custom properties to the Request object, e.g. body-parsing middleware sets req.body property. This approach is difficult to describe in TypeScript and the ever-changing shape of the Request object has negative impact on (micro)performance.

  2. Flow control is difficult to map to Promises and async/await. Execution of a middleware handler has three possible outcomes:

    i. The request was handled and the remaining items in the middleware chain are skipped. Implementation wise, middleware did not call next().

    ii. The middleware modified the request/response objects, or a route did not match the requested path, and the next handler in the middleware chain should be executed. Implementation wise, middleware called next() with no arguments.

    iii. There was an error and request handling should be aborted. Implementation wise, middleware called next() with a single argument - the error.

It is difficult to run a piece of code after the request was handled or transform the response before it’s being sent. For example, to print a log line containing information about the request including timing information, one has to register the logging middleware early in the middleware chain so that it can register event observers and/or monkey-patch request/response objects before any actual work is done - this is counter-intuitive since the log line is printed at the end of request handling.

Koa addresses these flaws by introducing an extensible Context object that contains not only the request and response, but also additional properties and helper methods.


©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 【萝鼓萱天】20170712 学习力践行记录 day58 1,早上鹅妈妈磨耳朵旧的五首磨十分钟,新的两首磨10分钟...
    眸眸_50ae阅读 206评论 0 0
  • 今天翻微博,看见了一条两个月之前的私信。 “你说人一辈子谈恋爱的次数是有限的吗?为什么我上大学的时候丑丑的也不会打...
    许你一世年华阅读 1,077评论 0 4
  • 夏日炎炎,如果没空调,没wifi是否觉得生无可恋? 但你可曾想过,全球大概有12亿人每天过着这样的生活,因为他们连...
    fa5bfa73efc6阅读 318评论 0 0
  • 每天睡前故事是孩子的最爱,在小妹家儿子又粘着让讲故事听。你看咱家的故事书又没带来,等到咱家再讲好不好。 小家伙撅着...
    王永霞622阅读 144评论 0 2
  • 在我上了初中后,同学朋友间书信往来变得很是频繁。那时候,大概是2002年,大部分同学没有手机,暗恋的人会写来情书,...
    低骨阅读 258评论 0 0

友情链接更多精彩内容