3000 端口的 HTTP 服务器。它演示了基本的路由处理,包括多种常见响应,同时还处理来自标准表单或 JSON 的 POST 数据。
详情请参见 Bun.serve。
Copy
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}`);