Check the Body at the Door

Your readJson() helper from the last lesson turns a good body into data and answers a broken one with a 400. But it still reads whatever a client sends, even a body labeled as plain text, and it would keep every byte of a body the size of a movie. A waiting list entry is about fifty bytes, so Mrs. Okafor’s board has no reason to read either one.

In this lesson, you’ll add two checks to readJson(): one that refuses a body that isn’t labeled as JSON, and one that stops reading once a body grows too big. You’ll also see why each check sits where it does. Start with the check that costs nothing, because it only needs the headers.

Refuse a Body That Isn’t JSON

A client says what kind of body it’s sending in the Content-Type header, and not every client says application/json.

If you leave out -H, then curl -d labels the body application/x-www-form-urlencoded, the format of an HTML form. A fetch() call with a string body and no headers labels it text/plain;charset=UTF-8.

You could parse those bodies anyway, and some would even work. But a client that sends the wrong label has made a mistake, and the helpful answer names it. That’s what 415 Unsupported Media Type is for. It tells the client that the server won’t read this kind of body.

Remember from Watch a Request Body Arrive that Node.js calls your listener once the headers are in, before the body. So this check runs before the server reads a single chunk. In body.ts, add a function above readJson() that looks at the header:

Language: TypeScript Filename: body.ts
function isJson(req: IncomingMessage): boolean {
  const header = req.headers["content-type"] ?? "";
  const type = header.split(";")[0].trim();
  return type.toLowerCase() === "application/json";
}

The header can carry extra details after a semicolon, as in application/json; charset=utf-8, so .split(";")[0] keeps only the part before it. Media types are case insensitive, so Application/JSON passes too. A request with no Content-Type at all gets an empty string from the ?? operator and fails the check.

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

Become a Member to join the conversation.