Introduction
Every route handler and middleware function in Express receives two central objects: req (the request) and res (the response). These are enhanced versions of Node's native http.IncomingMessage and http.ServerResponse, extended by Express with convenient properties and methods for reading incoming data and building outgoing responses without manually handling streams or headers.
Cricket analogy: req and res are like the umpire's signal log and the scoreboard operator: the umpire records what happened on the field (incoming data) while the scoreboard operator builds the public display (outgoing response), both enhanced beyond a raw notebook to make the job easier.
Syntax
app.post('/orders', (req, res) => {
// Reading from req
const body = req.body;
const id = req.params.id;
const filter = req.query.filter;
const auth = req.headers['authorization'];
// Writing to res
res.status(201);
res.set('X-Custom-Header', 'value');
res.json({ received: body });
});Explanation
Common req properties include req.params (route parameters), req.query (query string), req.body (parsed request body, requires middleware like express.json()), req.headers (request headers), req.method, and req.url. Common res methods include res.send() (send a response of various types), res.json() (send JSON and set Content-Type automatically), res.status(code) (set the HTTP status code, chainable), res.set()/res.header() (set response headers), res.redirect() (redirect to another URL), and res.sendFile() (send a file as the response). Methods like res.status() are chainable because they return the res object itself.
Cricket analogy: req.params is like the specific over number requested (over 42), req.query is like optional filters such as '?boundary=only', and res.status(200).json() is like the scorer stamping the official result and printing the innings summary in one chained motion.
Example
const express = require('express');
const app = express();
app.use(express.json());
app.post('/users/:id/comments', (req, res) => {
const userId = req.params.id;
const { text } = req.body;
const highlight = req.query.highlight === 'true';
if (!text) {
return res.status(400).json({ error: 'text is required' });
}
res.status(201).json({
userId,
text,
highlighted: highlight
});
});
app.listen(3000);Output
A POST to /users/7/comments?highlight=true with JSON body {"text":"Nice post!"} returns status 201 and body {"userId":"7","text":"Nice post!","highlighted":true}. If text is missing, the response is status 400 with {"error":"text is required"}.
Cricket analogy: A comment posted to player 7's profile with '?highlight=true' returns status 201 with the comment marked highlighted, like a fan comment pinned to the top of a player's feed; a missing comment text is like an empty scorecard entry, rejected with a 400 error.
Key Takeaways
- req carries incoming data: req.params, req.query, req.body, req.headers, req.method.
- req.body requires body-parsing middleware such as express.json() or express.urlencoded().
- res.send(), res.json(), and res.status() are the most commonly used response methods.
- res methods like status() and set() are chainable because they return the res object.
- Always send exactly one response per request; sending multiple responses throws an error.
Practice what you learned
1. Which middleware is required for req.body to be populated with parsed JSON data?
2. Which res method automatically sets the Content-Type header to application/json?
3. Why is res.status(201).json({...}) valid JavaScript?
4. Where would you find a value submitted via a URL query string like ?filter=active?
Was this page helpful?
You May Also Like
Route Parameters and Query Strings
Understand how to capture dynamic URL segments and optional query data in Express routes.
Handling JSON Requests in Express
Learn how to parse incoming JSON payloads in Express using the built-in express.json() middleware.
Routing in Express
Understand how Express matches HTTP methods and URL paths to handler functions using routes.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics