Request Body Parsing
Overview
When a frontend sends data to the server (like a massive JSON object from a React form via a POST request), the data does not arrive instantly. Because TCP is a stream, the data arrives in fragmented binary chunks. Historically, you had to manually listen to the stream, concatenate the buffers, and run JSON.parse(). Express solves this natively with specialized Body Parsing middleware, which buffers the stream for you and exposes the fully parsed object on req.body.
Syntax
const express = require('express');
const app = express();
// --- CRITICAL MIDDLEWARE ---
// 1. Tells Express to intercept streams with 'Content-Type: application/json'
// and parse them into native JS objects on req.body
app.use(express.json());
// 2. Tells Express to intercept standard HTML Form Submissions
// (Content-Type: application/x-www-form-urlencoded)
app.use(express.urlencoded({ extended: true }));
app.post('/api/register', (req, res) => {
// Without the middleware above, req.body is completely 'undefined'!
const username = req.body.username;
const password = req.body.password;
console.log(`Registering user: ${username}`);
res.status(201).json({ success: true });
});Common Pitfalls
- Sending JSON from the frontend but forgetting to set the Header. If your React
fetchcall sends JSON, but forgets to setheaders: { 'Content-Type': 'application/json' }, the Expressexpress.json()middleware will completely ignore the stream, leavingreq.bodyundefined. - Vulnerability to massive payloads. By default,
express.json()protects your server by throwing an error if a payload exceeds 100kb (to prevent memory-crashing DoS attacks). If you need to accept massive payloads, you must explicitly configure it:express.json({ limit: '10mb' }).
Interview Questions
express.json() parse file uploads (like a user uploading an image)?No. File uploads use multipart/form-data, which is an incredibly complex boundary-based binary stream protocol. Express natively ignores multipart streams. You MUST install a specialized third-party middleware, like multer or busboy, to intercept and save physical files.
Real-World Example
Using Destructuring to cleanly extract required fields from the parsed req.body.
app.post('/api/login', (req, res) => {
// Instantly extracts exactly what we need, ignoring extra junk data
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: "Missing credentials" });
}
// Proceed with authentication...
});Check Your Knowledge
Test your understanding of Request Body Parsing with these quick questions.