How to parse request body in Express
· Category: Node.js
Short answer
Add express.json() and express.urlencoded() middleware to parse JSON and form data bodies into req.body.
Steps
- Enable JSON parsing:
app.use(express.json());. - Enable URL-encoded form parsing:
app.use(express.urlencoded({ extended: true }));. - In a POST route, access parsed data via
req.body. - For multipart file uploads, use a library like
multerinstead of built-in middleware. - Validate the parsed data before using it to prevent injection attacks.
Tips
- The
extended: trueoption allows parsing of rich objects and arrays from URL-encoded data. - Always validate and sanitize
req.bodyfields; never trust client input.
Common issues
- If the middleware is missing,
req.bodywill beundefined. - Clients must send the correct
Content-Typeheader (application/json) for the parser to trigger.