이 코드는 포트 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" });
// POST 요청으로 JSON 데이터 수신
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}`);