Dies startet einen HTTP-Server, der auf Port 3000 lauscht. Er demonstriert grundlegendes Routing mit einer Reihe häufiger Responses und verarbeitet auch POST-Daten von Standard-Formularen oder als JSON.
Siehe Bun.serve für Details.
ts
const server = Bun.serve({
async fetch(req) {
const path = new URL(req.url).pathname;
// Mit text/html antworten
if (path === "/") return new Response("Welcome to Bun!");
// Weiterleitung
if (path === "/abc") return Response.redirect("/source", 301);
// Eine Datei zurücksenden (in diesem Fall *diese* Datei)
if (path === "/source") return new Response(Bun.file(import.meta.path));
// Mit JSON antworten
if (path === "/api") return Response.json({ some: "buns", for: "you" });
// JSON-Daten von einer POST-Anfrage empfangen
if (req.method === "POST" && path === "/api/post") {
const data = await req.json();
console.log("Received JSON:", data);
return Response.json({ success: true, data });
}
// POST-Daten von einem Formular empfangen
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}`);