Koa
async/awaitベースで直感的にmiddlewareを書ける
例
code:ts
const Koa = require('koa');
const app = new Koa();
app.use(ctx => {
ctx.body = 'Hello Koa';
});
app.listen(3000, () => {
});
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);
GPT-4.icon
🔀 ルーティングを使いたい場合(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, () => {
});
📦 よく使うミドルウェア例