0% found this document useful (0 votes)
1 views54 pages

10 introduction to Express node and middleware

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 54

Introduction to Express.

js

25/02/2025 By Dr. Jaspreet Singh Bajaj


Express.js

 Express.js is a fast, flexible web framework for Node.js.


 It’s effectively a tool that simplifies building web applications
and APIs using JavaScript on the server side.
 Express is an open-source that is developed and maintained by
the Node.js foundation.
 Express.js offers a robust set of features that enhance your
productivity and streamline your web application.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Why learn Express?

 Express is a user-friendly framework that simplifies the


development process of Node applications.
 It uses JavaScript as a programming language and provides an
efficient way to build web applications and APIs.
 With Express, you can easily handle routes, requests, and
responses, which makes the process of creating robust and
scalable applications much easier.
 Moreover, it is a lightweight and flexible framework that is easy
to learn and comes loaded with middleware options.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Getting Started Express

• 1. Installation: Install Express using npm:

npm install express

25/02/2025 By Dr. Jaspreet Singh Bajaj


2. Basic Example of an Express App:
const express =  Import the ‘express’ module to create
require('express'); a web application using Node.js.
const app = express();  Initialize an Express app using const
app = express();.
// Define routes and
middleware here  Add routes
// ... (endpoints) and middleware function
s to handle requests and perform
tasks like authentication or logging.
const PORT =
process.env.PORT || 3000;  Specify a port (defaulting to 3000) for
app.listen(PORT, () => { the server to listen on.
console.log(`Server running
on port ${PORT}`);
});

25/02/2025 By Dr. Jaspreet Singh Bajaj


Key Features of Express

 Middleware and Routing: Define clear pathways (routes) within


your application to handle incoming HTTP requests (GET, POST,
PUT, DELETE) with ease. Implement reusable functions
(middleware) to intercept requests and create responses, adding
functionalities like authentication, logging, and data parsing.
 Minimalistic Design: Express.js follows a simple and minimalistic
design philosophy. This simplicity allows you to quickly set up a
server, define routes, and handle HTTP requests efficiently. It’s an
excellent choice for building web applications without unnecessary
complexity.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Key Features of Express

 Flexibility and Customization: Express.js doesn’t impose a strict


application architecture. You can structure your code according to
your preferences. Whether you’re building a RESTful
(Representational State Transfer) API or a full-fledged web
app, Express.js adapts to your needs.
 Templating Power: Incorporate templating engines like Jade or EJS
(Embedded JavaScript templates) to generate dynamic HTML
content, enhancing user experience.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Key Features of Express

 Static File Serving: Effortlessly serve static files like images, CSS,
and JavaScript from a designated directory within your
application.
 Node.js Integration: Express.js seamlessly integrates with the
core functionalities of Node.js, allowing you to harness the
power of asynchronous programming and event-driven
architecture.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Applications of Express

• RESTful APIs: Develop robust APIs that adhere to the REST


architectural style, enabling communication with other
applications and front-end interfaces.
• Real-time Applications: Leverage Express.js’s event-driven nature
to create real-time applications like chat or collaborative editing
tools.
• Single-Page Applications (SPAs): Craft SPAs that fetch and update
content dynamically on the client-side, offering a seamless user
experience.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Installing Express on Windows (WINDOWS 10)

• Assuming that you have installed node.js on your system, the


following steps should be followed to install express on your
Windows:
• STEP-1: Creating a directory for our project and make that our
working directory.

$ mkdir myexpress
$ cd myexpress

25/02/2025 By Dr. Jaspreet Singh Bajaj


STEP-2: Using npm init command to create
a package.json file for our project.
• $ npm init -y

STEP-3: Installing Express


$ npm install express

25/02/2025 By Dr. Jaspreet Singh Bajaj


STEP-4: Verify that Express.js was installed on your
Windows:

• C:\Users\Admin\myexpress\node_modules>npm --version
express

