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(`

HTTP Echo Server

Check your terminal — the server printed everything it received.

Try these:

`) }) // Form page: allows to submit a POST and see the body app.get("/form", (req, res) => { res.send(`

Login Form

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(`

Server received your POST

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(`

Cookie Set

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(`

Cookies the server received

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(`

Delayed Response

This response was delayed by 5 seconds.

`) }, 5000) }) // Show all the different HTTP status codes app.get("/status", (req, res) => { res.send(`

HTTP Status Codes

2xx Success

3xx Redirection

4xx Client Errors

5xx Server Errors

`) }) // Demonstrates different status codes app.get("/status/:code", (req, res) => { const code = parseInt(req.params.code) res.status(code).send(`

Status ${code}

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") })