koajs/koa
GitHub: koajs/koa
一个轻量级的 Node.js HTTP 中间件框架,采用 async/await 语法和洋葱模型,为构建 Web 应用和 API 提供优雅的异步流程控制。
Stars: 35697 | Forks: 3233
[][gitter-url]
[][npm-url]
[][github-action-url]
[][coveralls-url]
[](#backers)
[](#sponsors)
[][pr-welcoming-url]
Expressive HTTP middleware framework for node.js to make web applications and APIs more enjoyable to write. Koa's middleware stack flows in a stack-like manner, allowing you to perform actions downstream then filter and manipulate the response upstream.
Only methods that are common to nearly all HTTP servers are integrated directly into Koa's small ~570 SLOC codebase. This
includes things like content negotiation, normalization of node inconsistencies, redirection, and a few others.
Koa is not bundled with any middleware.
## 安装
Koa 要求 __node v18.0.0__ 或更高版本,以支持 ES2015 和 async function。
```
npm install koa
```
## Hello Koa
```
const Koa = require('koa');
const app = new Koa();
// response
app.use(ctx => {
ctx.body = 'Hello Koa';
});
app.listen(3000);
```
## 快速开始
- [Kick-Off-Koa](https://github.com/koajs/kick-off-koa) - 通过一系列自定进度的研讨会来入门 Koa。
- [指南](docs/guide.md) - 直接前往文档。
## 中间件
Koa 是一个中间件框架,可以接受两种不同类型的函数作为中间件:
* async function
* common function
以下是使用每种不同函数的 logger 中间件示例:
### ___async___ 函数 (node v7.6+)
```
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
```
### Common 函数
```
// Middleware normally takes two parameters (ctx, next), ctx is the context for one request,
// next is a function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion.
app.use((ctx, next) => {
const start = Date.now();
return next().then(() => {
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
});
```
### Koa v1.x 中间件签名
中间件签名在 v1.x 和 v2.x 之间发生了变化。 旧版签名已被废弃。
**v3 中已移除对旧签名中间件的支持**
有关从 v2.x 升级到 v3.x 的信息,请参阅 [从 v2.x 到 v3.x 的迁移指南](docs/migration-v2-to-v3.md);有关从 v1.x 升级到 v2.x 的信息,请参阅 [从 v1.x 到 v2.x 的迁移指南](docs/migration-v1-to-v2.md)。
## Context、Request 和 Response
每个中间件都会接收一个 Koa `Context` 对象,该对象封装了传入的
http 消息及其对应的响应。 `ctx` 通常被用作
context 对象的参数名。
```
app.use(async (ctx, next) => { await next(); });
```
Koa 提供了一个 `Request` 对象作为 `Context` 的 `request` 属性。
Koa 的 `Request` 对象提供了处理
http 请求的实用方法,这些方法委派给 node `http` 模块中的 [IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage)
。
以下是一个检查请求客户端是否支持 xml 的示例。
```
app.use(async (ctx, next) => {
ctx.assert(ctx.request.accepts('xml'), 406);
// equivalent to:
// if (!ctx.request.accepts('xml')) ctx.throw(406);
await next();
});
```
Koa 提供了一个 `Response` 对象作为 `Context` 的 `response` 属性。
Koa 的 `Response` 对象提供了处理
http 响应的实用方法,这些方法委派给 [ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse)
。
Koa 采用委派给 Node 的 request 和 response 对象的模式,而不是去扩展它们,
这提供了一个更简洁的接口,减少了不同中间件之间以及与 Node 自身之间的冲突,
同时也为 stream 处理提供了更好的支持。 依然可以将 `IncomingMessage` 作为 `Context` 的 `req` 属性直接访问,并将 `ServerResponse` 作为
`Context` 的 `res` 属性直接访问。
以下是使用 Koa 的 `Response` 对象将文件以 stream 形式作为响应体的示例。
```
app.use(async (ctx, next) => {
await next();
ctx.response.type = 'xml';
ctx.response.body = fs.createReadStream('really_large.xml');
});
```
`Context` 对象还为其 `request` 和 `response` 上的方法提供了快捷方式。 在之前的
示例中, 可以使用 `ctx.type` 来代替 `ctx.response.type`,并可以使用 `ctx.accepts` 来
代替 `ctx.request.accepts`。
有关 `Request`、`Response` 和 `Context` 的更多信息,请参阅 [Request API 参考](docs/api/request.md)、
[Response API 参考](docs/api/response.md) 和 [Context API 参考](docs/api/context.md)。
## Koa 应用
执行 `new Koa()` 时创建的对象被称为 Koa 应用对象。
应用对象是 Koa 与 node 的 http server 交互的接口,负责处理
中间件的注册、将 http 分发给中间件、默认的错误处理,以及
context、request 和 response 对象的配置。
在 [Application API 参考](docs/api/index.md) 中了解更多关于应用对象的信息。
## 文档
- [使用指南](docs/guide.md)
- [错误处理](docs/error-handling.md)
- [写给 Express 用户的 Koa](docs/koa-vs-express.md)
- [FAQ](docs/faq.md)
- [API 文档](docs/api/index.md)
## 故障排除
查看 Koa 通用指南中的 [故障排除指南](docs/troubleshooting.md) 或 [调试 Koa](docs/guide.md#debugging-koa)。
## 运行测试
```
$ npm test
```
## 报告漏洞
要报告安全漏洞,请不要直接创建 issue,因为这会通知攻击者该漏洞的存在。相反,请发送电子邮件给 [dead_horse](mailto:heyiyu.deadhorse@gmail.com)、[jonathanong](mailto:me@jongleberry.com) 和 [niftylettuce](mailto:niftylettuce@gmail.com) 进行披露。
## 作者
参见 [AUTHORS](AUTHORS)。
# License
[MIT](https://github.com/koajs/koa/blob/master/LICENSE)
标签:GNU通用公共许可证, Node.js, Web框架, 中间件, 后端开发, 异步编程