Skip to content

Koa Aide-mémoire

Framework web Node.js de nouvelle génération créé par l'équipe d'Express, utilisant async/await.

01

Démarrage

Serveur Hello World

Koa utilise async/await au lieu des callbacks.

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

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

app.listen(3000);

Middleware

Le middleware forme une cascade — utilisez await next() pour passer le contrôle.

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

Router

koa-router pour le routage.

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());

Was this helpful?