Skip to content

Koa 速查表

Express 团队打造的下一代 Node.js Web 框架,基于 async/await。

01

快速上手

Hello Server

Koa 用 async/await 取代回调。

koa
import Koa from "koa";
const app = new Koa();

app.use(async ctx => {
  ctx.body = "Hello World";
});

app.listen(3000);

中间件

中间件是级联式的——用 await next() 把控制权交给下一层。

koa
app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${ms}ms`);
});

Router

用 koa-router 处理路由。

koa
import Router from "koa-router";
const router = new Router();

router.get("/users/:id", async ctx => {
  ctx.body = `User ${ctx.params.id}`;
});

app.use(router.routes());

这篇内容对您有帮助吗?