これはポート 3000 でリッスンしている HTTP サーバーを起動します。一般的なレスポンスの数を備えた基本的なルーティングを実演し、標準フォームまたは JSON からの POST データを処理します。
詳細については、Bun.serve を参照してください。
ts
const server = Bun.serve({
async fetch(req) {
const path = new URL(req.url).pathname;
// text/html でレスポンス
if (path === "/") return new Response("Welcome to Bun!");
// リダイレクト
if (path === "/abc") return Response.redirect("/source", 301);
// ファイルを返す(この場合は *この* ファイル)
if (path === "/source") return new Response(Bun.file(import.meta.path));
// JSON でレスポンス
if (path === "/api") return Response.json({ some: "buns", for: "you" });
// POST リクエストで JSON データを受信
if (req.method === "POST" && path === "/api/post") {
const data = await req.json();
console.log("Received JSON:", data);
return Response.json({ success: true, data });
}
// フォームからの POST データを受信
if (req.method === "POST" && path === "/form") {
const data = await req.formData();
console.log(data.get("someField"));
return new Response("Success");
}
// 404
return new Response("Page not found", { status: 404 });
},
});
console.log(`Listening on ${server.url}`);