25/02/2025 By Dr. Jaspreet Singh Bajaj


package.json
The package.json file is the heart of Node.js system. It is the manifest
file of any Node.js project and contains the metadata of the project.
The package.json file is the essential part to understand, learn and
work with the Node.js. It is the first step to learn about development
in Node.js.
The package.json file contains the metadata information. This
metadata information in package.json file can be categorized into
Identifying metadata properties: It basically consist of the properties
to identify the module/project such as the name of the project,
current version of the module, license, author of the project,
description about the project etc.
Functional metadata properties: As the name suggests, it consists of
the functional values/properties of the project/module such as the
entry/starting point of the module, dependencies in project, scripts
being used, repository links of Node project etc.
25/02/2025 By Dr. Jaspreet Singh Bajaj
Router in Express.js

In Express.js, a router is a mini-application capable of performing


middleware and routing functions. It is an isolated instance of
middleware and routing, allowing you to create modular and
mountable route handlers. A router behaves similarly to the main
express object, but it is used to handle routing for specific subsets of
an application.
Routers in Express.js help in managing different parts of your
application by grouping routes logically and keeping them separate
from other components. This modular approach makes your
application more manageable and easier to maintain.
Syntax:
express.Router( [options] )

25/02/2025 By Dr. Jaspreet Singh Bajaj


Why Use Routers in Express.js?

Modularity and Organization


Using routers allows you to break down your application into smaller,
manageable chunks. Instead of having all your routes in a single file,
you can divide them into different modules, each handling a specific
part of the application. For instance, you can have separate routers
for user management, product listings, and order processing.

Code Reusability
Routers promote code reusability by allowing you to define
middleware and route handlers that can be reused across different
parts of your application. You can create a router once and mount it
in multiple places if necessary.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Contd…

Middleware Handling
Routers can handle middleware specific to a particular route or group
of routes. This means you can apply middleware to certain routes
without affecting the entire application. Middleware such as
authentication, logging, and input validation can be applied
selectively.
Easier Testing and Debugging
With routers, each part of your application is encapsulated, making it
easier to test and debug. You can test individual routers in isolation,
ensuring that specific routes and their associated middleware work
as expected.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Scalability
As your application grows, managing all routes in a single file can
become unwieldy. Routers allow you to scale your application by
keeping route definitions separate and organized, making it easier to
add new features without disrupting the existing codebase.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Installation Steps

Step 1: Make a folder structure for the project.


mkdir myapp
Step 2: Navigate to project directory
cd myapp
Step 3: Initialize the NodeJs project inside the myapp folder.
npm init -y
Step 4: Install the necessary packages/libraries in your project using
the following commands.
npm install express

25/02/2025 By Dr. Jaspreet Singh Bajaj


Project Structure:

25/02/2025 By Dr. Jaspreet Singh Bajaj


Save it as home.js
// Importing express module
const express = require("express")
// Creating express router
const router = express.Router()
// Handling request using router
router.get("/home", (req,res,next) => {
res.send("This is the homepage request")
})
// Exporting router
module.exports = router

25/02/2025 By Dr. Jaspreet Singh Bajaj


Save it as login.js

// Importing the module


const express = require("express")
// Creating express Router
const router = express.Router()
// Handling login request
router.get("/login", (req,res,next) => {
res.send("This is the login request")
})
module.exports = router

25/02/2025 By Dr. Jaspreet Singh Bajaj


Save it as index.js
const express = require("express")
// Importing all the routes
const homeroute = require("./routes/Home.js")
const loginroute = require("./routes/login")
// Creating express server
const app = express()
// Handling routes request
app.use("/", homeroute)
app.use("/", loginroute)
// Server setup
app.listen((3000), () => {
console.log("Server is Running") })
25/02/2025 By Dr. Jaspreet Singh Bajaj
Step to run the application: Run the index.js using the following
command

