Topic 42 of 55
req.body
Overview
When clients send data via POST/PUT requests (like submitting a form or sending JSON), it arrives in the request body. Express does NOT parse bodies by default. You must configure body-parsing middleware to access `req.body`.
Syntax
javascript
const express = require('express');
const app = express();
// REQUIRED MIDDLEWARE:
// Tells Express to intercept requests with Content-Type: application/json
// and parse them into a JavaScript object attached to req.body
app.use(express.json());
// Tells Express to parse URL-encoded bodies (standard HTML form submissions)
app.use(express.urlencoded({ extended: true }));
app.post('/api/login', (req, res) => {
// Without the middleware above, req.body would be 'undefined'
const email = req.body.email;
const password = req.body.password;
res.send(`Login attempt for ${email}`);
});Common Pitfalls
- If `req.body` is `undefined`, it means you forgot to add `app.use(express.json())` at the top of your server file.
- Never trust `req.body`. A malicious user can send whatever JSON they want. Always sanitize and validate every field before saving to a database.
Real-World Example
Validating the request body before processing it:
example
javascript
// It's highly recommended to validate req.body using a library like Joi or Zod
const z = require('zod');
const UserSchema = z.object({
username: z.string().min(3),
email: z.string().email(),
age: z.number().int().positive()
});
app.post('/api/users', (req, res) => {
// Validate the incoming req.body against our schema
const validation = UserSchema.safeParse(req.body);
if (!validation.success) {
// 400 Bad Request if the payload is invalid
return res.status(400).json({
error: "Invalid payload",
details: validation.error.errors
});
}
// Safe to use validated data
const validData = validation.data;
res.status(201).json({ message: "User created", data: validData });
});