Esto inicia un servidor HTTP escuchando en el puerto 3000. Demuestra enrutamiento básico con varias respuestas comunes y también maneja datos POST desde formularios estándar o como JSON.
Consulta Bun.serve para más detalles.
ts
const server = Bun.serve({
async fetch(req) {
const path = new URL(req.url).pathname;
// responder con text/html
if (path === "/") return new Response("Welcome to Bun!");
// redireccionar
if (path === "/abc") return Response.redirect("/source", 301);
// enviar de vuelta un archivo (en este caso, *este* archivo)
if (path === "/source") return new Response(Bun.file(import.meta.path));
// responder con JSON
if (path === "/api") return Response.json({ some: "buns", for: "you" });
// recibir datos JSON en una solicitud POST
if (req.method === "POST" && path === "/api/post") {
const data = await req.json();
console.log("Received JSON:", data);
return Response.json({ success: true, data });
}
// recibir datos POST desde un formulario
if (req.method === "POST" && path === "/form") {
const data = await req.formData();
console.log(data.get("someField"));
return new Response("Success");
}
// 404s
return new Response("Page not found", { status: 404 });
},
});
console.log(`Listening on ${server.url}`);