The Request Object

req describes the incoming HTTP request: its URL, method, headers and data.

Syntaxreq.params / req.query / req.body

The req object holds everything about the incoming request. The most-used properties are:

PropertyContains
req.methodGET, POST, etc.
req.url / req.pathThe requested URL / path
req.paramsRoute parameters
req.queryQuery string values
req.bodyParsed request body
req.headersRequest headers

Example

Example · javascript
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.

Example · js
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.

Example · js
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.

Example · js
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

  • Be the first to comment on this lesson.