NelsonLabs
Express.js/Request & Response

Request & Response

The req and res objects in Express are extensions of Node's http.IncomingMessage and http.ServerResponse. Express adds many helpful properties and methods to both.

The request object (req)
javascript
app.post("/api/courses/:id/enrol", authenticate, (req, res) => {
  // URL parameters
  req.params.id         // "42"

  // Query string: ?preview=true&lang=en
  req.query.preview     // "true"
  req.query.lang        // "en"

  // Request body (requires express.json() middleware)
  req.body.email        // "nelson@nelsonlabs.dev"
  req.body.plan         // "free"

  // Headers
  req.headers["content-type"]      // "application/json"
  req.get("Authorization")          // "Bearer eyJ..."

  // Other useful properties
  req.method       // "POST"
  req.url          // "/api/courses/42/enrol?preview=true"
  req.path         // "/api/courses/42/enrol"
  req.ip           // "127.0.0.1"
  req.user         // set by auth middleware: req.user = { id: 7, role: "admin" }
});
The response object (res)
javascript
// Send JSON (most common for APIs)
res.json({ success: true, data: courses });

// Set status code + send JSON
res.status(201).json({ id: newCourse.id });
res.status(404).json({ error: "Course not found" });
res.status(400).json({ error: "Validation failed", field: "title" });

// Just a status (no body)
res.sendStatus(204);  // 204 No Content

// Redirect
res.redirect("/courses");
res.redirect(301, "https://new-url.com");

// Send a file
res.sendFile(path.join(__dirname, "public", "index.html"));

// Set headers before sending
res.set("X-Request-Id", requestId);
res.set("Cache-Control", "no-store");

// Cookies
res.cookie("sessionId", token, { httpOnly: true, secure: true });
res.clearCookie("sessionId");