req & res Objects (Express)

In Express, req (request) holds the incoming data — URL params, query string, headers, and body — while res (response) is how you reply, with helpers like res.json(), res.status(), and res.send().

Node.js

Every Express route handler receives two objects. req carries what the client sent: req.params (route placeholders like /users/:id), req.query (the ?key=value string), req.body (the parsed request body, populated by a body-parser like express.json()), req.headers, and req.cookies.

res builds the reply. res.send(body) sends text or HTML, res.json(obj) sends JSON with the right content type, res.status(code) sets the HTTP status (chainable: res.status(201).json(...)), res.redirect(url) sends a redirect, and res.set(header, value) sets headers. You must end the response exactly once.

These extend Node's raw http req/res with convenience methods. A common bug is sending two responses (calling res.json after already responding) or never responding at all, which leaves the request hanging — make sure each path ends the response once.

Syntax

req.params, req.query, req.body; res.status(200).json(data)

Examples

JavaScript

app.get("/users/:id", (req, res) => {
  const id = req.params.id;       // from the URL
  const verbose = req.query.v;     // from ?v=...
  if (!id) return res.status(400).json({ error: "no id" });
  res.status(200).json({ id, verbose });
});

Learn it in a lesson

See also

Back to the Dictionary