node index.js
Output: We will see the following output on the terminal screen.

Server is Running
Now go to http://localhost:3000/login and
http://localhost:3000/home, we will see the output on the browser
screen.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Introduction to middleware

Express serves as a routing and Middleware


framework for handling the different routing of the
webpage and it works between the request and
response cycle.
Middleware gets executed after the server receives the
request and before the controller actions send the
response. Middleware has and access to the request
object, responses object, and next, it can process the
request before the server sends a response. An
Express-based application is a series of middleware
function calls.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Middleware is a request handler that allows you to
intercept and manipulate requests and responses
before they reach route handlers. They are the
functions that are invoked by the Express.js routing
layer.

25/02/2025 By Dr. Jaspreet Singh Bajaj


It is a flexible tool that helps in adding functionalities
like logging, authentication, error handling, and more to
Express applications.
The basic syntax for the middleware functions is:

app.get(path, (req, res, next) => {}, (req, res) => {})
Middleware functions take 3 arguments: the request object, the
response object, and the next function in the application’s request-
response cycle, i.e., two objects and one function.

25/02/2025 By Dr. Jaspreet Singh Bajaj


• Middleware functions execute and usually add
information to the request or response objects. They
are also capable of ending the cycle by sending a
response when some condition is satisfied. If they
don’t send the response when they are done, they
start the execution of the next function in the stack.
This triggers calling the 3rd argument, next().
• The middle part (req,res,next)=>{} is the
middleware function. Here we generally perform the
actions required before the user is allowed to view the
webpage or call the data and many other functions.
So let us create our own middleware and see its uses.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Nodemon

The nodemon npm Module is a module that develop


node.js based applications by automatically restarting
the node application when file changes in the directory
are detected. Nodemon does not require any change in
the original code and method of development.

Advantages of Using nodemon Module:


1.It is easy to use and easy to get started.
2.It does not affect the original code and no instance
require to call it.
3.It help to reduce the time of typing the default syntax
node <file name> for execution again and again.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Using Middleware in Express

Step 1: Go to your project directory and enter the following


command to create a NodeJs project. Make sure that NodeJs is
installed in your machine.
npm init -y
Step 2: Install two dependencies using the following command.
npm install express nodemon
Step 3: In the scripts section of the package.json file, add the
following code line.
"start": "nodemon index.js",
Step 4: Create an index.js file in the directory. Make sure that it is not
inside any subdirectories of the directory you are working in.

25/02/2025 By Dr. Jaspreet Singh Bajaj


The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.18.2",
}

25/02/2025 By Dr. Jaspreet Singh Bajaj


Step 5: Now we will set up our express app and send a response to
our server. Here is the code for the index.js file.
const express = require("express");
const app = express();
const port = process.env.port || 5500;
app.get("/", (req, res) => { res.send(`<div>
<h2>Welcome to Chitkara</h2>
<h5>Tutorial on Middleware</h5>
</div>`); });
app.listen(port, () => {
console.log(`Listening to port ${port}`);
});
25/02/2025 By Dr. Jaspreet Singh Bajaj
Step to run the application: Run the code by entering the following
command on the terminal.
npm start

Question: Creating a Middleware in the app.get()


function.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Types of Middleware

Express JS offers different types of middleware and you should


choose the middleware on the basis of functionality required.
Application-level middleware: Bound to the entire application using
app.use() or app.METHOD() and executes for all routes.
Router-level middleware: Associated with specific routes using
router.use() or router.METHOD() and executes for routes defined
within that router.
Error-handling middleware: Handles errors during the request-
response cycle. Defined with four parameters (err, req, res, next).
Built-in middleware: Provided by Express (e.g., express.static,
express.json, etc.).
Third-party middleware: Developed by external packages (e.g., body-
parser, morgan, postman etc.).
25/02/2025 By Dr. Jaspreet Singh Bajaj
Difference between Application and
Router level Middleware
Application-level Router-Level
Feature Middleware Middleware

