06 Request Parsing
title: Request Parsing in Node.js REST APIs weight: 16 date: 2026-06-28 lastmod: 2026-06-28 description: Learn parsing request bodies in Node.js REST APIs including JSON, URL-encoded, multipart form data, and raw body parsing with Express and Koa. tags: [api-development, nodejs]
Request parsing in Node.js REST APIs extracts data from incoming requests by parsing JSON bodies, URL-encoded forms, multipart data for file uploads, and query string parameters using Express middleware.
```mermaid
flowchart TD
A[Request Body] --> B[Content-Type]
B --> C[application/json]
B --> D[multipart/form-data]
B --> E[application/x-www-form-urlencoded]
C --> F[express.json()]
D --> G[Upload middleware]
E --> H[express.urlencoded()]
style A fill:#e1f5fe
style B fill:#fff9c4
style F fill:#c8e6c9
Express provides express.json() for JSON bodies and express.urlencoded() for form data. For file uploads, use the multer middleware. Koa uses koa-body or koa-bodyparser. Each parser populates req.body or ctx.request.body with the parsed data.
Think of request parsing like a mail sorter. express.json() reads letters (JSON), express.urlencoded() reads postcards (form data), and multer reads packages with attachments (file uploads). Each sorter handles a specific envelope type.
Example: JSON Body Parsing
const express = require('express');
const app = express();
app.use(express.json({ limit: '1mb' }));
app.post('/api/users', (req, res) => {
console.log('Received body:', req.body);
console.log('Name:', req.body.name);
console.log('Email:', req.body.email);
res.status(201).json({
message: 'User created',
received: req.body
});
});
// Test: curl -X POST http://localhost:3000/api/users \
// -H "Content-Type: application/json" \
// -d '{"name":"Alice","email":"alice@example.com"}'
Expected output:
Received body: { name: 'Alice', email: 'alice@example.com' }
Name: Alice
Email: alice@example.com
Example: URL-Encoded Form Parsing
app.use(express.urlencoded({ extended: true }));
app.post('/api/contact', (req, res) => {
res.json({
name: req.body.name,
message: req.body.message,
parsed: true
});
});
// Test: curl -X POST http://localhost:3000/api/contact \
// -d "name=Alice&message=Hello"
Expected output:
{"name": "Alice", "message": "Hello", "parsed": true}
Example: File Upload with Multer
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/api/upload', upload.single('avatar'), (req, res) => {
console.log('File:', req.file);
console.log('Body:', req.body);
res.json({
message: 'File uploaded',
filename: req.file.filename,
size: req.file.size,
mimetype: req.file.mimetype
});
});
// Test: curl -X POST http://localhost:3000/api/upload \
// -F "avatar=@photo.jpg" \
// -F "description=Profile photo"
Expected output:
File: { fieldname: 'avatar', originalname: 'photo.jpg', encoding: '7bit', mimetype: 'image/jpeg', destination: 'uploads/', filename: 'abc123.jpg', size: 102400 }
Common Mistakes
- Forgetting body parser middleware — Without express.json(), req.body is undefined for JSON POST requests. Always add body parsing middleware.
- Setting body size limit too high — Accepting unlimited body sizes can crash your server. Set reasonable limits: 1MB for JSON, 10MB for file uploads.
- Not handling malformed JSON — express.json() returns 400 for invalid JSON, but you may want to customize the error response with a try/catch wrapper.
- Using express.json() for file uploads — JSON cannot handle binary data. Use multer or another multipart parser for file uploads.
- Missing Content-Type validation — Validate that Content-Type matches what your parser expects. Reject unsupported types with 415 Unsupported Media Type.
Practice Questions
- What middleware is needed to parse JSON request bodies in Express?
- How do you handle file uploads in Express?
- What is the difference between extended: true and extended: false in urlencoded?
- How do you set a body size limit?
- Challenge: Create an Express endpoint that accepts both JSON and form-data inputs. The endpoint should detect the Content-Type, parse accordingly, and return the parsed fields along with the content type used.
FAQ
Mini Project
Build an Express API endpoint that accepts three content types: JSON for user data, multipart/form-data for user data with an avatar upload, and URL-encoded for a simple contact form. Validate the Content-Type header and parse accordingly. Log the parsed data.
What's Next
Now learn about response formatting in Building REST APIs with Node.js.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro