Introduction
Routing is one of the most important concepts in Express.js. It decides how a server responds when a user visits a particular URL or sends a specific HTTP request. In this chapter, you will practice Express routing with 10 solved questions covering basic routes, multiple routes, route parameters, query parameters, HTTP methods, route handlers, route-specific middleware, route chaining, and a simple REST-style routing example. Node.js Express Routing practice questions with solutions help to understand the concepts.
Question 1: How do you create a basic route in Express.js?
Problem
Create a simple Express application with a home route that displays a welcome message.
Solution
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Welcome to the Node.js Express Routing Practice!");
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Run the Application
node index.js
Open:
http://localhost:3000/
Output
Welcome to the Node.js Express Routing Practice!
Step-by-Step Explanation
This creates a GET route:
app.get("/", (req, res) => {
The first argument:
"/"
represents the home URL.
The second argument is the route handler:
(req, res) => {
res.send("Welcome...");
}
req represents the request, while res is used to send the response.
Question 2: How do you create multiple routes in Express.js?
Problem
Create separate routes for Home, About, Courses, and Contact pages.
Solution
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Home Page");
});
app.get("/about", (req, res) => {
res.send("About Page");
});
app.get("/courses", (req, res) => {
res.send("Courses Page");
});
app.get("/contact", (req, res) => {
res.send("Contact Page");
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Test the Routes
Home:
http://localhost:3000/
About:
http://localhost:3000/about
Courses:
http://localhost:3000/courses
Contact:
http://localhost:3000/contact
Step-by-Step Explanation
Each route follows this structure:
app.get("PATH", (req, res) => {
// Response
});
For example:
app.get("/courses", (req, res) => {
res.send("Courses Page");
});
When the browser requests:
/courses
Express executes this route.
Question 3: How do you create routes for different HTTP methods?
Problem
Create separate routes for GET, POST, PUT, and DELETE requests for students.
Solution
const express = require("express");
const app = express();
app.use(express.json());
app.get("/students", (req, res) => {
res.send("GET: Get all students");
});
app.post("/students", (req, res) => {
res.send("POST: Create a student");
});
app.put("/students", (req, res) => {
res.send("PUT: Update a student");
});
app.delete("/students", (req, res) => {
res.send("DELETE: Delete a student");
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Routing Table
| HTTP Method | Route | Purpose |
|---|---|---|
| GET | /students | Get students |
| POST | /students | Create student |
| PUT | /students | Update student |
| DELETE | /students | Delete student |
Step-by-Step Explanation
The URL is the same:
/students
but the HTTP methods are different.
For GET:
app.get("/students", ...)
For POST:
app.post("/students", ...)
For PUT:
app.put("/students", ...)
For DELETE:
app.delete("/students", ...)
Express determines which handler to execute based on both the HTTP method and path.
Question 4: How do you use route parameters in Express routing?
Problem
Create a route that displays information about a specific student based on their ID.
Solution
const express = require("express");
const app = express();
app.get("/students/:id", (req, res) => {
const studentId = req.params.id;
res.json({
message: "Student information",
id: studentId
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Test
Open:
http://localhost:3000/students/15
Output
{
"message": "Student information",
"id": "15"
}
Step-by-Step Explanation
The route contains:
"/students/:id"
The :id part is a route parameter.
If the URL is:
/students/15
then:
req.params.id
contains:
15
You can also convert it to a number:
const studentId = Number(req.params.id);
More Examples
/students/1
/students/2
/students/10
/students/100
All of these can be handled by:
app.get("/students/:id", ...)
Question 5: How do you use multiple route parameters?
Problem
Create a route that accepts both a course name and a student ID.
Solution
const express = require("express");
const app = express();
app.get(
"/courses/:course/students/:id",
(req, res) => {
const course = req.params.course;
const id = req.params.id;
res.json({
course: course,
studentId: id
});
}
);
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Test
Open:
http://localhost:3000/courses/nodejs/students/25
Output
{
"course": "nodejs",
"studentId": "25"
}
Step-by-Step Explanation
The route contains two parameters:
/courses/:course/students/:id
The course is available through:
req.params.course
The student ID is available through:
req.params.id
Another Example
Request:
/courses/python/students/10
Values:
course = python
id = 10
Question 6: How do you use query parameters with Express routes?
Problem
Create a student search route that accepts a name and course through query parameters.
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({
message: "Search request",
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
{
"message": "Search request",
"name": "Rahul",
"course": "Node.js"
}
Step-by-Step Explanation
The query string is:
?name=Rahul&course=Node.js
Express provides these values through:
req.query
Therefore:
req.query.name
returns:
Rahul
and:
req.query.course
returns:
Node.js
Question 7: How do you create route-specific middleware?
Problem
Create middleware that runs only when the /admin route is accessed.
Solution
const express = require("express");
const app = express();
const checkAdmin = (req, res, next) => {
console.log("Admin middleware executed.");
next();
};
app.get("/admin", checkAdmin, (req, res) => {
res.send("Welcome to the Admin Page");
});
app.get("/home", (req, res) => {
res.send("Welcome to the Home Page");
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Test
Visit:
http://localhost:3000/admin
Console:
Admin middleware executed.
Browser:
Welcome to the Admin Page
Now visit:
http://localhost:3000/home
The admin middleware does not execute.
Step-by-Step Explanation
The middleware is:
const checkAdmin = (req, res, next) => {
console.log("Admin middleware executed.");
next();
};
It is attached directly to the route:
app.get("/admin", checkAdmin, (req, res) => {
Therefore, it runs only for /admin.
Request Flow
Request
↓
/admin route
↓
checkAdmin middleware
↓
next()
↓
Route handler
↓
Response
Question 8: How do you use multiple route handlers in Express?
Problem
Create two route handlers for the same route. The first handler should log a message, and the second should send the response.
Solution
const express = require("express");
const app = express();
const firstHandler = (req, res, next) => {
console.log("First handler executed.");
next();
};
const secondHandler = (req, res) => {
res.send("Second handler sent the response.");
};
app.get(
"/students",
firstHandler,
secondHandler
);
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Output in Console
First handler executed.
Output in Browser
Second handler sent the response.
Step-by-Step Explanation
The request first enters:
firstHandler
It executes:
console.log("First handler executed.");
Then:
next();
passes control to:
secondHandler
The second handler sends:
res.send("Second handler sent the response.");
Request Flow
Client
↓
/students
↓
firstHandler
↓
next()
↓
secondHandler
↓
Response
Question 9: How do you use express.Router()?
Problem
Create a separate router for student routes instead of putting every route directly inside index.js.
Solution
Step 1: Create index.js
const express = require("express");
const app = express();
const studentRoutes = require("./studentRoutes");
app.use("/students", studentRoutes);
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Step 2: Create studentRoutes.js
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
res.send("All Students");
});
router.get("/:id", (req, res) => {
res.send(
`Student ID: ${req.params.id}`
);
});
router.post("/", (req, res) => {
res.send("Create Student");
});
module.exports = router;
Test
Open:
http://localhost:3000/students
Output:
All Students
Open:
http://localhost:3000/students/10
Output:
Student ID: 10
Step-by-Step Explanation
Create a router:
const router = express.Router();
Add routes to the router:
router.get("/", ...)
Then export it:
module.exports = router;
In index.js, import it:
const studentRoutes = require("./studentRoutes");
Mount it:
app.use("/students", studentRoutes);
Now:
router.get("/")
becomes:
/students
And:
router.get("/:id")
becomes:
/students/:id
Important Point
express.Router() helps organize large applications by keeping related routes in separate files.
Question 10: How do you create a complete Express routing example?
Problem
Create a small student API using:
- GET all students
- GET one student
- POST student
- PUT student
- DELETE student
- Route parameters
- JSON request body
- Status codes
express.Router()
Solution
Step 1: Create index.js
const express = require("express");
const app = express();
const studentRoutes = require("./studentRoutes");
app.use(express.json());
app.use("/api/students", studentRoutes);
app.use((req, res) => {
res.status(404).json({
success: false,
message: "Route not found."
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Step 2: Create studentRoutes.js
const express = require("express");
const router = express.Router();
let students = [
{
id: 1,
name: "Rahul",
course: "Node.js"
},
{
id: 2,
name: "Priya",
course: "JavaScript"
}
];
// GET all students
router.get("/", (req, res) => {
res.status(200).json({
success: true,
students: students
});
});
// GET one student
router.get("/:id", (req, res) => {
const id = Number(req.params.id);
const student = students.find(
student => student.id === id
);
if (!student) {
return res.status(404).json({
success: false,
message: "Student not found."
});
}
res.status(200).json({
success: true,
student: student
});
});
// CREATE student
router.post("/", (req, res) => {
const {
name,
course
} = req.body;
if (!name || !course) {
return res.status(400).json({
success: false,
message: "Name and course are required."
});
}
const newStudent = {
id: students.length + 1,
name: name,
course: course
};
students.push(newStudent);
res.status(201).json({
success: true,
message: "Student created successfully.",
student: newStudent
});
});
// UPDATE student
router.put("/:id", (req, res) => {
const id = Number(req.params.id);
const student = students.find(
student => student.id === id
);
if (!student) {
return res.status(404).json({
success: false,
message: "Student not found."
});
}
const {
name,
course
} = req.body;
if (!name || !course) {
return res.status(400).json({
success: false,
message: "Name and course are required."
});
}
student.name = name;
student.course = course;
res.status(200).json({
success: true,
message: "Student updated successfully.",
student: student
});
});
// DELETE student
router.delete("/:id", (req, res) => {
const id = Number(req.params.id);
const index = students.findIndex(
student => student.id === id
);
if (index === -1) {
return res.status(404).json({
success: false,
message: "Student not found."
});
}
const deletedStudent =
students.splice(index, 1)[0];
res.status(200).json({
success: true,
message: "Student deleted successfully.",
student: deletedStudent
});
});
module.exports = router;
Step 3: Run the Application
node index.js
You should see:
Server running on http://localhost:3000
Test 1: Get All Students
GET /api/students
Full URL:
http://localhost:3000/api/students
Test 2: Get One Student
GET /api/students/1
Full URL:
http://localhost:3000/api/students/1
Test 3: Create a Student
POST /api/students
JSON body:
{
"name": "Aman",
"course": "Python"
}
Test 4: Update a Student
PUT /api/students/1
JSON body:
{
"name": "Rahul Kumar",
"course": "Data Science"
}
Test 5: Delete a Student
DELETE /api/students/2
Step-by-Step Routing Structure
The main application contains:
app.use("/api/students", studentRoutes);
This means all student routes begin with:
/api/students
Inside studentRoutes.js:
router.get("/")
becomes:
GET /api/students
This:
router.get("/:id")
becomes:
GET /api/students/:id
This:
router.post("/")
becomes:
POST /api/students
This:
router.put("/:id")
becomes:
PUT /api/students/:id
And:
router.delete("/:id")
becomes:
DELETE /api/students/:id
Final Routing Map
| Method | Route | Purpose |
|---|---|---|
| GET | /api/students | Get all students |
| GET | /api/students/:id | Get one student |
| POST | /api/students | Create student |
| PUT | /api/students/:id | Update student |
| DELETE | /api/students/:id | Delete student |
Key Takeaways
- Routing determines how an Express application responds to URLs and HTTP methods.
- Express routes can be created using
app.get(),app.post(),app.put(),app.patch(), andapp.delete(). - A route normally contains an HTTP method, path, and handler function.
reqrepresents the incoming request.resrepresents the outgoing response.- Route parameters are created using
:parameterName. - Route parameters are available through
req.params. - Query parameters are available through
req.query. - Multiple route parameters can be used in one route.
- The same URL can have different handlers for different HTTP methods.
- Middleware can be attached to individual routes.
next()passes control to the next middleware or route handler.- Multiple route handlers can be used for a single route.
express.Router()helps organize routes into separate files.- Routers are especially useful in larger Express applications.
app.use()can mount a router at a specific path.- A router’s path is combined with the path used in
app.use(). - Route parameters are generally received as strings.
Number()can be used when a route parameter needs to be treated as a number.- Query parameters are useful for searching, filtering, sorting, and pagination.
- Route-specific middleware is useful for authentication, authorization, validation, and logging.
- A 404 route can handle requests for URLs that do not exist.
- Well-organized routing makes Express applications easier to read and maintain.
- REST APIs commonly use routing to represent resources and CRUD operations.
FAQs
1. What is routing in Express.js?
Routing is the process of deciding how an Express application responds to a particular URL and HTTP method.
For example:
app.get("/students", (req, res) => {
res.send("Students");
});
This route responds to a GET request for /students.
2. What is the difference between app.get() and router.get()?
app.get() creates a route directly on the main Express application.
Example:
app.get("/students", (req, res) => {
res.send("Students");
});
router.get() creates a route on an Express Router.
Example:
router.get("/", (req, res) => {
res.send("Students");
});
The router can then be mounted using:
app.use("/students", router);
This approach is useful for organizing large applications.
3. What are route parameters in Express.js?
Route parameters are dynamic values included in a URL.
Example:
app.get("/students/:id", (req, res) => {
res.send(req.params.id);
});
For:
/students/10
the value of:
req.params.id
is:
10
4. What is the difference between route parameters and query parameters?
A route parameter is part of the URL path:
/students/10
It can be accessed with:
req.params.id
A query parameter comes after ?:
/students?course=Node.js
It can be accessed with:
req.query.course
Route parameters are commonly used to identify resources, while query parameters are commonly used for filtering, searching, and other optional parameters.
5. Why is express.Router() used in Express.js?
express.Router() allows you to create modular and reusable route groups.
For example, you can keep student routes in:
studentRoutes.js
and product routes in:
productRoutes.js
This keeps a larger Express application organized.
6. Can one Express route have multiple middleware functions?
Yes.
For example:
app.get(
"/admin",
checkLogin,
checkAdmin,
(req, res) => {
res.send("Admin Page");
}
);
The middleware functions execute in order. A middleware normally calls next() to pass control to the next function.
7. Can the same URL have different HTTP methods in Express.js?
Yes.
For example:
app.get("/students", ...);
app.post("/students", ...);
app.put("/students", ...);
app.delete("/students", ...);
All four routes use /students, but they respond to different HTTP methods and can perform different operations.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
