Request Handling & Custom Responses

🦁 Express.jsLesson 4Beginner

The Request (req) and Response (res) objects are the primary conduits through which your Express server exchanges information with clients.

1 Essential req properties
  • req.params: Extracts variables from dynamic path segments (e.g. /users/:id).
  • req.query: Extracts query parameters from URLs (e.g. /search?q=js).
  • req.headers: Inspects HTTP headers sent by the client.
  • req.ip: Retrieves the remote IP address of the client connection.
2 Dynamic response methods

Express extends response handling with methods like res.json(), res.status(), and res.download():

JavaScript — req_res_demo.js
app.get("/users/:id", (req, res) => {
  const userId = req.params.id;
  const filter = req.query.filter || "none";
  
  // Return a JSON response with status code 200
  res.status(200).json({
    id: userId,
    filter: filter,
    active: true
  });
});

app.get("/download-log", (req, res) => {
  // Initiates download request for a local file
  res.download("./logs/app.log");
});
3 Code Challenge
Challenge: Write an endpoint /api/headers that returns a JSON list showing the incoming request's User-Agent header and host details, with a custom header X-Powered-By-Mana added to the response.