运行时包管理器打包器测试运行器代码检查格式化指南参考博客反馈

常见的 HTTP 服务器用法

此代码启动一个监听 3000 端口的 HTTP 服务器。它演示了使用常见响应进行基本路由处理,并处理来自标准表单或 JSON 格式的 POST 数据。

详情请参见 Bun.serve。

server.ts
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}`);