Introduction
The request and response objects are at the heart of Express.js applications. The req object contains information sent by the client, while the res object is used by the server to send data back. In this chapter, you will practice req and res with 10 solved examples covering request methods, URLs, parameters, query strings, request bodies, headers, JSON responses, status codes, redirects, and practical API responses. Node.js Express Request and Response Practice questions with solutions help to understand the concepts.
Question 1: How do you read the HTTP method from the request object?
Problem
Create an Express application that displays the HTTP method used by the client.
Solution
const express = require("express");
const app = express();
app.use((req, res) => {
res.send(`HTTP Method: ${req.method}`);
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Test
Open:
http://localhost:3000/
Output
HTTP Method: GET
Step-by-Step Explanation
The request object is represented by:
req
Express provides the HTTP method through:
req.method
When you open a webpage in a browser, the browser normally sends a GET request.
Therefore:
req.method
returns:
GET
Question 2: How do you read the requested URL?
Problem
Create a route that displays the URL requested by the client.
Solution
const express = require("express");
const app = express();
app.get("/about", (req, res) => {
res.send(`Requested URL: ${req.url}`);
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Test
Open:
http://localhost:3000/about
Output
Requested URL: /about
Step-by-Step Explanation
Express provides the requested URL through:
req.url
For example, if the client requests:
/about
then:
req.url
contains:
/about
Question 3: How do you read route parameters from the request?
Problem
Create a student route that accepts a student ID from the URL.
Solution
const express = require("express");
const app = express();
app.get("/students/:id", (req, res) => {
const studentId = req.params.id;
res.send(
`Student ID is: ${studentId}`
);
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Test
Open:
http://localhost:3000/students/25
Output
Student ID is: 25
Step-by-Step Explanation
The route contains:
/students/:id
Here, :id is a route parameter.
Express stores route parameters inside:
req.params
Therefore:
req.params.id
gets the ID.
For:
/students/25
the value is:
25
Question 4: How do you read query parameters from the request?
Problem
Create a search route that reads name and course from the query string.
Solution
const express = require("express");
const app = express();
app.get("/search", (req, res) => {
const name = req.query.name;
const course = req.query.course;
res.json({
name: name,
course: course
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Test
Open:
http://localhost:3000/search?name=Rahul&course=Node.js
Output
{
"name": "Rahul",
"course": "Node.js"
}
Step-by-Step Explanation
The query string is:
?name=Rahul&course=Node.js
Express makes query parameters available through:
req.query
Therefore:
req.query.name
returns:
Rahul
And:
req.query.course
returns:
Node.js
Question 5: How do you read JSON data from the request body?
Problem
Create a POST route that receives a student’s name and course in JSON format.
Solution
const express = require("express");
const app = express();
app.use(express.json());
app.post("/students", (req, res) => {
const name = req.body.name;
const course = req.body.course;
res.json({
message: "Student data received.",
name: name,
course: course
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Send This JSON
{
"name": "Aman",
"course": "Python"
}
Output
{
"message": "Student data received.",
"name": "Aman",
"course": "Python"
}
Step-by-Step Explanation
First, enable JSON parsing:
app.use(express.json());
Then the JSON data becomes available through:
req.body
For example:
req.body.name
gets the student’s name.
And:
req.body.course
gets the course.
Question 6: How do you read request headers?
Problem
Create a route that reads the User-Agent header sent by the client.
Solution
const express = require("express");
const app = express();
app.get("/", (req, res) => {
const userAgent = req.get("User-Agent");
res.send(
`Your User-Agent is: ${userAgent}`
);
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Test
Open:
http://localhost:3000/
The browser will display a User-Agent value similar to:
Your User-Agent is: Mozilla/5.0 ...
Step-by-Step Explanation
HTTP requests contain headers.
Express provides:
req.get()
for reading a specific request header.
This:
req.get("User-Agent")
reads the User-Agent header.
You can also read other headers:
req.get("Content-Type")
or:
req.get("Authorization")
Question 7: How do you send a JSON response using res.json()?
Problem
Create an API that returns student information as JSON.
Solution
const express = require("express");
const app = express();
app.get("/student", (req, res) => {
const student = {
id: 1,
name: "Rahul",
course: "Node.js"
};
res.json(student);
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Test
Open:
http://localhost:3000/student
Output
{
"id": 1,
"name": "Rahul",
"course": "Node.js"
}
Step-by-Step Explanation
Create an object:
const student = {
id: 1,
name: "Rahul",
course: "Node.js"
};
Then send it with:
res.json(student);
Express converts the JavaScript object into a JSON response.
Another Example
res.json({
success: true,
message: "Student found."
});
Question 8: How do you send an HTTP status code with a response?
Problem
Create an API that returns a 201 Created status when a student is successfully created.
Solution
const express = require("express");
const app = express();
app.use(express.json());
app.post("/students", (req, res) => {
const student = {
name: req.body.name,
course: req.body.course
};
res.status(201).json({
success: true,
message: "Student created successfully.",
student: student
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Send
{
"name": "Priya",
"course": "JavaScript"
}
Response
{
"success": true,
"message": "Student created successfully.",
"student": {
"name": "Priya",
"course": "JavaScript"
}
}
The HTTP status is:
201 Created
Step-by-Step Explanation
This:
res.status(201)
sets the HTTP status code.
Then:
.json(...)
sends the JSON response.
You can combine them:
res.status(201).json({
message: "Created"
});
Common Status Codes
| Status | Meaning |
|---|---|
| 200 | Successful request |
| 201 | Resource created |
| 400 | Bad request |
| 401 | Authentication required |
| 403 | Forbidden |
| 404 | Resource not found |
| 500 | Server error |
Question 9: How do you redirect a user using the response object?
Problem
Create an Express route that redirects the user from /old-page to /new-page.
Solution
const express = require("express");
const app = express();
app.get("/old-page", (req, res) => {
res.redirect("/new-page");
});
app.get("/new-page", (req, res) => {
res.send("Welcome to the New Page.");
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Test
Open:
http://localhost:3000/old-page
The browser will be redirected to:
http://localhost:3000/new-page
Output
Welcome to the New Page.
Step-by-Step Explanation
The old route uses:
res.redirect("/new-page");
Express tells the browser to go to another URL.
The new route then handles the request:
app.get("/new-page", ...)
Redirect to an External Website
You can also redirect to another website:
res.redirect("https://example.com");
Question 10: How do you combine request and response objects in a practical API?
Problem
Create a student API that reads:
- Student ID from route parameters
- Course from query parameters
- Student name from JSON body
- HTTP method from the request
- A custom response using
res.status()andres.json()
Solution
const express = require("express");
const app = express();
app.use(express.json());
app.post("/students/:id", (req, res) => {
const studentId = req.params.id;
const course = req.query.course;
const name = req.body.name;
const method = req.method;
res.status(200).json({
success: true,
method: method,
studentId: studentId,
name: name,
course: course
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Send This Request
URL:
http://localhost:3000/students/25?course=Node.js
Method:
POST
JSON body:
{
"name": "Rahul"
}
Response
{
"success": true,
"method": "POST",
"studentId": "25",
"name": "Rahul",
"course": "Node.js"
}
Step-by-Step Explanation
The route is:
/students/:id
So the student ID comes from:
req.params.id
The URL also contains:
?course=Node.js
So the course comes from:
req.query.course
The JSON body contains:
{
"name": "Rahul"
}
So the name comes from:
req.body.name
The HTTP method comes from:
req.method
Finally, the server sends the response using:
res.status(200).json(...)
Request and Response Flow
Client
↓
POST /students/25?course=Node.js
↓
Express
↓
req.params.id
req.query.course
req.body.name
req.method
↓
Route Handler
↓
res.status()
↓
res.json()
↓
Client
Key Takeaways
- Express uses
reqto represent the incoming request. - Express uses
resto represent the outgoing response. req.methodreturns the HTTP method.req.urlprovides the requested URL.req.paramscontains route parameters.req.querycontains query parameters.req.bodycontains parsed request body data.express.json()is needed to parse JSON request bodies.req.get()can read request headers.res.send()sends a response to the client.res.json()sends a JSON response.res.status()sets the HTTP status code.res.redirect()redirects the client to another URL.req.paramsandreq.queryserve different purposes.- Route parameters are part of the URL path.
- Query parameters appear after
?in the URL. - Request bodies are commonly used with POST and PUT/PATCH requests.
- HTTP headers provide additional request information.
- JSON responses are widely used in REST APIs.
- Status codes communicate the result of a request.
- A good Express API should return meaningful status codes.
reqhelps the server understand what the client sent.resallows the server to control what the client receives.- Request and response objects are fundamental to Express.js development.
FAQs
1. What is the req object in Express.js?
The req object represents the incoming HTTP request.
It provides information such as:
req.method
req.url
req.params
req.query
req.body
For example:
app.get("/", (req, res) => {
console.log(req.method);
});
The request object helps the server understand what the client requested.
2. What is the res object in Express.js?
The res object represents the HTTP response that the server sends to the client.
Common response methods include:
res.send()
res.json()
res.status()
res.redirect()
For example:
res.json({
message: "Hello"
});
3. What is the difference between req.params and req.query?
req.params contains parameters defined in the route.
Example:
/students/10
Route:
app.get("/students/:id", ...)
Access:
req.params.id
req.query contains parameters after ?.
Example:
/students?course=Node.js
Access:
req.query.course
4. What is req.body in Express.js?
req.body contains data sent by the client in the request body.
For JSON requests, you normally enable:
app.use(express.json());
Then:
req.body.name
can access a name property from the JSON body.
5. What is the difference between res.send() and res.json()?
res.send() can send different types of responses, including text.
Example:
res.send("Hello World");
res.json() is designed for sending JSON responses.
Example:
res.json({
message: "Hello World"
});
res.json() is especially common when creating APIs.
6. How do you set an HTTP status code in Express.js?
Use:
res.status()
For example:
res.status(404).json({
message: "Student not found."
});
This sends a 404 Not Found status along with a JSON response.
7. How do you read request headers in Express.js?
You can use:
req.get("Header-Name")
For example:
const userAgent = req.get("User-Agent");
You can also access the headers object directly:
req.headers
Headers contain metadata about the HTTP request.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
