From 099825e5acf0addc32786749247d6c8a0d64fda2 Mon Sep 17 00:00:00 2001 From: Jake Gordon Date: Fri, 16 Feb 2024 00:30:59 +0000 Subject: [PATCH] Common HTTP server usage guide (#8732) Co-authored-by: Georgijs <48869301+gvilums@users.noreply.github.com> --- docs/guides/http/server.md | 46 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 docs/guides/http/server.md diff --git a/docs/guides/http/server.md b/docs/guides/http/server.md new file mode 100644 index 0000000000..1f1f9b48a6 --- /dev/null +++ b/docs/guides/http/server.md @@ -0,0 +1,46 @@ +--- +name: Common HTTP server usage +--- + +This starts an HTTP server listening on port `3000`. It demonstates basic routing with a number of common responses and also handles POST data from standard forms or as JSON. + +See [`Bun.serve`](/docs/api/http) for details. + +```ts +const server = Bun.serve({ + async fetch (req) { + const path = new URL(req.url).pathname; + + // respond with text/html + if (path === "/") return new Response("Welcome to Bun!"); + + // redirect + if (path === "/abc") return Response.redirect("/source", 301); + + // send back a file (in this case, *this* file) + if (path === "/source") return new Response(Bun.file(import.meta.file)); + + // respond with JSON + if (path === "/api") return Response.json({ some: "buns", for: "you" }); + + // receive JSON data to a POST request + if (req.method === "POST" && path === "/api/post") { + const data = await req.json(); + console.log("Received JSON:", data); + return Response.json({ success: true, data }); + } + + // receive POST data from a form + 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}`); +```