Parsing JSON bodies with express.json
why req.body needs a body parser.
register express.json via app.use so it reads the request stream and populates req.body before handlers run, place it before routes.
expecting req.body to work without any parser.
WHAT THIS TESTS This confirms you understand that Express leaves body parsing to middleware, and that you know the modern built-in rather than reaching for an external package.
A GOOD ANSWER COVERS By default Express does not read or parse the request body, so req.body is undefined. To parse JSON payloads you use the express.json middleware, which is now built into Express. It consumes the incoming request stream, buffers the chunks, parses the resulting JSON, and assigns the parsed object to req.body. You register it with app.use(express.json()), and crucially you mount it before your route handlers so that by the time a handler runs, req.body is already populated. The middleware only parses requests whose Content-Type indicates JSON, leaving other types alone. You can configure it, for example with a limit option to cap body size and reject oversized payloads. In older code this role was played by the separate body-parser package, which express.json was derived from.
COMMON WRONG ANSWERS Thinking req.body works out of the box. Registering the parser after the routes, so handlers still see undefined. Manually reading data and end events when the built-in middleware already does it. Confusing express.json with express.urlencoded, which handles form submissions.
LIKELY FOLLOW-UPS How do you parse URL-encoded form data. How do you limit body size to prevent abuse. What is the historical relationship to body-parser.
ONE CONCRETE EXAMPLE With app.use(express.json()) placed before app.post('/users', (req, res) => res.json(req.body)), a POST carrying {"name":"Ana"} and Content-Type application/json gives req.body equal to { name: 'Ana' }. Remove the middleware and req.body is undefined, causing the handler to fail.
Read the original → expressjs.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.