Express.js Introduction
Express.js is a lightweight and flexible web framework for Node.js. It helps developers create web applications and APIs easily by providing features for routing, request handling, middleware, and response management.
In the previous module, we learned how to create an HTTP server using Node.js's built-in HTTP module. Now, we will learn how Express.js makes server-side development simpler and more organized.
1. What Is Express.js?
Express.js is a web framework that runs on Node.js. It provides a simple way to handle HTTP requests, define routes, send responses, and build REST APIs.
For example, Samadhan wants to create a website where users can view courses offered by CIIT Training Institute. Using Express.js, he can create routes for displaying course information, handling user requests, and returning responses.
Without a framework, we can use Node.js's built-in HTTP module to handle requests manually. Express.js provides convenient methods that make many common tasks easier.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to Express.js!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
In this example, we create an Express application, define a route for the home page, send a response, and start the server on port 3000.
2. Why Do We Use Express.js?
Express.js simplifies common server-side programming tasks. It helps developers organize application logic and build APIs without manually implementing every request-handling operation.
| Feature | Explanation |
|---|---|
| Routing | Defines how the application responds to different URLs and HTTP methods. |
| Request Handling | Provides access to request information through the request object. |
| Response Handling | Provides convenient methods to send text, JSON, and other responses. |
| Middleware | Allows functions to process requests and responses in a sequence. |
| REST APIs | Helps developers create endpoints for exchanging application data. |
| Static Files | Supports serving files such as CSS, JavaScript, and images. |
3. Node.js vs Express.js
Node.js and Express.js are related, but they are not the same thing. Node.js provides the JavaScript runtime and built-in modules. Express.js is a framework that runs on Node.js.
| Node.js | Express.js |
|---|---|
| A JavaScript runtime environment. | A web framework for Node.js. |
Provides built-in modules such as http. |
Provides convenient routing and request-handling methods. |
| Can create an HTTP server directly. | Can create a web application using Express methods. |
| Can handle requests using lower-level APIs. | Simplifies many common web development tasks. |
Remember: Express.js does not replace Node.js. Express.js runs on top of Node.js and uses its capabilities.
4. Architecture of Express.js
The following diagram shows how a browser communicates with an Express.js application running on Node.js.
Client / Browser
Sends an HTTP request
Express.js Application
Receives and processes the request
Route Handler
Executes the matching route logic
HTTP Response
Sends the result back to the client
For example, when a user opens the home page, Express.js matches
the GET route for / and executes its callback function.
The response is then sent to the browser.
5. Important Features of Express.js
A. Routing
Routing determines how the application responds when a client requests a particular URL using a particular HTTP method.
app.get('/', (req, res) => {
res.send('Home Page');
});
app.get('/about', (req, res) => {
res.send('About Page');
});
Here, the first route responds to requests for /,
while the second responds to requests for /about.
B. Request and Response Handling
Express.js provides the req object to access
information about an incoming request and the res
object to send a response.
app.get('/student', (req, res) => {
res.send('Student Details');
});
When the client requests /student, the server
responds with the text Student Details.
C. JSON Responses
Express.js provides res.json() to send JavaScript
objects or arrays as JSON responses.
app.get('/api/course', (req, res) => {
res.json({
name: 'Node.js',
institute: 'CIIT Training Institute'
});
});
The client receives the course information in JSON format. This is useful when developing REST APIs.
6. Creating Your First Express Application
Now let us create a simple Express.js application that responds to requests for the home page and the about page.
Step 1: Create a project folder.
mkdir express-demo
cd express-demo
Step 2: Initialize the Node.js project.
npm init -y
This command creates a package.json file containing
project information and configuration.
Step 3: Install Express.js.
npm install express
This command installs Express.js as a dependency of the project.
Step 4: Create a file named server.js.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Welcome to Express.js!');
});
app.get('/about', (req, res) => {
res.send('This is the About page.');
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
In this example, we define two GET routes. The home route responds with a welcome message, and the about route responds with information about the page.
7. Express Application Request Flow
This diagram shows how the two routes in our application respond to different browser requests.
Browser Request
GET / or GET /about
Express Route Matching
Checks the HTTP method and URL
GET /
Home route
GET /about
About route
Express.js executes the callback associated with the matching route and sends the response to the client.
8. Running the Express Application
Save your code in server.js and execute the following
command in the terminal.
node server.js
Expected terminal output:
Server running at http://localhost:3000
Test the home page:
http://localhost:3000/
Browser response:
Welcome to Express.js!
Test the about page:
http://localhost:3000/about
Browser response:
This is the About page.
9. Understanding the Express Code
| Code | Explanation |
|---|---|
require('express') |
Imports the installed Express.js package. |
express() |
Creates an Express application. |
app.get() |
Defines a route that handles GET requests. |
req |
Represents the incoming HTTP request. |
res |
Represents the HTTP response. |
res.send() |
Sends a response to the client. |
res.json() |
Sends a JSON response. |
app.listen() |
Starts the application server on the specified port. |
10. Important Points to Remember
- Express.js is a web framework built for Node.js.
- Express.js must be installed before it can be imported into a project.
express()creates an Express application.app.get()handles GET requests for specified routes.reqprovides information about the incoming request.res.send()sends a response to the client.res.json()sends data as a JSON response.app.listen()starts the server.- Express.js simplifies routing and common web application tasks.
11. Practice Tasks
Task 1: Create a Home Page
- Create a Node.js project.
- Install Express.js using
npm install express. - Create a file named
server.js. - Define a GET route for
/. - Display a welcome message using
res.send().
Expected result: Opening the home page should display a welcome message in the browser.
Task 2: Create an About Page
- Create a GET route for
/about. - Return a message describing your application.
- Start the server and test the route in your browser.
Expected result: The about page should display the message returned by the Express route.
Task 3: Return Course Information
- Create a GET route named
/api/course. - Create an object containing a course name and institute name.
- Return the object using
res.json(). - Open the route in the browser to view the JSON response.
Expected result: The browser should display course information in JSON format.
Summary
In this lesson, we learned that Express.js is a web framework for Node.js that simplifies routing, request handling, and response management. We compared Node.js with Express.js, explored its architecture, and created our first Express application with home and about routes.
Remember the flow: Client Request → Express Application → Route Handler → HTTP Response.