← All lessons
How HTTP requests work
One request, one response
Browser
api.shop.test
request.http
// first line: method, path, versionPOST /notes HTTP/1.1Host: api.shop.testContent-Type: application/jsonContent-Length: 19// a blank line ends the headers {"text":"buy eggs"}server.js
app.post("/notes", (req, res) => { const note = create(req.body.text); res.status(201) .location(`/notes/${note.id}`) .json(note);});Send your own request to a small notes API
Routes: /notes and /notes/:id. Notes 1 and 2 exist
Request
Response
server.js
app.use(express.json()); // a body that isn't JSON gets a 400 hereapp.get("/notes", (req, res) => res.json(all()));app.post("/notes", auth, (req, res) => { if (!req.body?.text) return res.sendStatus(400); const note = create(req.body.text); res.status(201).location(`/notes/${note.id}`).json(note);});app.all("/notes", (req, res) => res.set("Allow", "GET, POST").sendStatus(405)); app.get("/notes/:id", (req, res) => { const note = find(req.params.id); if (!note) return res.sendStatus(404); res.json(note);});app.put("/notes/:id", auth, (req, res) => res.json(replace(req)));app.delete("/notes/:id", auth, (req, res) => res.sendStatus(204));app.all("/notes/:id", (req, res) => res.set("Allow", "GET, PUT, DELETE").sendStatus(405)); app.use((req, res) => res.sendStatus(404));auth.js
function auth(req, res, next) { if (!req.headers.authorization) { res.set("WWW-Authenticate", "Bearer"); return res.sendStatus(401); } next();}Read a status code the first digit says who to blame
Status line
meaning
class
Type a code from 100 to 599
A 200 with an error message inside breaks this. Clients, caches and retries all trust the code
client.js
// fetch follows 301, 302, 303, 307 and 308 for youconst res = await fetch("/notes/1");if (res.ok) return res.json(); // 200 to 299// 4xx: change the request before trying againif (res.status < 500) throw new Error(res.status);// 5xx: the same request may work laterreturn retryLater(res);Topics
Next: How QUIC and HTTP/3 work
Open lesson