Skip to Content
πŸŽ‰ Welcome to my notes πŸŽ‰
Express.js↔️ The Request (req) and Response (res) Objects in Express.js

↔️ The Request (req) and Response (res) Objects in Express.js

In every Express route handler and middleware function, you are given two arguments: the request object (usually called req) and the response object (usually called res). These objects are enhanced versions of Node.js’s native http objects.

  • The req object represents the incoming HTTP request from the client. It contains all the information you need to understand what the client is asking for.
  • The res object represents the HTTP response that your application will send back to the client. You use it to build and dispatch your reply.

Analogy: The req object is like an order ticket at a restaurant. It has all the details of what the customer wants (the URL path, query strings, headers, and any data in the body). The res object is like the empty tray and plate you use to prepare and send the food back to the customer.


πŸ“₯ The Request Object (req) - What the Client Sent

The req object allows you to access information about the client’s request. Here are some of the most useful properties:

  • req.params: An object containing properties mapped to the named route β€œparameters.” For example, if you have a route like /users/:userId, the userId is available as req.params.userId.
  • req.query: An object containing the URL query string parameters. For a URL like /search?term=books&page=2, req.query would be { term: 'books', page: '2' }.
  • req.body: An object containing the data submitted in the request body. This property is undefined by default. You must use a body-parsing middleware, like express.json(), to populate it.
  • req.method: A string containing the HTTP request method ('GET', 'POST', etc.).
  • req.path: A string containing the path part of the URL.
  • req.headers: An object containing the HTTP headers of the request.

πŸ’» Code Example: Accessing Request Data

index.js
const express = require("express"); const app = express(); // Middleware to parse JSON bodies app.use(express.json()); // A route with a dynamic parameter app.post("/users/:userId", (req, res) => { // Accessing route parameters const userId = req.params.userId; // Accessing query string const sortOrder = req.query.sort || "asc"; // Default to 'asc' if not provided // Accessing the request body (thanks to express.json()) const userData = req.body; console.log(`User ID from params: ${userId}`); console.log(`Sort order from query: ${sortOrder}`); console.log("User data from body:", userData); res.send(`Data received for user ${userId}.`); }); app.listen(3000); // To test, run: curl -X POST "http://localhost:3000/users/123?sort=desc" -H "Content-Type: application/json" -d '{"name":"Alice"}'

πŸ“€ The Response Object (res) - What You Send Back

The res object provides numerous methods to build and send a response to the client.

  • res.send([body]): The most versatile method. It sends the HTTP response. The body can be a String, a Buffer, or an Object/Array (which will be automatically converted to JSON).
  • res.json([body]): Specifically for sending JSON responses. It correctly sets the Content-Type header to application/json. This is the standard for building APIs.
  • res.status(code): Sets the HTTP status code of the response (e.g., 200, 404, 500). This method is chainable.
  • res.sendStatus(code): Sets the status code and sends the text version of it as the response body (e.g., res.sendStatus(404) sends β€œNot Found”).
  • res.redirect([status], path): Redirects the request to a different URL.
  • res.set(headerName, value): Sets a single response header.

πŸ’» Code Example: Sending a Response

index.js
// ...inside a route handler... app.get("/api/products", (req, res) => { const products = [ { id: 1, name: "Laptop" }, { id: 2, name: "Mouse" }, ]; // Set a custom header res.set("X-Powered-By", "My Awesome API"); // Set the status code and send the JSON response res.status(200).json({ status: "success", data: products, }); }); // To test, run: curl "http://localhost:3000/api/products"

✨ Summary

  • The req object is your window into the incoming request, allowing you to read params, queries, the body, and headers.
  • The res object is your tool for crafting the perfect response to send back, using methods like .send(), .json(), and .status().
  • You must end the request-response cycle by calling a response method (like .send(), .json(), .redirect(), etc.). If you don’t, the client’s request will hang and eventually time out.
  • Remember that req.body requires body-parsing middleware like express.json() to work.
Last updated on