Koa 是一个背靠 Express 的团队设计的全新的 Web 框架,旨在使之成为一个更轻量,更丰富,更加 robust 的基础框架。通过促进异步方法的使用,Koa 允许使用者抛弃 callback 调用,并且大大简化了错误处理。Koa 并没有将中间件绑定到核心代码,而是提供了一组优雅的方法让编写服务更加快速,通过很多第三方的扩展给 Koa 提供服务,从而实现更加丰富完整的 HTTP server。

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. By leveraging async functions, Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within its core, and it provides an elegant suite of methods that make writing servers fast and enjoyable.

安装和入门

Koa 需要 node v7.6.0 及以上版本

nvm install 7
npm i koa
node my-koa-app.js

先从简单的例子说起,实现一个简单的 HTTP 服务:

const Koa = require('koa');
const app = new Koa();

const main = ctx => {
  ctx.response.body = 'Hello World';
};

app.use(main);
app.listen(3000);

Koa 有一个 Context 对象,表示一次请求上下文,通过对该对象的访问来控制返回给客户端的内容。

路由

Koa 的原生路由就需要使用者自己通过字符串匹配来维护复杂的路由,通过扩展 koa-route 可以实现更加丰富的路由选择

const route = require('koa-route');

const about = ctx => {
  ctx.response.type = 'html';
  ctx.response.body = '<a href="/">About</a>';
};

const main = ctx => {
  ctx.response.body = 'Hello World';
};

app.use(route.get('/', main));
app.use(route.get('/about', about));

那么这样之后通过 localhost:3000/localhost:3000/about 就可以访问不同内容。

对于静态资源可以使用 koa-static

const path = require('path');
const serve = require('koa-static');
const main = serve(path.join(__dirname));
app.use(main);

更多的内容可以参考文末链接。

reference