Koa
Expressの後継で、より軽量なWebフレームワーク
async/awaitベースで直感的にmiddlewareを書ける
開発者は@tj
website
github
例
code:ts
const Koa = require('koa');
const app = new Koa();
app.use(ctx => {
ctx.body = 'Hello Koa';
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
#wip
https://koajs.com/
Introduction
Application
Context
Request
Response
Links
code:ts
import Koa from "koa";
const app = new Koa();
// ① 一番外側:loggerの前処理(next()の前)
app.use(async (ctx, next) => {
// logger: 前
await next(); // → 次のミドルウェアへ(②へ)
// ⑥ logger: 後(X-Response-Timeを取得)
const rt = ctx.response.get('X-Response-Time');
console.log(${ctx.method} ${ctx.url} - ${rt});
});
// ② 次の層:x-response-timeの前処理
app.use(async (ctx, next) => {
// ③ x-response-time: 前
const start = Date.now();
await next(); // → 次のミドルウェアへ(④へ)
// ⑤ x-response-time: 後
const ms = Date.now() - start;
ctx.set('X-Response-Time', ${ms}ms);
});
// ④ 一番内側:responseの処理
app.use(async ctx => {
ctx.body = 'Hello World'; // レスポンスを設定
});
app.listen(3000);
かなり直感的なMiddleware Patternだmrsekut.icon
GPT-4.icon
🔀 ルーティングを使いたい場合(koa-router)
@koa/routerを使うことでルーティング機能を追加できます。
code:js
// index.js
const Koa = require('koa');
const Router = require('@koa/router');
const app = new Koa();
const router = new Router();
router.get('/', (ctx) => {
ctx.body = 'トップページです';
});
router.get('/hello', (ctx) => {
ctx.body = 'こんにちは、Koa!';
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
📦 よく使うミドルウェア例
koa-bodyparser: リクエストボディのパース
koa-static: 静的ファイル提供
koa-session: セッション管理
koa-logger: ログ表示