CPCODELAB
Express

The Request and Response Objects

9 min read

The Request and Response Objects

The req object extends Node's IncomingMessage and gives you everything about the incoming HTTP request. The res object extends ServerResponse and provides methods for building your reply.

Commonly Used Request Properties

  • req.method — HTTP verb ("GET", "POST", ...)
  • req.url — raw request URL including query string
  • req.path — pathname without query string
  • req.headers — all request headers as an object
  • req.body — parsed request body (requires middleware)
  • req.params — named URL segments
  • req.query — parsed query string parameters
  • req.cookies — cookies (requires cookie-parser middleware)
  • req.ip — client IP address

Commonly Used Response Methods

  • res.send(body) — send a response (string, Buffer, or object)
  • res.json(obj) — send a JSON response with Content-Type header
  • res.status(code) — set the HTTP status code (chainable)
  • res.set(name, value) — set a response header
  • res.redirect(url) — send a 302 redirect
  • res.sendFile(path) — stream a file to the client
  • res.end() — close the connection without a body

Always end the request-response cycle by calling exactly one of res.send(), res.json(), res.end(), res.redirect(), or res.sendFile(). Calling more than one will throw a headers-already-sent error.

Ready to test yourself?
Practice Express— quiz & coding exercises