Skip to main content
这段代码启动了一个监听 3000 端口的 HTTP 服务器。它演示了基本的路由处理,包括多种常见响应,同时还处理来自标准表单或 JSON 的 POST 数据。 详情请参见 Bun.serve
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79server.ts
const server = Bun.serve({
  async fetch(req) {
    const path = new URL(req.url).pathname;

    // 以 text/html 响应
    if (path === "/") return new Response("欢迎使用 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}`);