Why does req.body come out undefined in Express, and what does express.json do?
Express does not read request bodies by itself. express.json() is middleware that parses JSON bodies with a JSON content type and places the result on req.body. Without it, req.body is undefined.
Explain it simply
A request body arrives as a stream of bytes, like water coming through a pipe. Something has to collect it, check what it says, and turn it into an object. Express leaves that to you, and express.json() is the ready-made worker for JSON bodies.
Example
const express = require("express");
const app = express();
app.use(express.json({ limit: "100kb" })); // JSON bodies
app.use(express.urlencoded({ extended: false })); // HTML form bodies
app.post("/register", (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({ error: "name and email are required" });
}
res.status(201).json({ name, email });
});
app.listen(3000);Details:
- It only parses requests whose
Content-Typeisapplication/json. If the client forgets the header,req.bodystays empty. - Register it before your routes; middleware order matters.
- The
limitoption stops someone from sending a huge body; the default is 100 kb. - Malformed JSON causes a 400 error that your error handler can catch.
- File uploads use
multipart/form-data, which needs a different tool such asmulter.
What to say in the interview
"express.json is built-in body-parsing middleware for JSON. It must be registered before the routes, depends on the Content-Type header, and has a size limit. Without it req.body is undefined."
Common mistakes
- Registering the parser after the route that needs it.
- Forgetting the Content-Type header in Postman or fetch.