How Node really works · Chapter 17 of 34
An HTTP server
By the end of this chapter you can write a JSON API with nothing but node:http: routes, status codes, headers and request bodies. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Networking
- 5 tasks
- Node.js
- In the all labs plan
The first 2 chapters of How Node really works are free. This one comes with the all labs plan.
Why you need this
Tapri's app reads its menu from a JSON file built into each release, so changing the price of bun maska means shipping a new app. Meera wants the app to ask a server instead: fetch the menu, place an order, check on it later. Kabir wants it written with the bare module first, because Express and every other framework are built on it.
So far your scripts read files and print. A server is different: it waits, runs your code once per request, and must answer every request, even a broken one. One unhandled error in a handler, and the whole server is gone for every customer.
What you build: 5 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
sendJson: answer with JSON, the right status and the right length
Write sendJson(res, status, data). It turns data into JSON text and ends res with it, with the status code status and two headers: content-type, exactly application/json; charset=utf-8, and content-length, the length of the JSON text in bytes (not in characters: ₹ is one character but three bytes).
- Task 2 · interview question
Interview: readJson, read a JSON body from the request stream
Write readJson(req, limit), with limit 10000 when it is left out. req is a readable stream of Buffer chunks (a request body). It returns a promise of the body parsed as JSON. The check cuts a ₹ in half between two chunks, so the text must still come out whole.
A body of more than limit bytes rejects with an Error whose message is 'Body too large' and whose statusCode property is 413 (a body of exactly limit bytes is fine). A body that is not valid JSON rejects with an Error whose message is 'Invalid JSON' and whose statusCode property is 400.
- Task 3
createTapriServer: serve the menu and single menu items
Write createTapriServer(). It returns a new http.Server that is not listening yet: the check calls listen itself. GET /menu answers 200 with MENU. GET /menu/<id> answers 200 with the item whose id matches, or 404 with { error: 'Not found' } when there is none (/menu/99, /menu/chai).
Route on the path only, so a query string such as /menu?lang=hi still gets the menu. Every response is JSON, sent with sendJson.
- Task 4
createTapriServer: take new orders and look them up again
POST /orders reads a JSON body { itemId, qty } with readJson (limit 10000 bytes). itemId must be the id of a MENU item and qty a whole number of at least 1; anything else (a missing qty, 0, 1.5, itemId 99) answers 400 { error: 'Invalid order' }. Bad JSON answers 400 { error: 'Invalid JSON' }, and a body over the limit answers 413 { error: 'Body too large' }.
A good order answers 201 with { id, item, qty, total }, where item is the menu item's name and total is its price times qty, and a Location header /orders/<id>. GET /orders/<id> answers 200 with that order, or 404 { error: 'Not found' }.
Keep the orders in memory. Ids start at 1 and go up by one, separately for every server createTapriServer makes.
- Task 5
createTapriServer: answer unknown routes and wrong methods properly
Any other path answers 404 { error: 'Not found' }: /, /chai, and a path with an extra part such as /menu/1/extra.
A known path with the wrong method answers 405 { error: 'Method not allowed' } with an Allow header naming the one method that path takes: GET for /menu, /menu/<id> and /orders/<id>, POST for /orders. The shape of the path decides this, so PUT /orders/1 is a 405 even when there is no order 1.
What you will learn
- createServer: a function that runs for every request, and a server you start on any free port.
- Status codes and headers: what the client reads first, and why content-length counts bytes.
- The request body: a stream of Buffer chunks, not a ready string.
- Routing: the path, the method, and the right answer for each.
More in Networking
Build "An HTTP server" yourself
Tapri’s order server must never stall at the 4 pm rush. You learn why it would. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of How Node really works are free. This one comes with the all labs plan.