import express from "express" import { status } from "http-status" const app = express() app.use(express.urlencoded({ extended: true })) app.use(express.json()) // Log every incoming request to the terminal app.use((req, res, next) => { console.log("\n" + "=".repeat(50)) console.log(`${req.method} ${req.url}`) console.log("\n-- Headers --") console.log(req.headers) if (Object.keys(req.body || {}).length > 0) { console.log("\n-- Body --") console.log(req.body) } if (Object.keys(req.cookies || {}).length > 0) { console.log("\n-- Cookies --") console.log(req.cookies) } console.log("=".repeat(50)) next() }) // Serve static files from the "public" directory (for CSS, images, etc.) app.use(express.static("public")) // Simple GET: echoes request info back as HTML app.get("/", (req, res) => { res.send(`
Check your terminal — the server printed everything it received.
Submit this and watch the terminal. Also check DevTools → Network tab.
`) }) // Receives the POST: echoes the body back app.post("/login", (req, res) => { const { username, password } = req.body res.send(`Username: ${username}
Password: ${password}
⚠️ Over plain HTTP, anyone between you and the server could read this.
Back `) }) // Sets a cookie: shows Set-Cookie header in DevTools app.get("/set-cookie", (req, res) => { res.cookie("session", "abc123xyz", { httpOnly: true, maxAge: 60 * 60 * 1000, // 1 hour }) res.send(`The server sent a Set-Cookie header. Check DevTools → Network → Response Headers.
Now visit show-cookies — the browser will automatically send it back.
`) }) // Shows what cookies the server received app.get("/show-cookies", (req, res) => { const cookieHeader = req.headers["cookie"] || "none" res.send(`Cookie: ${cookieHeader}
The browser sent this automatically — you didn't write any JavaScript for that.
`) }) // Returns JSON: shows Content-Type in action app.get("/json", (req, res) => { res.json({ message: "This is a JSON response", method: req.method, url: req.url, headers: req.headers, }) }) // Delayed response: simulates a slow server app.get("/delay", (req, res) => { setTimeout(() => { res.send(`This response was delayed by 5 seconds.
`) }, 5000) }) // Show all the different HTTP status codes app.get("/status", (req, res) => { res.send(`This response was sent with HTTP status ${code} (${status[code as keyof typeof status]}).
`) }) app.listen(3000, () => { console.log("Echo server running on http://localhost:3000") console.log("Watching for requests...\n") })