クイックリファレンス

Koa.js フレームワーク チートシート

Koa.jsのクイックリファレンス:オニオンモデルのミドルウェア、async/awaitカスケード、コンテキスト(ctx)、ルーティング、中央集権エラーハンドリング。

· 公開日

Koa は、Expressの創設チームによって開発された、Node.js向けの表現力豊かで堅牢なHTTPミドルウェアフレームワークです。

基本サーバーとオニオンモデルミドルウェア

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

// ロガーミドルウェア (往復でカスケード実行)
app.use(async (ctx, next) => {
  const start = Date.now();
  await next(); // 下流のミドルウェアに処理を引き渡す
  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// レスポンスミドルウェア
app.use(async (ctx) => {
  ctx.body = { message: 'Hello from Koa!' };
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));

コンテキスト (ctx) リファレンス

// リクエスト情報の検査
ctx.method;             // "GET", "POST", etc.
ctx.url;                // Full URL path
ctx.query;              // Parsed query string object
ctx.headers;            // Request headers object
ctx.get('User-Agent');  // ヘッダー取得ヘルパー

// レスポンスの構築
ctx.status = 200;       // HTTPステータスコードの設定
ctx.body = 'Hello';     // 文字列、Buffer、Stream、または JSON オブジェクト
ctx.set('X-Custom', 'Value'); // カスタムレスポンスヘッダーの設定
ctx.type = 'json';      // Content-Type のショートハンド
ctx.redirect('/login'); // 302リダイレクトを送信

中央集権的なエラーハンドリング

app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || 500;
    ctx.body = { error: err.message };
    ctx.app.emit('error', err, ctx);
  }
});

app.on('error', (err, ctx) => {
  console.error('Server error:', err);
});

参考リンク

関連テーマ