Request and Response in Express.js
Learn how to handle HTTP requests and send responses using the request (req) and response (res) objects in Express.js.
Whenever a client sends a request to a server, Express.js provides a request object to read the incoming information and a response object to send the result back to the client. For example, Samadhan requests student details from the CIIT Training Institute server.
Express.js makes it easier to handle requests and responses
using methods such as app.get(),
res.send(), res.json() and
res.status().
1. What Is a Request Object?
A request object, commonly written as req,
contains information about the HTTP request received from
the client. It helps the server understand what the client
is requesting.
For example, when Pradnya opens the student details page,
the browser sends a GET request to the server. Express.js
provides the req object to access information
about that request.
app.get("/student", (req, res) => {
console.log(req.method);
console.log(req.url);
res.send("Student Details");
});
In this example, req.method returns the HTTP
method and req.url returns the requested URL.
The server then sends a response to the browser.
req object contains information received
from the client.
2. Important Request Properties
Express.js provides several request properties that help us read information from incoming HTTP requests.
| Property | Purpose | Example |
|---|---|---|
req.method |
Returns the HTTP request method. | GET |
req.url |
Returns the requested URL. | /student |
req.query |
Reads query string parameters. | ?name=Pradnya |
req.params |
Reads named route parameters. | :id |
req.headers |
Provides incoming HTTP request headers. | req.headers.host |
We will study route parameters in detail in the next lesson.
3. What Is a Response Object?
A response object, commonly written as res,
is used by the server to send data back to the client.
The response may contain plain text, HTML, JSON data or
an HTTP status code.
For example, when Samadhan requests course information,
the server can use res.send() to send a message
or res.json() to return structured course data.
app.get("/welcome", (req, res) => {
res.send("Welcome to CIIT Training Institute!");
});
Here, res.send() sends the welcome message
to the client when the /welcome route is requested.
res object helps the server send a response
back to the client.
4. Important Response Methods
Express.js provides different response methods depending on what information the server needs to return.
| Method | Purpose | Example |
|---|---|---|
res.send() |
Sends a response such as text or HTML. | res.send("Hello") |
res.json() |
Sends a JSON response. | res.json({ name: "Pradnya" }) |
res.status() |
Sets the HTTP response status code. | res.status(404) |
res.end() |
Ends the response without sending additional data. | res.end() |
5. How Do Request and Response Work?
The client sends an HTTP request to the Express.js server. Express matches the route, executes its callback function, processes the request and sends a response to the client.
1. Client / Browser
Samadhan requests student information.
2. HTTP Request
The client sends a GET request to /student.
3. Request Object (req)
Express reads the incoming request information.
4. Response Object (res)
The server sends the requested student information.
5. Client Receives Response
The browser receives the response data.
6. First Program: Handling a Request and Response
Let's create a simple Express.js server that receives a request and sends a text response to the client.
Step 1: Create app.js
const express = require("express");
const app = express();
app.get("/student", (req, res) => {
console.log("Request Method:", req.method);
console.log("Request URL:", req.url);
res.send("Student details received successfully");
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Step 2: Run the Server
node app.js
Step 3: Open the URL
http://localhost:3000/student
Expected Terminal Output
Server running on port 3000
Request Method: GET
Request URL: /student
Expected Browser Response
Student details received successfully
Explanation:
The app.get() method defines a GET route.
When the client requests /student, Express
executes the callback function. The req object
provides the method and URL, while res.send()
sends the response to the browser.
7. Sending a JSON Response
APIs often return data in JSON format. The
res.json() method sends a JavaScript object
to the client as a JSON response.
Example: Sending Student Details
const express = require("express");
const app = express();
app.get("/student", (req, res) => {
const student = {
id: 1,
name: "Pradnya",
course: "Node.js"
};
res.json(student);
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Test URL
http://localhost:3000/student
Expected Response
{
"id": 1,
"name": "Pradnya",
"course": "Node.js"
}
Explanation:
The server creates a student object and passes it to
res.json(). Express serializes the object
into JSON and sends it to the client.
8. Sending a Response with a Status Code
HTTP status codes tell the client the result of a request. For example, status code 200 indicates success, 201 indicates that a resource was created, and 404 indicates that a resource was not found.
Example: Page Not Found
const express = require("express");
const app = express();
app.get("/not-found", (req, res) => {
res.status(404).send("Page not found");
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Test URL
http://localhost:3000/not-found
Expected Response
Page not found
Explanation:
The res.status(404) method sets the status code
to 404. The chained send() method sends the
error message to the client.
9. Reading Query Parameters from a Request
Query parameters allow clients to send additional information through the URL. They are commonly used for searching and filtering data.
For example, Pradnya can request a greeting by providing her name in the query string.
Example: Reading a Name
const express = require("express");
const app = express();
app.get("/welcome", (req, res) => {
const name = req.query.name || "Student";
res.send("Welcome, " + name + "!");
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Test URL
http://localhost:3000/welcome?name=Pradnya
Expected Response
Welcome, Pradnya!
Explanation:
The req.query.name property reads the value of
the name query parameter. If the parameter is
missing, the example uses Student as the default.
10. Difference Between req and res
| Request Object (req) | Response Object (res) |
|---|---|
| Contains incoming request information. | Used to send a response to the client. |
| Reads the request method and URL. | Sends text, JSON and status codes. |
Example: req.method |
Example: res.send() |
Example: req.query |
Example: res.json() |
11. Important Points
-
The
reqobject contains incoming request information. -
The
resobject sends a response to the client. -
Use
req.methodto read the HTTP method. -
Use
req.urlto read the requested URL. -
Use
res.send()to send text or HTML. -
Use
res.json()to send JSON data. -
Use
res.status()to set an HTTP status code. - Send only one final response for each request.
Summary
In this lesson, we learned how Express.js handles HTTP requests and responses. We explored the request object and its properties, sent text and JSON responses, used HTTP status codes, and read query parameters. These concepts are essential for building Express.js web applications and REST APIs.