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

  1. Enable JSON parsing: app.use(express.json());.
  2. Enable URL-encoded form parsing: app.use(express.urlencoded({ extended: true }));.
  3. In a POST route, access parsed data via req.body.
  4. For multipart file uploads, use a library like multer instead of built-in middleware.
  5. Validate the parsed data before using it to prevent injection attacks.

Tips

  • The extended: true option allows parsing of rich objects and arrays from URL-encoded data.
  • Always validate and sanitize req.body fields; never trust client input.

Common issues

  • If the middleware is missing, req.body will be undefined.
  • Clients must send the correct Content-Type header (application/json) for the parser to trigger.