The Request Object
req describes the incoming HTTP request: its URL, method, headers and data.
Syntax
req.params / req.query / req.bodyThe req object holds everything about the incoming request. The most-used properties are:
| Property | Contains |
|---|---|
req.method | GET, POST, etc. |
req.url / req.path | The requested URL / path |
req.params | Route parameters |
req.query | Query string values |
req.body | Parsed request body |
req.headers | Request headers |
Example
app.get('/inspect/:id', (req, res) => {
res.json({
method: req.method,
path: req.path,
params: req.params,
query: req.query,
userAgent: req.headers['user-agent'],
});
});When to use it
- A route handler reads req.method and req.path to build audit log entries that capture exactly what action was taken on which resource.
- An analytics middleware reads req.headers['user-agent'] and req.ip from the request object to track visitor device types.
- A multi-tenant API reads req.hostname to determine which tenant's database connection to attach to the request.
More examples
Inspecting request properties
Returns a snapshot of the most commonly used req object properties for debugging purposes.
app.get('/info', (req, res) => {
res.json({
method: req.method,
path: req.path,
ip: req.ip,
protocol: req.protocol,
secure: req.secure,
});
});Reading request headers
Uses req.get() to read individual headers by name in a case-insensitive manner.
app.get('/headers', (req, res) => {
const ua = req.get('User-Agent');
const accept = req.get('Accept');
const authHdr = req.get('Authorization');
res.json({ ua, accept, hasAuth: !!authHdr });
});Combining path, query, and body
Reads input from three different sources (params, query, body) in a single route handler.
app.put('/articles/:id', (req, res) => {
const { id } = req.params; // route segment
const { draft } = req.query; // ?draft=true
const { title } = req.body; // JSON body
res.json({ id, isDraft: draft === 'true', title });
});
Discussion