Introduction
Express.js is a lightweight web framework built on Node.js. It makes creating web servers, routes, APIs, middleware, and request-response handling much easier. In this chapter, you will practice Express.js basics with 10 solved questions, starting from creating an Express server and gradually moving to routes, request data, JSON responses, middleware, status codes, and basic error handling. Node.js Express.js Basics practice questions with solutions help to build concepts
Question 1: How do you install Express.js?
Problem
Create a new Node.js project and install Express.js.
Solution
Create a project folder:
mkdir express-practice
cd express-practice
Initialize the Node.js project:
npm init -y
Install Express:
npm install express
Create a file named:
index.js
Step-by-Step Explanation
npm init -y creates the package.json file.
npm init -y
Then:
npm install express
installs Express.js into your project.
Your project will look similar to:
express-practice/
│
├── node_modules/
├── package.json
├── package-lock.json
└── index.js
Check Express Installation
Open package.json:
{
"dependencies": {
"express": "^5.x"
}
}
The exact version may be different depending on when you install it.
Question 2: How do you create a basic Express.js server?
Problem
Create an Express server that displays a simple message in the browser.
Solution
Create index.js:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Hello from Express.js!");
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Run the application:
node index.js
Output
You will see:
Server running on http://localhost:3000
Open:
http://localhost:3000
You will see:
Hello from Express.js!
Step-by-Step Explanation
First import Express:
const express = require("express");
Create an Express application:
const app = express();
Create a route:
app.get("/", (req, res) => {
Send a response:
res.send("Hello from Express.js!");
Start the server:
app.listen(3000);
Question 3: How do you create multiple routes in Express.js?
Problem
Create separate routes for:
- Home
- About
- Contact
Solution
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Welcome to the Home Page");
});
app.get("/about", (req, res) => {
res.send("This is the About Page");
});
app.get("/contact", (req, res) => {
res.send("This is the 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
Contact:
http://localhost:3000/contact
Step-by-Step Explanation
Each route has three important parts:
app.get("/about", (req, res) => {
app.get() specifies the HTTP method.
GET
"/about" specifies the URL path.
/about
req represents the incoming request.
res represents the response sent back to the client.
Question 4: How do you send JSON data from Express.js?
Problem
Create an API endpoint that returns student information as JSON.
Solution
const express = require("express");
const app = express();
app.get("/student", (req, res) => {
res.json({
id: 1,
name: "Rahul",
course: "Node.js"
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Open:
http://localhost:3000/student
Output
{
"id": 1,
"name": "Rahul",
"course": "Node.js"
}
Step-by-Step Explanation
The important method is:
res.json()
It sends JavaScript data as a JSON response.
For example:
res.json({
name: "Rahul",
course: "Node.js"
});
Express handles the JSON response for you.
Question 5: How do you handle POST requests in Express.js?
Problem
Create an Express API that receives a student’s name and course using a POST request.
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.status(201).json({
message: "Student received successfully.",
student: {
name: name,
course: course
}
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Request
Send:
POST /students
with this JSON body:
{
"name": "Priya",
"course": "JavaScript"
}
Response
{
"message": "Student received successfully.",
"student": {
"name": "Priya",
"course": "JavaScript"
}
}
Step-by-Step Explanation
First add:
app.use(express.json());
This middleware allows Express to parse incoming JSON request bodies.
The body is 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 use route parameters in Express.js?
Problem
Create a route that displays a student’s ID from the URL.
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/25
Output
{
"message": "Student information",
"id": "25"
}
Step-by-Step Explanation
The route contains:
"/students/:id"
The :id is a route parameter.
Its value can be accessed using:
req.params.id
If you visit:
/students/25
then:
req.params.id
will contain:
25
Converting the Parameter to a Number
Route parameters are received as strings.
If you need a number:
const studentId = Number(req.params.id);
Question 7: How do you use query parameters in Express.js?
Problem
Create a search API that accepts a student’s name through a query parameter.
Solution
const express = require("express");
const app = express();
app.get("/search", (req, res) => {
const name = req.query.name;
res.json({
message: "Search request received.",
searchName: name
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Test
Open:
http://localhost:3000/search?name=Rahul
Output
{
"message": "Search request received.",
"searchName": "Rahul"
}
Step-by-Step Explanation
The URL contains:
?name=Rahul
This is a query parameter.
Express provides query parameters through:
req.query
Therefore:
req.query.name
returns:
Rahul
Multiple Query Parameters
You can also use:
/search?name=Rahul&course=Node.js
Then:
const name = req.query.name;
const course = req.query.course;
Question 8: How do you create custom middleware in Express.js?
Problem
Create middleware that prints the HTTP method and requested URL whenever a user visits your server.
Solution
const express = require("express");
const app = express();
const logger = (req, res, next) => {
console.log(
`${req.method} ${req.url}`
);
next();
};
app.use(logger);
app.get("/", (req, res) => {
res.send("Home Page");
});
app.get("/about", (req, res) => {
res.send("About Page");
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Example Console Output
If you visit:
http://localhost:3000/
you may see:
GET /
If you visit:
http://localhost:3000/about
you may see:
GET /about
Step-by-Step Explanation
Middleware is a function that runs during the request-response process.
Our middleware is:
const logger = (req, res, next) => {
It prints:
console.log(
`${req.method} ${req.url}`
);
Then:
next();
passes control to the next middleware or route handler.
We activate it using:
app.use(logger);
What Happens Without next()?
If middleware does not send a response and does not call:
next();
the request may not continue to the next handler.
Question 9: How do you send an HTTP status code in Express.js?
Problem
Create an API that returns different status codes for success and missing data.
Solution
const express = require("express");
const app = express();
const students = [
{
id: 1,
name: "Rahul"
},
{
id: 2,
name: "Priya"
}
];
app.get("/students/: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
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Test 1
Open:
http://localhost:3000/students/1
You will receive a successful response with status:
200
Test 2
Open:
http://localhost:3000/students/99
You will receive:
{
"success": false,
"message": "Student not found."
}
with status:
404
Common Express Status Codes
200 → Successful request
201 → Resource created
400 → Bad request
401 → Authentication required/failed
403 → Access forbidden
404 → Resource not found
500 → Internal server error
Important Point
You can set the status code using:
res.status(404)
and then send a response:
res.status(404).json({
message: "Not found"
});
Question 10: How do you create a simple Express.js application using routes, JSON, middleware, and error handling?
Problem
Build a small Express application that contains:
- Custom middleware
- JSON parsing
- GET route
- POST route
- Route parameter
- Basic validation
- Error handling
Solution
Create index.js:
const express = require("express");
const app = express();
app.use(express.json());
// Custom middleware
app.use((req, res, next) => {
console.log(
`${req.method} ${req.url}`
);
next();
});
// Temporary data
let students = [
{
id: 1,
name: "Rahul",
course: "Node.js"
},
{
id: 2,
name: "Priya",
course: "JavaScript"
}
];
// Get all students
app.get("/api/students", (req, res) => {
res.status(200).json({
success: true,
students: students
});
});
// Get one student
app.get("/api/students/: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
app.post("/api/students", (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
});
});
// 404 handler
app.use((req, res) => {
res.status(404).json({
success: false,
message: "Route not found."
});
});
// Error-handling middleware
app.use((error, req, res, next) => {
console.error(error);
res.status(500).json({
success: false,
message: "Internal server error."
});
});
app.listen(3000, () => {
console.log(
"Server running on http://localhost:3000"
);
});
Step-by-Step Explanation
Step 1: Import Express
const express = require("express");
Step 2: Create the application
const app = express();
Step 3: Enable JSON parsing
app.use(express.json());
Now Express can read JSON request bodies.
Step 4: Add custom middleware
app.use((req, res, next) => {
console.log(
`${req.method} ${req.url}`
);
next();
});
This logs every request.
Step 5: Create GET route
app.get("/api/students", (req, res) => {
This returns all students.
Step 6: Create parameter route
app.get("/api/students/:id", (req, res) => {
This returns one student.
Step 7: Create POST route
app.post("/api/students", (req, res) => {
This creates a new student.
Step 8: Validate input
if (!name || !course) {
If either value is missing, the server returns:
400 Bad Request
Step 9: Add a 404 handler
app.use((req, res) => {
res.status(404).json({
success: false,
message: "Route not found."
});
});
This handles requests for routes that do not exist.
Step 10: Add error-handling middleware
app.use((error, req, res, next) => {
Express recognizes error-handling middleware by its four parameters:
error
req
res
next
Project Structure
express-practice/
│
├── node_modules/
├── index.js
├── package.json
└── package-lock.json
Run the Application
node index.js
Output:
Server running on http://localhost:3000
Test the API
Get all students:
GET /api/students
Get one student:
GET /api/students/1
Create a student:
POST /api/students
JSON body:
{
"name": "Aman",
"course": "Python"
}
Try a missing route:
GET /something
You will receive:
{
"success": false,
"message": "Route not found."
}
Key Takeaways
- Express.js is a web framework for Node.js.
- Express makes server and API development easier.
- Install Express using
npm install express. - Create an Express application using
express(). - Use
app.listen()to start the server. app.get()creates GET routes.app.post()creates POST routes.app.put()creates PUT routes.app.patch()creates PATCH routes.app.delete()creates DELETE routes.reqrepresents the incoming HTTP request.resrepresents the server response.res.send()can send a response to the client.res.json()is commonly used to send JSON.req.bodycontains parsed request-body data.req.paramscontains route parameters.req.querycontains query parameters.express.json()parses incoming JSON request bodies.- Middleware runs during the request-response cycle.
next()passes control to the next middleware or route handler.res.status()sets the HTTP status code.- Route parameters are useful for identifying specific resources.
- Query parameters are useful for searching and filtering.
- Express supports custom middleware.
- Express applications can have 404 handlers.
- Error-handling middleware uses four parameters:
error,req,res, andnext. - Express can be used to build REST APIs and complete backend applications.
FAQs
1. What is Express.js in Node.js?
Express.js is a lightweight web framework for Node.js. It provides features for creating web servers, routes, middleware, REST APIs, and request-response handling.
2. How do I install Express.js?
Inside your Node.js project, run:
npm install express
Then import it:
const express = require("express");
3. What is the difference between Node.js and Express.js?
Node.js is a JavaScript runtime that allows JavaScript to run outside the browser.
Express.js is a framework that runs on Node.js and provides convenient tools for building web servers and APIs.
A simple way to remember it is:
Node.js → Runtime
Express.js → Web framework for Node.js
4. What does app.get() do in Express.js?
app.get() creates a route that responds to HTTP GET requests.
Example:
app.get("/about", (req, res) => {
res.send("About Page");
});
When a user visits /about using GET, this route executes.
5. What is middleware in Express.js?
Middleware is a function that runs during the request-response process.
Example:
app.use((req, res, next) => {
console.log(req.method);
next();
});
The next() function allows the request to continue to the next middleware or route handler.
6. What is req.params in Express.js?
req.params contains values from route parameters.
For example:
app.get("/students/:id", (req, res) => {
console.log(req.params.id);
});
For:
/students/10
req.params.id contains:
10
7. What is express.json() used for?
express.json() is built-in Express middleware that parses incoming JSON request bodies.
Example:
app.use(express.json());
After adding it, JSON data can be accessed using:
req.body
For example:
{
"name": "Rahul",
"course": "Node.js"
}
can be accessed with:
req.body.name
req.body.course
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
