常見的 HTTP 伺服器用法
此程式碼啟動一個監聽 3000 埠的 HTTP 伺服器。它演示了使用常見響應進行基本路由處理,並處理來自標準表單或 JSON 格式的 POST 資料。
詳情請參見 Bun.serve。
const server = Bun.serve({
async fetch(req) {
const path = new URL(req.url).pathname;
// 傳回 text/plain
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("收到的 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("成功");
}
// 404 頁面未找到
return new Response("頁面未找到", { status: 404 });
},
});
console.log(`監聽地址 ${server.url}`);