βοΈ 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
reqobject represents the incoming HTTP request from the client. It contains all the information you need to understand what the client is asking for. - The
resobject 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, theuserIdis available asreq.params.userId.req.query: An object containing the URL query string parameters. For a URL like/search?term=books&page=2,req.querywould be{ term: 'books', page: '2' }.req.body: An object containing the data submitted in the request body. This property isundefinedby default. You must use a body-parsing middleware, likeexpress.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 aString, aBuffer, or anObject/Array(which will be automatically converted to JSON).res.json([body]): Specifically for sending JSON responses. It correctly sets theContent-Typeheader toapplication/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
reqobject is your window into the incoming request, allowing you to read params, queries, the body, and headers. - The
resobject 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.bodyrequires body-parsing middleware likeexpress.json()to work.
Last updated on