At the end of the last lesson, your plot board read Zoë Martin’s entry for the waiting list and logged it in full. However, that log line is still only text. To add Zoë to Mrs. Okafor’s list, the handler needs her name and contact as data, and it has to cope when a client sends something that isn’t JSON at all.
In this lesson, you’ll turn the body’s text into data, decide what the client hears when that fails, and wrap the reading and the parsing in one helper, readJson(), that any route taking a body can call. Start with what can go wrong when you parse the text a client sends.
Decide What a Bad Body Deserves
The text Node.js hands you is whatever the client sent, and clients make mistakes. A short session in Node.js’s REPL shows what JSON.parse() does with a good entry, an entry with a stray comma, and no text at all:
> JSON.parse('{"name":"Zoë"}')
{ name: 'Zoë' }
> JSON.parse('{"name":"Zoë",}')
Uncaught:
SyntaxError: Expected double-quoted property name in JSON at position 14 (line 1 column 15)
> JSON.parse("")
Uncaught SyntaxError: Unexpected end of JSON input
The valid entry becomes an object. Broken text makes JSON.parse() throw a SyntaxError, and so does empty text, which is what arrives when a client sends a POST and forgets the body.
Watch out for the line you’d write first in joinWaitlist(), const entry = JSON.parse(text);. Nothing catches its SyntaxError, so the handler’s promise rejects, Node.js stops the whole server, and every caller after that gets a refused connection.
Yet the server did nothing wrong. The client sent text that isn’t JSON, so the client has to change the request before sending it again. That’s what 400 Bad Request says. A 500 would blame the server for a mistake it didn’t make.
The two failures deserve different messages, though. “Unexpected end of JSON input” tells someone who forgot the body very little. So an empty body gets its own check before parsing, with a message that names the problem. Broken JSON gets a message of its own. Both get a 400 status in the board’s usual error shape.
To test where that line between the client’s mistakes and the server’s falls, ask the AI mentor: