Reading Request Data
The three sources of input are req.params, req.query and req.body.
Client data reaches your handler through three channels. Knowing which to use is key:
req.params— required parts of the path, like an id in/users/:id.req.query— optional key=value pairs after?.req.body— the payload of a POST/PUT/PATCH request (needs a body parser).
Remember to enable express.json() so req.body is populated for JSON requests.
Example
app.use(express.json());
// POST /users/42?notify=true with body { "name": "Ada" }
app.post('/users/:id', (req, res) => {
res.json({
id: req.params.id, // '42'
notify: req.query.notify, // 'true'
name: req.body.name, // 'Ada'
});
});When to use it
- A checkout endpoint reads the cart contents from req.body after express.json() parses the JSON payload sent by the client.
- A file upload handler checks req.files (populated by multer) to validate that an image was included before saving to disk.
- A search endpoint reads req.query.q and req.query.limit to construct a database query with pagination.
More examples
Reading JSON body
Parses a JSON body with express.json() and destructures the required fields, returning 400 when items are missing.
app.use(express.json());
app.post('/orders', (req, res) => {
const { items, address } = req.body;
if (!items?.length) return res.status(400).json({ error: 'No items' });
res.status(201).json({ order: { items, address } });
});Reading query string data
Destructures query parameters with default values to support optional filtering and pagination.
app.get('/products', (req, res) => {
const { category = 'all', page = 1, limit = 20 } = req.query;
res.json({ category, page: Number(page), limit: Number(limit) });
});Combining params, query, and body
Demonstrates reading data from all three sources in one handler: route param, query string, and request body.
app.patch('/posts/:id', (req, res) => {
const id = req.params.id; // URL segment
const publish = req.query.publish; // ?publish=true
const changes = req.body; // JSON patch payload
res.json({ id, publish: publish === 'true', changes });
});
Discussion