Applies globally to the


Where it’s applied ? whole app. Applied to a router.

App.use() or app.METHO Router.use() or router.M


How it’s applied ? D(). ETHOD()

Affects all routes and Only affects routes


Paths affected
paths. defined in router.

Logging, authentication, Authentication for parts


Common uses error handling of app validation.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Middleware lifecycle/chaining

• Middleware can be chained from one to another,


Hence creating a chain of functions that are executed
in order. The last function sends the response back to
the browser. So, before sending the response back to
the browser the different middleware processes the
request.
• The next() function in the express is responsible for
calling the next middleware function if there is one.

Modified requests will be available to each


middleware via the next function

25/02/2025 By Dr. Jaspreet Singh Bajaj


25/02/2025 By Dr. Jaspreet Singh Bajaj
In the above case, the incoming request is modified
and various operations are performed using several
middlewares, and middleware is chained using
the next function. The router sends the response back
to the browser.
Advantages of using Middleware
• Middleware can process request objects multiple
times before the server works for that request.
• Middleware can be used to add logging and
authentication functionality.
• Middleware improves client-side rendering
performance.
• Middleware is used for setting some specific HTTP
headers.
25/02/2025 By Dr. Jaspreet Singh Bajaj
Body-parser Middleware
Body-parser is the Node.js body-parsing middleware. It
is responsible for parsing the incoming request bodies
in a middleware before you handle it. It’s commonly
used in web applications built with Express.js to handle
form submissions, JSON payloads, and other types of
request bodies.

25/02/2025 By Dr. Jaspreet Singh Bajaj


Installing Body parser module
Step 1: First init the node app using the below command.
npm init -y
Step 2: You can visit the link to Install the body-parser module. You
can install this package by using this command.
npm install body-parser express ejs

Step 3: After installing body-parser you can check your body-parser


version in the command prompt using the command.
npm version body-parser

25/02/2025 By Dr. Jaspreet Singh Bajaj


The updated dependencies in your package.json file will look like this:

"dependencies":{
"body-parser": "^1.20.2",
"express": "^4.18.2",
"ejs": "^3.1.9"
}

25/02/2025 By Dr. Jaspreet Singh Bajaj


