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整理维护