Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Watch a Request Body Arrive

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 a POST, and -H adds a header such as Content-Type: application/json. The route table already sends POST /waitlist to joinWaitlist(), which still answers with the placeholder 404.
  • A handler needs the request to read its body. type Handler gains req: IncomingMessage as its first parameter, and IncomingMessage joins ServerResponse in the type import. Every handler takes req first, even the ones that don’t use it, because arguments go by position. The listener calls route.handler(req, res, url).
  • The body isn’t on req.body. Frameworks often put a parsed body there, but console.log(req.body) logs undefined, and the client still gets the placeholder 404, so nothing looks broken. npm run check flags 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 req doesn’t hold the body: it’s the stream the body arrives on.
  • for await reads the chunks. for await (const chunk of req) waits for each chunk and ends when the body has arrived. To use it inside joinWaitlist(), the function becomes async and returns Promise<void>. It still fits Handler, which returns void, and the listener ignores that Promise for now.
  • Each chunk is a Buffer. With curl --limit-rate 12, Zoë’s 50-byte entry arrives as five Buffer chunks, 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 one Buffer, 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/catch that stops your server. The catch logs 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.

The Final Code

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 Your plot board answers Mrs. Okafor’s questions about the plots. Her third common call is how to join the waiting list. Joining sends a name and a contact as a request body.

00:12 You’ve sent one with fetch, as JSON with a Content-Type header. Curl’s -d option sends the text after it as the body, in a POST.

00:21 Its -H option adds the header.

00:24 Your table already routes a POST to /waitlist, but to a placeholder. Here, you’ll find the body, and read it. To read the body, a handler needs the request, but so far it gets only the response and the URL.

00:40 So add req to the Handler type, first. Its type, IncomingMessage, joins ServerResponse in the type import.

00:49 Then every handler takes req first, even the ones that don’t use it. Arguments go by position, and res now comes second. The listener passes req along.

01:01 Now, where’s the body? Frameworks often put the parsed body on req.body, so look there. Log req.body in joinWaitlist(), and save.

01:13 Before you send Zoë Martin’s entry, pause the video and predict what the server logs for the body.

01:24 It logs undefined, not the entry. The client still gets the placeholder 404, so nothing looks broken. The type check flags it too. IncomingMessage has no body property.

01:37 Node strips types without checking them, so the file ran anyway.

01:43 Why is it missing? Node calls your listener as soon as the request line and the headers have arrived. That’s all it needs to route. The body comes after them, over the same connection, in pieces called chunks.

01:57 So the body was never waiting on req. Instead, req is the stream it arrives on, and you read the chunks from it. Node uses streams for files too, but reading one in a loop is all you need now.

02:13 To read them, loop over req with a for await loop. It’s a for...of loop that waits for each chunk, and ends when the body has arrived.

02:22 To await inside joinWaitlist(), make it async, with a Promise as its return type. Inside the loop, log each chunk.

02:32 The type check passes, because a function returning a Promise fits a Handler that returns void. The listener ignores that Promise for now.

02:40 At full speed, Zoë’s entry arrives in one chunk, but a bigger body or a slower connection arrives in pieces, cut wherever the bytes fall. To watch, slow curl to 12 bytes a second with its --limit-rate option.

02:55 The listener logs the request right away. Then the chunks arrive, about one a second. Five in all, and the client gets the placeholder. Each chunk is a Buffer: raw bytes, two hexadecimal digits per byte.

03:12 The first chunk ends with c3, and the second starts with ab. Those two bytes make one letter, the ë in Zoë. Decode each chunk as it arrives, and the first ends in half a letter, a replacement mark.

03:29 So keep the bytes until the end. Push each chunk into an array. After the loop, Buffer.concat() joins them into one Buffer. Its toString() method decodes that with UTF-8, once.

03:42 Log the text, save, and send the entry again. The server logs Zoë’s entry, whole. Log bodies only on your own machine. They carry names and emails.

03:56 If a client hangs up mid-body, the loop throws and stops your server. So wrap the loop in try/catch, log the hang-up, and return: nobody’s left to answer.

04:08 So the body isn’t waiting on req when the handler runs. Await its chunks with for await, join them, then decode once. For now, the loop reads however much a client sends.

04:20 You’ll limit that soon.

04:23 Your board reads what a client sends now, but only as text. In the next lesson, Parse the Body With a readJson Helper, you’ll turn that text into data.

Become a Member to join the conversation.