Lesson 31 of 50 – Introduction to Express.js
62% Completed
62%

Introduction to Express.js

Express.js is a popular web framework for Node.js. It makes it easier to create web servers, websites, and REST APIs.

In this lesson: You will learn what Express.js is, why we use it, how to install it, and how to create your first Express application.

1. What Is Express.js?

Express.js is a lightweight web framework built on top of Node.js. It provides useful features for handling HTTP requests, sending responses, creating routes, and building APIs.

Example: Node.js and Express.js

Node.js: Allows JavaScript to run outside a browser.

Express.js: Makes building web servers and APIs with Node.js easier.

Express.js runs on Node.js. It does not replace Node.js.

2. Why Do We Use Express.js?

Express.js helps developers build web applications with less code.

Feature Description
Routing Handles different URLs and HTTP methods.
Request Handling Reads information sent by clients.
Response Handling Sends text, HTML, JSON, or other responses.
Middleware Runs functions during the request-response process.
REST APIs Helps create APIs for websites and mobile applications.

3. Requirements Before Learning Express.js

You should know the following before starting Express.js:

  • Basic JavaScript
  • Variables, functions, and objects
  • Basic Node.js concepts
  • npm and Node.js installation
  • Basic understanding of HTTP requests and responses
Note: Make sure Node.js and npm are installed on your computer before continuing.

4. Create an Express.js Project

Follow these steps to create your first Express project.

Step 1: Create a Project Folder

Open your terminal or command prompt and run:

mkdir express-demo
cd express-demo
Step 2: Initialize the Project

Run the following command:

npm init -y

This command creates a package.json file containing project information and configuration.

Step 3: Install Express.js

Run this command inside the project folder:

npm install express

npm downloads Express.js and adds it to the project's dependencies.

5. Create Your First Express Application

Create a file named app.js inside the express-demo folder.

app.js
const express = require('express');

const app = express();

app.get('/', (req, res) => {
    res.send('Welcome to Express.js!');
});

app.listen(3000, () => {
    console.log('Server running at http://localhost:3000');
});

Understanding the Code

  • require('express') loads the Express package using CommonJS.
  • express() creates an Express application.
  • app.get() defines a route for HTTP GET requests.
  • req represents the incoming request.
  • res represents the response sent to the client.
  • res.send() sends a response to the client.
  • app.listen() starts the server on port 3000.

6. Run the Express Server

Run the following command in your terminal:

node app.js

You should see this message:

Server running at http://localhost:3000

Now open your browser and visit: http://localhost:3000

Browser Output
Welcome to Express.js!

Your first Express application is running successfully.

7. Understand Express Routing

Routing determines how an application responds to a request made to a particular URL and HTTP method.

Example: Multiple Routes
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('/contact', (req, res) => {
    res.send('Contact Page');
});

app.listen(3000, () => {
    console.log('Server started on port 3000');
});

Try these URLs:

  • http://localhost:3000/ — Home Page
  • http://localhost:3000/about — About Page
  • http://localhost:3000/contact — Contact Page

8. Send a JSON Response

Express.js is commonly used to create APIs. APIs often send data in JSON format.

Example: JSON Response
const express = require('express');

const app = express();

app.get('/student', (req, res) => {
    res.json({
        id: 101,
        name: 'Rahul',
        course: 'Node.js'
    });
});

app.listen(3000, () => {
    console.log('Server started on port 3000');
});

Visit http://localhost:3000/student.

Expected JSON response:

{
  "id": 101,
  "name": "Rahul",
  "course": "Node.js"
}

9. What Is Middleware?

Middleware is a function that can run during the request-response cycle. Middleware can inspect requests, perform tasks, modify request or response objects, and pass control to the next function.

Example: Simple Middleware
const express = require('express');

const app = express();

app.use((req, res, next) => {
    console.log('A request was received');
    next();
});

app.get('/', (req, res) => {
    res.send('Hello Student!');
});

app.listen(3000, () => {
    console.log('Server started on port 3000');
});

app.use() registers middleware. next() passes control to the next middleware or route handler when appropriate.

10. Important Express.js Methods

Method Purpose
express() Creates an Express application.
app.get() Handles HTTP GET requests.
app.post() Handles HTTP POST requests.
app.put() Handles HTTP PUT requests.
app.delete() Handles HTTP DELETE requests.
app.use() Registers middleware or mounts a router.
res.send() Sends a response.
res.json() Sends a JSON response.
app.listen() Starts the server listening for requests.

11. Node.js HTTP Module vs Express.js

Node.js HTTP Module Express.js
Built into Node.js. Installed separately using npm.
Requires more manual request handling. Provides convenient routing and middleware.
Uses http.createServer(). Uses express() to create an app.
Useful for low-level HTTP server work. Useful for web applications and REST APIs.

12. Practical Assignment

Assignment: Create a Simple Website Server

Create an Express application with the following requirements:

  1. Create a project named my-express-app.
  2. Initialize the project using npm init -y.
  3. Install Express.js.
  4. Create an app.js file.
  5. Create a home route that displays your name.
  6. Create an about route that displays your course name.
  7. Create a /student route that returns JSON data.
  8. Run the server and test all three routes in your browser.
Lesson Summary: Express.js is a Node.js web framework. You learned how to install Express, create an application, define routes, send text and JSON responses, and use basic middleware.

Test Your Knowledge – MCQ Quiz

Select the correct answer for each question.

1. What is Express.js?
2. Which command installs Express.js?
3. Which method sends a JSON response in Express.js?