In this lesson, you went looking for Zoë Martin’s waiting-list entry on req.body, found undefined, and then read the body the way Node delivers it: as chunks, joined and decoded once.
Key Points
- Joining the waiting list sends a body. The entry is a name and a contact, sent as JSON.
curl -d '<text>'sends the text as the body, in aPOST, and-Hadds a header such asContent-Type: application/json. The route table already sendsPOST /waitlisttojoinWaitlist(), which still answers with the placeholder404. - A handler needs the request to read its body.
type Handlergainsreq: IncomingMessageas its first parameter, andIncomingMessagejoinsServerResponsein the type import. Every handler takesreqfirst, even the ones that don’t use it, because arguments go by position. The listener callsroute.handler(req, res, url). - The body isn’t on
req.body. Frameworks often put a parsed body there, butconsole.log(req.body)logsundefined, and the client still gets the placeholder404, so nothing looks broken.npm run checkflags it:Property 'body' does not exist on type 'IncomingMessage'.Node strips types without checking them, so the file runs anyway. - The headers come first. Node calls your listener as soon as the request line and the headers have arrived, which is all it needs to route. The body follows over the same connection, in pieces called chunks. So
reqdoesn’t hold the body: it’s the stream the body arrives on. for awaitreads the chunks.for await (const chunk of req)waits for each chunk and ends when the body has arrived. To use it insidejoinWaitlist(), the function becomesasyncand returnsPromise<void>. It still fitsHandler, which returnsvoid, and the listener ignores thatPromisefor now.- Each chunk is a
Buffer. Withcurl --limit-rate 12, Zoë’s 50-byte entry arrives as fiveBufferchunks, about a second apart, each shown as raw bytes in hexadecimal. At full speed, it arrives in one. - Decoding chunk by chunk can split a character.
ëis two bytes,c3 ab, and the first two chunks split it, so decoding the first chunk on its own ends in a replacement mark:{"name":"Zo�. - Join the bytes, then decode once. Push each chunk into
chunks: Buffer[]. After the loop,Buffer.concat(chunks)joins them into oneBuffer, and.toString("utf8")decodes it. Log bodies only on your own machine, since they carry names and emails. - A client can hang up mid-body. Then the loop throws, and without a
try/catchthat stops your server. Thecatchlogs the hang-up and returns, since nobody’s left to answer.
So the rule is: the body isn’t waiting on req when the handler runs. Await its chunks with for await, join them with Buffer.concat(), then decode once. For now, the loop reads however much a client sends, and you’ll limit that soon. The board also reads the body only as text: in the next lesson, you’ll turn that text into data.