Skip to content

這啟動了一個監聽端口 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" });

    // 接收 JSON 數據到 POST 請求
    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}`);

Bun學習網由www.bunjs.com.cn整理維護