// Save as main.html <input type="submit"
<!DOCTYPE html> value="Submit
Form">
<html>
</pre>
<head> </form>
<title>Body-Parser Module Demo</title> </body>
</head> </html>
<body>
<h1>Demo Form</h1>
<form action="saveData" method="POST">
<pre>
Enter your Email : <input type="text"
name="email"> <br>
25/02/2025 By Dr. Jaspreet Singh Bajaj
//Save it as index.js
const bodyparser = require('body-parser')
const express = require("express")
const path = require('path') app.post('/saveData', (req, res)
const app = express() => {
console.log("Using Body-
let PORT = process.env.port || 3000
parser: ", req.body.email)
// View Engine Setup })
app.set("views", path.join(__dirname))
app.set("view engine", "ejs") app.listen(PORT, function
// Body-parser middleware (error) {
app.use(bodyparser.urlencoded({ extended: true })) if (error) throw error
console.log("Server created
app.use(bodyparser.json())
Successfully on PORT", PORT)
app.get("/", function (req, res) { })
res.render("SampleForm")
});
25/02/2025 By Dr. Jaspreet Singh Bajaj
Run the index.js file using the below command:
node index.js
Now Open the browser and type the below URL and you will see the
Demo Form as shown below:
http://localhost:3000/

25/02/2025 By Dr. Jaspreet Singh Bajaj


Now submit the form and then you will see the
following output:

25/02/2025 By Dr. Jaspreet Singh Bajaj


Serving static webpages

To serve static files such as images, CSS files, and JavaScript files, use
the express.static built-in middleware function in Express.
The function signature is:
express.static(root, [options])
The root argument specifies the root directory from which to serve
static assets. For more information on the options argument, see
express.static.
For example, use the following code to serve images, CSS files, and
JavaScript files in a directory named public:
app.use(express.static('public'))
Now, you can load the files that are in the public directory:

25/02/2025 By Dr. Jaspreet Singh Bajaj


http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/hello.html
Express looks up the files relative to the static directory, so the name
of the static directory is not part of the URL.
To use multiple static assets directories, call the express.static
middleware function multiple times:
app.use(express.static('public'))
app.use(express.static('files'))
Express looks up the files in the order in which you set the static
directories with the express.static middleware function.

25/02/2025 By Dr. Jaspreet Singh Bajaj


To create a virtual path prefix (where the path does not actually exist
in the file system) for files that are served by the express.static
function, specify a mount path for the static directory, as shown
below:
app.use('/static', express.static('public'))
Now, you can load the files that are in the public directory from the
/static path prefix.
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

25/02/2025 By Dr. Jaspreet Singh Bajaj


However, the path that you provide to the express.static function is
relative to the directory from where you launch your node process. If
you run the express app from another directory, it’s safer to use the
absolute path of the directory that you want to serve:

const path = require('path')


app.use('/static', express.static(path.join(__dirname, 'public')))

25/02/2025 By Dr. Jaspreet Singh Bajaj


Introduction to Blocking
It refers to the blocking of further operation until the current
operation finishes. Blocking methods are executed synchronously.
Synchronously means that the program is executed line by line. The
program waits until the called function or the operation returns.

Synchronous (Blocking)
–Line by line Execution

Example: Following example uses the readFileSync() function to read


files and demonstrate Blocking in Node.js

25/02/2025 By Dr. Jaspreet Singh Bajaj


Example
const fs = require('fs');
const filepath = 'text.txt';
// Reads a file in a synchronous and blocking way
const data = fs.readFileSync(filepath, {encoding: 'utf8'});
// Prints the content of file
console.log(data);
// This section calculates the sum
of numbers from 1 to 10
let sum = 0;
for(let i=1; i<=10; i++){
sum = sum + i; }
// Prints the sum
console.log('Sum: ', sum);
25/02/2025 By Dr. Jaspreet Singh Bajaj
Introduction to Non-Blocking
It refers to the program that does not block the
execution of further operations. Non-Blocking methods
are executed asynchronously. Asynchronously means
that the program may not necessarily execute line by
line. The program calls the function and move to the
next operation and does not wait for it to return.

• Non- synchronous (Non-blocking)


– Line by line Execution , non granted
– Call back function will be fired

Example: Following example uses the readFile()


function to read files and demonstrate Non-Blocking in
Node
25/02/2025 By Dr. Jaspreet Singh Bajaj
const fs = require('fs');
const filepath = 'text.txt';
// Reads a file in a asynchronous and non-blocking way
fs.readFile(filepath, {encoding: 'utf8'}, (err, data) => {
// Prints the content of file
console.log(data); });
// This section calculates the
sum of numbers from 1 to 10
let sum = 0;
for(let i=1; i<=10; i++){
sum = sum + i; }
// Prints the sum
console.log('Sum: ', sum);
25/02/2025 By Dr. Jaspreet Singh Bajaj
Difference between Blocking vs Non-Blocking

1. Execution Flow:
• Blocking: Executes tasks sequentially, waiting for each to complete
before moving to the next.
• Non-Blocking: Initiates tasks and moves to the next without
waiting, often using callbacks or promises to handle completion.

25/02/2025 By Dr. Jaspreet Singh Bajaj


2. Performance:

• Blocking: Can lead to performance bottlenecks, especially in I/O-


bound operations.
• Non-Blocking: More efficient for I/O operations, allowing other
tasks to run concurrently.

25/02/2025 By Dr. Jaspreet Singh Bajaj

You might also like