0% found this document useful (0 votes)
28 views39 pages

Unit 2

This document provides an introduction to Node.js and Express.js, detailing their functionalities, installation processes, and usage in web application development. It covers Node.js as a runtime environment for JavaScript, its single-threaded event loop architecture, and how to set up a basic Express server. Additionally, it outlines the importance of project structure in Node.js applications and includes steps for creating a RESTful backend using Express.js and Firebase.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views39 pages

Unit 2

This document provides an introduction to Node.js and Express.js, detailing their functionalities, installation processes, and usage in web application development. It covers Node.js as a runtime environment for JavaScript, its single-threaded event loop architecture, and how to set up a basic Express server. Additionally, it outlines the importance of project structure in Node.js applications and includes steps for creating a RESTful backend using Express.js and Firebase.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Shree Uttar Gujarat BCA College Unit-2 [FFWD]

Unit-2: Introduction to [Link] and Server-Side Basics with [Link]

What is [Link]?
 [Link] is runtime environment of JavaScript which is built on Chrome’s V8 engine.
 [Link] allows you to run JavaScript on the server.
 [Link] is an open source server environment.
 [Link] runs on various platforms (Windows, Linux, UNIX, Mac OS X, etc.).
 [Link] also provides a rich library of various JavaScript modules to simplify the development of web
applications.
 [Link] was developed by Ryan Dahl in 2009.
 [Link] is not a language or framework.
 [Link] is used to build back-end services like APIs like Web App or Mobile App.
 [Link] = Runtime Environment + JavaScript Library

 How Node works?


 Node accepts the request from the clients and sends the response, while working with the request
[Link] handles them with a single thread.
 To operate I/O operations or requests [Link] use the concept of threads.
 Thread is a sequence of instructions that the server needs to perform.
 It runs parallel on the server to provide the information to multiple clients.
 [Link] is an event loop single-threaded language.
 It can handle concurrent requests (request that are occurring at the same time) with a single
thread without blocking it for one request.

 What Can [Link] Do?


 [Link] can generate dynamic page content.
 [Link] can create, open, read, write, delete, and close files on the server.
 [Link] can add, delete and modify data in your database.
 [Link] eliminates the waiting, and simply continues with the next request.
 [Link] runs single-threaded, non-blocking, asynchronous programming, which is very memory
efficient.

 Who Uses [Link]?


 Netflix, NASA, PayPal, Uber, Walmart, Twitter, Yahoo!, eBay, GoDaddy, Microsoft, Wikipins
LinkedIn.

 Why [Link]?
 [Link] uses asynchronous programming.

By: Pooja Soni 1


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
 Where to Use [Link] (Applications)?
 I/O bound Applications
 Data Streaming Applications
 Data Intensive Real-time Applications (DIRT)
 JSON APIs based Applications
 Single Page Applications

 How [Link] handles a file request?


1. Sends the task to the computer's file system.
2. Ready to handle the next request.
3. When the file system has opened and read the file, the server returns the content to the client.
4. [Link] eliminates the waiting, and simply continues with the next request.

 What is a [Link] File?


• [Link] files contain tasks that will be executed on certain events.
• A typical event is someone trying to access a port on the server.
• [Link] files must be initiated on the server before having any effect.
• [Link] files have extension ".js".

 Downloading [Link]
Step-1: Downloading the [Link] ‘.msi’ installer.

 The first step to install [Link] on windows is to download the installer.


 Visit the official [Link] [Link] and download the .msi file
according to your system environment (32-bit & 64-bit).
 An MSI installer will be downloaded on your system.

Step-2: Running the [Link] installer.


 Now you need to install the [Link] installer on your PC. You need to follow the following
steps for the [Link] to be installed:-
 Double click on the .msi installer.
o The [Link] Setup wizard will open.
 Welcome To [Link] Setup Wizard.
o Select “Next”

By: Pooja Soni 2


Shree Uttar Gujarat BCA College Unit-2 [FFWD]

 After clicking “Next”, End-User License Agreement (EULA) will open.


o Check “I accept the terms in the License Agreement”
o Select “Next”

 Destination Folder
o Set the Destination Folder where you want to install [Link] & Select “Next”

 Custom Setup Select “Next”

By: Pooja Soni 3


Shree Uttar Gujarat BCA College Unit-2 [FFWD]

 Ready to Install [Link].


o Select “Install”

 Authenticate the prompt as an

o “Administrator”

 Installing [Link].

(Do not close or cancel the installer until the install is complete)
 Complete the [Link] Setup Wizard.
o Click “Finish”

By: Pooja Soni 4


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
Step 3: Verify that [Link] was properly installed or not.
 To check that [Link] was completely installed on your system or not, you can run the
following command in your command prompt or Windows Powershell and test it:-
o C:\Users\Admin> node –v

 If [Link] was completely installed on your system, the command prompt will print the version
of the [Link] installed.
Step 4: Updating the Local npm version.
 The final step in [Link] installed is the updating of your local npm -- version (if required) the
package manager that comes bundled with [Link].

[Link]
[Link] is a lightweight [Link] framework that simplifies building web applications and APIs,
offering routing, middleware, and easy database integration. [Link] is a minimal and
flexible [Link] web application framework that provides a list of features for building web and
mobile applications easily. It simplifies the development of server-side applications by offering an
easy-to-use API for routing, middleware, and HTTP utilities.

 Built on [Link] for fast and scalable server-side development.


 Simplifies routing and middleware handling for web applications.
 Supports building REST APIs, real-time applications, and single-page applications.
 Provides a lightweight structure for flexible and efficient server-side development.
Install Express in a Node Project

Before adding Express to your project, ensure that [Link] is installed on your system.

Setting up Express

Here are the steps to set up Express in your [Link] project:

Step 1: Navigate to Your Project Directory

Open your terminal or command prompt and move to your project's root directory

cd path-to-your-porject

By: Pooja Soni 5


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
Step 2: Initialize the NodeJS Project

Set up your project by creating a [Link] file

npm init -y

This command initializes the project with default settings, creating a [Link] file that manages
your project's dependencies and metadata.

Step 3: Install [Link]: Add [Link] to your project

npm install express

This installs the [Link] framework and adds it to the dependencies section of your [Link].

Step 4: Create a Basic Express Server ([Link])


const express = require('express');
const app = express();
const PORT = 3000;

[Link]('/', (req, res) => {


[Link]('Hello, World!');
});
[Link](PORT, () => {
[Link](`Server is listening at [Link]
});

Step 5: Start the Server: Run your server with the following command

node [Link]
2.1.2 Creating a RESTful backend using [Link] + Firebase (Firestore)

Prerequisites
You will need [Link] and npm (Node Package Manager) installed on your system.

Steps

1. Install Required Software

Install [Link]

 Download from: [Link]


 Choose LTS version

Verify installation:
node -v
npm -v
2. Create Project Folder
mkdir express-rest-api
cd express-rest-api
By: Pooja Soni 6
Shree Uttar Gujarat BCA College Unit-2 [FFWD]
3. Initialize Node Project: This creates [Link] (project configuration file):
npm init -y

4. Install Dependencies

1) Express (core framework): npm install express

2) Supporting Middleware: npm install cors dotenv

What is cors and dotenv?

Frontend → Backend (CORS)


Frontend (React / Browser)
|
| request
Browser Security (CORS check)
|
| without cors → BLOCK
| with cors → ALLOW
Backend (Express Server)

Explanation:

 Browser stops request by default


 cors tells browser: “allow this request”

dotenv (Hidden Values Flow)

.env file (hidden)


PORT=5000
DB_PASSWORD=****
|
[Link]
|
Express Server

Explanation:

 Important values stay outside code


 Code safely reads them

cors → allows frontend to talk to backend


dotenv → hides important values (password, port, keys)

3) Development Tool (Auto restart server)

npm install nodemon --save-dev

It watches your files when you save code, it restarts the server automatically.

By: Pooja Soni 7


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
What is Nodemon?
 Definition: Nodemon is a utility that monitors files in your [Link] project and automatically
restarts the server when changes are detected.
 Why it matters:
o Saves time by eliminating manual restarts.
o Ensures you immediately see the effect of code changes.
o Helps maintain a smooth development workflow.

How to Use Nodemon


 Installation:
o Globally: npm install -g nodemon
o Locally (recommended): npm install --save-dev nodemon
 Running your app:
o Without Nodemon: node [Link]
o With Nodemon: nodemon [Link]
 Best practice: Add scripts in [Link]:

"scripts": {
"start": "node [Link]",
"dev": "nodemon [Link]"
}

Then run npm run dev for auto-restarts.


Simple Steps to Use Nodemon:

1. Install Nodemon Globally or Locally:


You can install Nodemon globally so it can be used across all your projects:

npm install -g nodemon

 Alternatively, you can install Nodemon locally within your project:

npm install --save-dev nodemon

By: Pooja Soni 8


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
2. Add a Start Script to [Link]:

 Update your [Link] to add a script that uses Nodemon. If Nodemon is installed locally, you can
refer to it directly within the script.

 Using in [Link]:

{
"name": "your-project-name",
"version": "1.0.0",
"main": "[Link]",
"scripts": {
"start": "node [Link]",
"dev": "nodemon [Link]"
},
"dependencies": {
// your dependencies
},
"devDependencies": {
"nodemon": "^3.1.4"
}
}

Here, "dev": "nodemon [Link]" is the script that will run Nodemon. Replace [Link] with the entry
point of your application.

3. Run Your Application with Nodemon:

Use the script you defined in [Link] to start your application with Nodemon.

nodemon [Link]

Congratulations! Nodemon ran successfully.

By: Pooja Soni 9


Shree Uttar Gujarat BCA College Unit-2 [FFWD]

Folder structure for a Node JS project

 Organizing a Node JS project with well planned folder structure is crucial for readability, scalability,
and maintainability. A clear structure helps in managing code, configurations, modules, and other
assets effectively. In this article, we are going to learn the folder structure of the Node JS project. We
are going to learn all the directories present in the folder structure and files present in the Node JS
project.

Prerequisites
To understand the folder structure for a Node JS project, ensure you have:
 Basic knowledge of Node JS and npm
 A code editor or IDE
 Node JS installed on your machine
Folder Structure Overview:

Node project folder structure

Folder structure contains the files and folders that are present in the directory. There are multiple
files and folders, for example, api, config, models, services, subscribers, [Link], [Link], package-
[Link], [Link], [Link], etc.

Steps to create Folder Structure

Step 1: Open the terminal and go to the path where you want to create the project and create a folder
with your project name.

mkdir folder_name

By: Pooja Soni 10


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
Step 2: Run the command npm init to initialized the node project. This will create the [Link]
file
npm init
Step 3: Install the dependencies like express, nodemon etc. This will create [Link] file and
node_modules folder.

npm i express nodemon


Step 4: Run the command git-init to initialized the git in the project. This will add .gitignore file.

git init
Step 5: Create a file named [Link] which will contain all the info of the project.

touch [Link]
Step 6: Create a file with extension .env which will contain the sensitive information and credentials
of the project.
touch [Link]

Step 7: Create a file named [Link] or [Link] will be the end point to run the application.

touch [Link]
Step 8: Create folder like public and src.

mkdir src

Files and folders details

 Root Directory: The root directory is the main folder in which all the files and folders for that
particular application are present, like the entrpoint file, src folder, public folder, routes, models,
views, and controllers.

 Node Modules: This folder contains the files and folders regarding installed files and
dependencies that are used in this project. All the installation files for dependencies are stored in
node modules.

 Public: This folder contains static files that are visible to people, like [Link], [Link], and CDN
links and files.

 Source: This folder present with the name of src which contains all the files required to handle
server like routes, controllers, models, views, etc.

 Routes: This will contains all the routes and endpoints required for the server and also thier
required files like for authentication routes we can create a file and setup routes.

 Controllers: Controllers folder contains the business logic and validations for the input data
received by the client side and performs their business logic and sends it to database controllers,
which contains logical files and folders.

By: Pooja Soni 11


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
 Models: Models contain all the schemas of the database, like which kind of input will be received
from client-side and server-side validations. This will contain all files of validations and data
schemas that should exist.

 [Link]: This file contains the data and details of all dependencies installed in your project.
Express is a kind of dependency that is used to establish a server, so this file will contain all the
details regarding Express, like version and installed.

 [Link]: It is the entrypoint file of the server, which contains the main routes of the application and
server ports from which the server will start listening, as well as the basic routes used in this
application.

 .gitignore: Git ignore is a file that contains files and folders that should not be pushed to the
server. The git ignore file is used to stop pushing files from the server, like node module files,
which should not be pushed to the server because they can easily be installed with
the [Link] file.

 [Link]: This is a markdown file where we write down information about your project, like
all development details about your application.

 env: The env file stands for Environmental Variables of Application. This file contains details about
environment variables like API keys, the private salt of a Payment Gateway, and many other details
that should be kept private.

Why Node JS project structure is important?

 Project structure shows the organization of code and files, and a clean, simple, and decent project
structure shows a clean written code, which helps to debug code, and another developer can easily
read it. Also, while deploying code on the server, it can recognize files easily, which is why
developers are implementing clean, simple, and decent project structures.

2.2 Handling Routes and HTTP Methods


2.2.1 Defining routes using GET, POST, PUT, DELETE
HTTP Methods in RESTful API Development

 There are some of the most crucial HTTP methods that you must know as a developer, to develop
RESTful APIs for your application. RESTful APIs are those that follow the REST (Representational
State Transfer) architectural style. With this being said, let’s continue with the article on the essential
RESTful methods to assist you to have with working on the server side using JavaScript.

5 Essential HTTP Methods in RESTful API Development

1. GET

The GET method is used to 'retrieve' a record or a collection of records from the server. The below
code shows the implementation of the GET method in JavaScript.

Example:
By: Pooja Soni 12
Shree Uttar Gujarat BCA College Unit-2 [FFWD]
1.1. Backend (Node with Express)

// returns the list of students


[Link]('/students', function (req, res) {

[Link](students);

});

Here, the code defines a get() method that is used to retrieve the 'students' (here is an array of
objects) data from the server. It defines a route that listens to the '/students' endpoint. The second
parameter is a callback function that receives 'req'(request) and 'res' (response) objects as
arguments. It uses the '[Link]()' method to send the data to the client.

1.2. Frontend (JavaScript)

const getStudents = async(URL) => {


const response = await fetch(URL);

const data = await [Link]();

[Link](data)
}
getStudents(BASEURL+"/students");

Here, the code defines an async function called 'getStudents()' that makes a GET request to the API
Endpoint (/students) using the fetch function. The fetch function returns a promise that is resolved
with await and the response object is stored in the ‘response’ variable. The json() method is called on
the response to parse the data which again returns a promise that is resolved by await and the data is
stored in the ‘data’ variable. The parsed data(list of students) is then logged into the console.

2. POST

The POST method sends data to create a 'new record' on the server. The below code shows the
implementation of the POST method in JavaScript.

Example:

2.1. Backend (Node with Express)

// add student
[Link]("/students", function (req, res) {
var student = [Link];

[Link](student);

[Link]({ message: "Record Added" });


});

Here, the code defines a post() method that is used to add a new record i.e. 'student' data to the
By: Pooja Soni 13
Shree Uttar Gujarat BCA College Unit-2 [FFWD]
server. It defines a route that listens to the '/students' endpoint. The second parameter is a callback
function that receives 'req'(request) and 'res' (response) objects as arguments. It extracts the data
from the request using '[Link]', and appends it to the existing list using the array push() method.
Finally, it sends the acknowledgment message back to the client in the form of JSON data
using [Link]().

2.2. Frontend (JavaScript)

const addStudent = async (URL, student) => {


const response = await fetch(URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: student,
});
const data = await [Link]();
[Link]([Link]);
};

addStudent(BASEURL + "/students", { id: 3, name: "Pooja" });

Here, the code defines an async function called 'addStudent()' that makes a POST request to the API
Endpoint (/students) with the request body containing the 'student' data. The fetch function
returns a promise which is resolved with await and the response object is stored in
the ‘response’ variable. The json() method is called on the response to parse the data which again
returns a promise that is resolved by await and the data is stored in the ‘data’ variable. The parsed
data (acknowledgment message - Record Added) is then logged into the console.

3. PUT
The PUT method sends data to update an 'existing record' on the server. The below code shows the
implementation of the PUT method in JavaScript.

Example:
3.1. Backend (Node with Express)

[Link]("/students/:id", function (req, res) {


var id = [Link];
var student = [Link];

// updating user with the specific id


for (var i = 0; i < [Link]; i++) {
if (students[i].id == id) {
students[i] = student;
break;
}
}

[Link]({ message: "Record Updated" });


});
By: Pooja Soni 14
Shree Uttar Gujarat BCA College Unit-2 [FFWD]

Here, the code defines a put() method that is used to update an existing record i.e. 'student
with specific id' on the server. It defines a route that listens to the '/students/:id' endpoint. The
':id' here is a URL parameter that is extracted using '[Link]'. The data passed inside the
request body is extracted using '[Link]'. The student's data is traversed to find the student with
the matching id which on found gets the particular record replaced with new data. Finally, it sends
the acknowledgment message back to the client in the form of JSON data using [Link]().

3.2. Frontend (JavaScript)


const updateStudent = async (URL, student) => {
const response = await fetch(URL, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: student,
});

const data = await [Link]();

[Link]([Link]);
};
updateStudent(BASEURL + "/students/3", { id: 3, name: "Pooja Updated" });

Here, the code defines an async function called 'updateStudent()' that makes a PUT request to the
API Endpoint (/students/3) with the request body containing the 'student' data. The fetch function
returns a promise which is resolved with await and the response object is stored in
the ‘response’ variable. The json() method is called on the response to parse the data which again
returns a promise that is resolved by await and the data is stored in the ‘data’ variable. The parsed
data (acknowledgment message - "Record Updated") is then logged into the console.

4. PATCH

Like the PUT method, PATCH is also used to send data to update an 'existing record' on the server.
But the important difference between PUT and PATCH is that PATCH only applies partial
modifications to the record instead of replacing the whole record. The below code shows the
implementation of the PATCH method in JavaScript.

Example:
4.1. Backend (Node with Express)

[Link]("/students/:id", function (req, res) {


var id = [Link];
var student = [Link];

for (var i = 0; i < [Link]; i++) {


if (students[i].id == id) {

// replacing only specific properties

By: Pooja Soni 15


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
for (var key in student) {
students[i][key] = student[key];
}
break;

}
}
[Link]({ message: "Record Updated using patch" });
});

Here, the code defines a patch() method that is used to partially update an existing record
i.e. 'student with specific id' on the server. It defines a route that listens to
the '/students/:id' endpoint. The ':id' here is a URL parameter that is extracted
using '[Link]'. The data passed inside the request body is extracted using '[Link]'. The
student's data is traversed to find the student with the matching id which on found gets the particular
record updated, here instead of updating the entire object only the specific properties on the objects
get updated. Finally, it sends the acknowledgment message back to the client in the form of JSON data
using [Link]().

4.2. Frontend (JavaScript)


// update using patch
const updateStudentPatch = async (URL, student) => {
const response = await fetch(URL, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: student,
});

const data = await [Link]();

[Link](data);
};

updateStudentPatch(BASEURL + "/students/2", { name: "Aarana Updated using Patch" });

Here, the code defines an async function called 'updateStudentPatch()' that makes a PATCH request
to the API Endpoint (/students/2) with the request body containing the specific('name') property
'student' data. The fetch function returns a promise which is resolved with await and the response
object is stored in the ‘response’ variable. The json() method is called on the response to parse the
data which again returns a promise that is resolved by await and the data is stored in the ‘data’
variable. The parsed data (acknowledgment message - 'Record Updated using patch') is then logged
into the console.

5. DELETE

By: Pooja Soni 16


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
The DELETE method is used to delete record(s) from the server. The below code shows the
implementation of the DELETE method in JavaScript.

Example:
5.1. Backend (Node with Express)

[Link]("/students/:id", function (req, res) {


var id = [Link];

for (var i = 0; i < [Link]; i++) {


if (students[i].id == id) {
[Link](i, 1);
break;
}
}

[Link]({ message: "Record Deleted" });


});

Here, the code defines a delete() method that is used to delete an existing record (here 'student
with specific id') on the server. It defines a route that listens to the '/students/:id' endpoint.
The ':id' here is a URL parameter that is extracted using '[Link]'. The student's data
(here Array of students) is traversed to find the student with the matching id which on found gets
deleted using the Array splice() method in javascript. Finally, it sends the acknowledgment message
back to the client in the form of JSON data using [Link]().

5.2. Frontend (JavaScript)

const deleteStudent = async (URL) => {


const response = await fetch(URL, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
});

const data = await [Link]();

[Link](data);
};
deleteStudent(BASEURL + "/students/3");

Here, the code defines an async function called 'deleteStudent()' that makes a PATCH request to the
API Endpoint (/students/3). The fetch function returns a promise which is resolved with await and
the response object is stored in the ‘response’ variable. The json() method is called on the response
to parse the data which again returns a promise that is resolved by await and the data is stored in the
‘data’ variable. The parsed data (acknowledgment message - 'Record Deleted') is then logged into the
console.
Code Files

By: Pooja Soni 17


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
1. Backend Code
// [Link]
var express = require("express");

// database
var students = [
{ id: 1, name: "Drashti" },
{ id: 2, name: "Aarana" },
];

var app = express();


[Link]([Link]());

// returns the list of students


[Link]("/students", function (req, res) {
[Link](students);
});

// add student
[Link]("/students", function (req, res) {
var student = [Link];
[Link](student);
[Link]({ message: "Record Added" });
});

// update student
[Link]("/students/:id", function (req, res) {
var id = [Link];
var student = [Link];
for (var i = 0; i < [Link]; i++) {
if (students[i].id == id) {
students[i] = student;
break;
}
}
[Link]({ message: "Record Updated" });
});

// update using patch


[Link]("/students/:id", function (req, res) {
var id = [Link];
var student = [Link];
for (var i = 0; i < [Link]; i++) {
if (students[i].id == id) {
for (var key in student) {
students[i][key] = student[key];
}
break;
}
}
By: Pooja Soni 18
Shree Uttar Gujarat BCA College Unit-2 [FFWD]
[Link]({ message: "Record Updated using patch" });
});

// delete student
[Link]("/students/:id", function (req, res) {
var id = [Link];
for (var i = 0; i < [Link]; i++) {
if (students[i].id == id) {
[Link](i, 1);
break;
}
}
[Link]({ message: "Record Deleted" });
});

[Link](5000, () => {
[Link]("Server started on port 5000");
});

2. Frontend Code

var BASEURL = "[Link]

const getStudents = async (URL) => {


const response = await fetch(URL);

const data = await [Link]();


[Link](data);
};

const addStudent = async (URL, student) => {


const response = await fetch(URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: student,
});

const data = await [Link]();

[Link](data);
};

const updateStudent = async (URL, student) => {


const response = await fetch(URL, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
By: Pooja Soni 19
Shree Uttar Gujarat BCA College Unit-2 [FFWD]
body: student,
});

const data = await [Link]();

[Link](data);
};

// update using patch


const updateStudentPatch = async (URL, student) => {
const response = await fetch(URL, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: student,
});

const data = await [Link]();

[Link](data);
};

// delete student
const deleteStudent = async (URL) => {
const response = await fetch(URL, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
});

const data = await [Link]();


[Link](data);
};

// Function Calls
getStudents(BASEURL + "/students");

addStudent(BASEURL + "/students", { id: 3, name: "Pooja" });

updateStudent(BASEURL + "/students/3", { id: 3, name: "Pooja Updated" });

updateStudentPatch(BASEURL + "/students/2", {
name: "Aarana Updated using Patch",
});

deleteStudent(BASEURL + "/students/3");
2.2.2 Sending responses and working with route/query parameters

By: Pooja Soni 20


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
Route parameters in [Link] are dynamic URL segments defined with a colon (:) and accessed via
[Link], enabling efficient handling of variable data such as IDs in RESTful routes.
Syntax:
[Link]('/users/:id', (req, res) => {
const userId = [Link];
[Link](`User ID is: ${userId}`);
});
In the above syntax:
 :id: defines the route parameter.
 [Link]: retrieves the value from the URL.
Here are the different ways to handle route parameters in [Link] include basic, optional, and
multiple parameters.

1. Basic Route Parameter Handling


Basic route parameters capture dynamic values directly from the URL. They are defined with a colon (:)
in the route path and accessed via [Link] inside the route handler.
Now let's understand this with the help of example:
const express = require('express');
const app = express();
const PORT = 3000;

[Link]('/users/:userId', (req, res) => {


const userId = [Link];
[Link](`<h1>User Profile</h1><p>User ID: ${userId}</p>`);
});

[Link](PORT, () => {
[Link](`Server is running at [Link]
});
Output: Accessing [Link] will display

Basic Route Parameter Handling

By: Pooja Soni 21


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
In this example:
 /users/:userId: :userId is a route parameter that captures the value after /users/.
 [Link]: Access the captured value and use it in the route handler for further logic.

2. Optional Route Parameters


Optional route parameters allow a URL segment to be omitted without breaking the route. They are
defined by adding a question mark (?) after the parameter name. If the parameter is not provided, a
default value can be used.
Now let's understand this with the help of example:
const express = require('express');
const app = express();
const PORT = 3000;

[Link]('/products/:productId?', (req, res) => {


const productId = [Link] || 'default';
[Link](`<h1>Product Page</h1><p>Product ID: ${productId}</p>`);
});

[Link](PORT, () => {
[Link](`Server is running at [Link]
});

Output: Accessing [Link] will display

Route Parameters
In this example:
 /products/:productId?: :productId is optional, meaning the route will match with or without the
productId.
 [Link] || 'default': If no productId is provided, 'default' will be used instead.

Accessing [Link] will display


Product Page
Product ID: default

By: Pooja Soni 22


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
3. Multiple Route Parameters

Express allows you to define multiple route parameters in a single route. You can capture several
dynamic values from the URL by adding multiple colon-prefixed parameters.

Now let's understand this with the help of example:


const express = require('express');
const app = express();
const PORT = 3000;

[Link]('/posts/:category/:postId', (req, res) => {


const category = [Link];
const postId = [Link];
[Link](`<h1>Post</h1><p>Category: ${category}, Post ID: ${postId}</p>`);
});

[Link](PORT, () => {
[Link](`Server is running at [Link]
});

Output Accessing [Link] will display

Multiple Route Parameters


In this example:
 /posts/:category/:postId: The route captures both category and postId from the URL.
 [Link] and [Link]: Access the captured values for use in the handler.

What is a Controller?

A controller in [Link] is a JavaScript function (or a collection of functions) that manages how your
application responds to incoming HTTP requests. It acts as a middle layer between the route
definitions and the actual business logic or database operations. In simpler terms, while the route
decides what URL or method to listen to, controllers decide how to process the request and what
response to send back. This separation helps keep your code clean, organized, and easier to manage.

Why Use Controllers?


As your [Link] application grows, managing all the logic directly inside your files can quickly
become messy and hard to maintain. This is where controllers come into play. Controllers help you
separate the routing logic from the business logic, making your code cleaner, more organized, and

By: Pooja Soni 23


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
easier to manage. By using controllers, you can structure your project in a modular way, which
improves readability, promotes reusability, and allows your application to scale efficiently.
 Separation of Concerns: It keeps route definitions clean by moving logic to separate files.
 Modularity: It makes your code reusable and testable.
 Maintainability: It is easier to update or refactor logic when it's not tightly coupled with routes.
 Scalability: It is easier to manage as the application grows.

Create a Basic Controller

To understand how a controller works in [Link], let's walk through creating one from scratch.
This section will show you how to define a simple controller, connect it to routes, and organize its
files for better structure. By following these steps, you will learn the foundations of separating
concerns and writing clean, modular code in your Express application.

Step 1: Define a Controller

Define a file named [Link]


[Link] =(req,res)=>{
const users=[{id:1,name:'Abu'},{id:2,name:'Babu'}, {id:3, name:'dabbu'}];
[Link](users);
};
[Link]=(req,res)=>{
const userID= [Link];
const user={id: userID, name:'Alice'};
[Link](user);
};

Step 2: Connect Controllers to routes

create a file named [Link]


const express=require('express');
const router=[Link]();
const userController=require('../controllers/')
[Link]('/',(req,res)=>{
[Link]('/users', [Link]);
[Link]('/users/:id', [Link]);
[Link]=router;
})

Step 3: Use Routes in the main app

const express= require('express');


const app= express();
const userRoutes= require('./routes/userRoutes');
[Link]('/api','userRoutes');
const PORT= 3000;
[Link](PORT,()=>{
[Link](`server is running on port ${PORT}`);
});

By: Pooja Soni 24


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
2.3 Middleware and API Basics

2.3.1 Understanding middleware in Express


Middleware in Express refers to functions that process requests before reaching the route
handlers. These functions can modify the request and response objects, end the request -response
cycle, or call the next middleware function. Middleware functions are executed in the order they
are defined. They can perform tasks like authentication, logging, or error handling. Middleware
helps separate concerns and manage complex routes efficiently.

Syntax
[Link]((req, res, next) => {
[Link]('Middleware executed');
next();
});
 (req, res, next) => {}: This is the middleware function where you can perform actions on the
request and response objects before the final handler is executed.
 next(): This function is called to pass control to the next middleware in the stack if the current
one doesn't end the request-response cycle.

What Middleware Does in [Link]?

Middleware functions in [Link] can perform several important tasks:


1. Execute Code: Middleware can run any code when a request is received.
2. Modify Request and Response: Middleware can modify both the request (req) and response
(res) objects.
3. End the Request-Response Cycle: Middleware can send a response to the client, ending the
cycle.
4. Call the Next Middleware: Middleware can call next() to pass control to the next function in
the middleware stack.

How Middleware Works in [Link]?


In [Link], middleware functions are executed sequentially in the order they are added to the
application.
1. Request arrives at the server.
2. Middleware functions are applied to the request, one by one.
3. Each middleware can either:
 Send a response and end the request-response cycle.
By: Pooja Soni 25
Shree Uttar Gujarat BCA College Unit-2 [FFWD]
 Call next() to pass control to the next middleware.
4. If no middleware ends the cycle, the route handler is reached, and a final response is sent.

Types of Middleware

ExpressJS offers different types of middleware and you should choose the middleware based on
functionality required.

1. Application-level Middleware

Application-level middleware is bound to the entire Express application using [Link]() or


[Link](). It executes for all routes in the application, regardless of the specific path or
HTTP method.
This type of middleware is commonly used for tasks like logging, body parsing, authentication
checks, or setting headers for every incoming request.
[Link]([Link]()); // Parses JSON data for every incoming request
[Link]((req, res, next) => {
[Link]('Request received:', [Link], [Link]);
next();
});

2. Router-level Middleware

Router-level middleware is applied to a specific router instance using [Link]() or


[Link](). It only applies to routes defined within that particular router, making it perfect
for modular applications where middleware is only relevant to specific groups of routes.
This type of middleware is often used to group related routes (e.g., all routes related to
authentication or user management) and apply middleware logic to them.
const router = [Link]();

// Apply middleware to only this router's routes


[Link]((req, res, next) => {
[Link]('Router-specific middleware');
next();
});

[Link]('/dashboard', (req, res) => {


[Link]('Dashboard Page');
});

[Link]('/user', router); // The middleware applies only to routes under "/user"

3. Error-handling Middleware

Error-handling middleware is a special type of middleware used to catch and respond to errors
during the request-response cycle. It is defined with four parameters: err, req, res, next.
By: Pooja Soni 26
Shree Uttar Gujarat BCA College Unit-2 [FFWD]
This middleware is essential for sending a consistent error response and avoiding unhandled
exceptions that might crash the server.
[Link]((err, req, res, next) => {
[Link]([Link]); // Log the error stack
[Link](500).send('Something went wrong!');
});

4. Built-in Middleware

Express provides built-in middleware to help with common tasks, like serving static files or
parsing data.
For example, [Link]() serves files like images, and [Link]() helps parse incoming
JSON data.
[Link]([Link]('public')); // Serves static files from the "public" folder
[Link]([Link]()); // Parses JSON payloads in incoming requests

5. Third-party Middleware

Third-party middleware is developed by external developers and packaged as npm modules.


These middleware packages add additional functionality to your application, such as request
logging, security features, or data validation.
For example, the morgan middleware logs HTTP requests, and body-parser helps parse incoming
request bodies for easier handling of form data.
const morgan = require('morgan');
[Link](morgan('dev')); // Logs HTTP requests using the "dev" format

const bodyParser = require('body-parser');


[Link]([Link]({ extended: true })); // Parses URL-encoded bodies

Steps to Implement Middleware in Express

Step 1: Initialize the [Link] Project


npm init -y

Step 2: Install the required dependencies.


npm install express

Step 3: Set Up the Express Application

// Filename: [Link]
const express = require('express');
const app = express();
const port = [Link] || 3000;

By: Pooja Soni 27


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
[Link]('/', (req, res) => {
[Link]('<div><h2>Welcome to SUGC</h2><h5>Example on Middleware</h5></div>');
});

[Link](port, () => {
[Link](`Listening on port ${port}`);
});

Step 4: Start the Application:

node [Link]
Output:
When you navigate to [Link] you will see:
Welcome to SUGCExample on Middleware
Middleware 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

const express = require('express');


const app = express();

// Middleware 1: Log request method and URL


[Link]((req, res, next) => {
[Link](`${[Link]} request to ${[Link]}`);
next();
});

// Middleware 2: Add a custom header


[Link]((req, res, next) => {
[Link]('X-Custom-Header', 'Middleware Chaining Example');
By: Pooja Soni 28
Shree Uttar Gujarat BCA College Unit-2 [FFWD]
next();
});

// Route handler
[Link]('/', (req, res) => {
[Link]('Hello, World!');
});

[Link](3000, () => {
[Link]('Server is running on port 3000');
});
 Middleware 1: Logs the HTTP method and URL of the incoming request.
 Middleware 2: Sets a custom header X-Custom-Header in the response.
 Route Handler: Sends a "Hello, World!" message as the response.

Output
When a client makes a GET request to [Link] the server responds with:
Hello, World!
Advantages of using Middleware

 Modularity: Breaks down complex tasks into smaller, manageable functions.


 Reusability: Middleware functions can be reused across different routes or applications.
 Maintainability: Organizes code logically, making it easier to manage and update.
 Error Handling: Centralizes error handling, improving the application's robustness.
 Performance Optimization: Allows for tasks like caching, compression, and security checks to
be handled efficiently.

How to create custom middleware in express?

 [Link] is the most powerful framework of the [Link]. [Link] is a routing and Middleware
framework for handling the different routing of the webpage, and it works between the request and
response cycle. [Link] use different kinds of middleware functions in order to complete
the different requests made by the client for e.g. client can make get, put, post, and
delete requests these requests can easily handle by these middleware functions.

Working of the middleware functions:

By: Pooja Soni 29


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
Custom Middlewares:

We can create multiple Custom middleware using [Link] according to the routing of the request
and also forward the request to the next middleware.

Syntax:
app.<Middlewaretype>(path,(req,res,next))

Parameters: Custom Middleware takes the following two parameters:


 path: The path or path pattern or in regular expression by which particular Middleware will be
called.
 callback: The second parameter is the callback function that takes three parameters request,
response, and next() function as an argument.

Built-in Middleware Functions in [Link]

 [Link] is a [Link] framework used to develop the backend of web applications. While you can
create custom middleware in [Link] using JavaScript, [Link] also provides several built -in
middleware functions for use in Express applications. Middleware are functions that are executed
when called and then pass control to the next middleware function using the next() function. They act
as an intermediary layer.

1) Built-in Middleware in Express

1. [Link]() (Body Parser): Used to parse JSON request bodies.

[Link]([Link]());
Example:
[Link]("/api/student", (req, res) => {
[Link]([Link]); // JSON data
[Link]("Student Added");
});

2. [Link](): Used to parse form data

[Link]([Link]({ extended: true }));

3. [Link]() (Static Files): Used to serve static files (HTML, CSS, images)

Folder structure:
public/
├── [Link]
├── [Link]
[Link]([Link]("public"));

Access in browser: [Link]

By: Pooja Soni 30


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
2) External Middleware (body-parser – Older Method)

npm install body-parser

const bodyParser = require("body-parser");


[Link]([Link]());
[Link]([Link]({ extended: true }));

Note: [Link]() is preferred now.

3) Custom Middleware (Very Important)

Example 1: Logger Middleware

middleware/[Link]

const logger = (req, res, next) => {


[Link](`${[Link]} ${[Link]}`);
next(); // move to next middleware
};
[Link] = logger;

Use it:
const logger = require("./middleware/logger");
[Link](logger);

Example 2: Authentication Middleware

const auth = (req, res, next) => {


const token = [Link];
if (!token) {
return [Link](401).json({ message: "Unauthorized" });
}
next();
};

Use for protected routes:


[Link]("/api/marks", auth, (req, res) => {
[Link]({ marks: 85 });
});

Example 3: Validation Middleware

const validateStudent = (req, res, next) => {


const { name, age } = [Link];
if (!name || !age) {
return [Link](400).json({ message: "Invalid data" });
}
next();
};

By: Pooja Soni 31


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
Use: [Link]("/api/student", validateStudent, [Link]);

4) Application-level vs Route-level Middleware

Application-level

[Link](logger);

Runs for all routes

Route-level

[Link]("/add", validateStudent, addStudent);

Runs for specific routes

5) Error-Handling Middleware: Special middleware with 4 parameters

[Link]((err, req, res, next) => {


[Link](500).json({ error: [Link] });
});

2.3.3 Introduction to CORS and environment variables


Cross Origin Resource Sharing (CORS)

 Cross-Origin Resource Sharing (CORS) is a browser security mechanism that controls how a web
application running on one origin (domain, protocol, or port) can request resources from a different
origin. By default, browsers block such cross-origin requests to prevent unauthorized access to
sensitive data. CORS provides a controlled way to enable intentional sharing of resources with trusted
third-party domains through specific HTTP headers.
function httpGetAction(urlLink) {
var xmlHttp = new XMLHttpRequest();
[Link]("GET", urlLink, false);
[Link]();
return [Link];
}

It creates a new XMLHttpRequest object.

 Opens a GET request to the given URL.


 The false means synchronous request: The browser will freeze/lock until the response comes
back.
 Sends the request.
 Returns the response text.

This JavaScript function makes an HTTP GET request to the provided URL (urlLink) and returns the
response text from the resource.

By: Pooja Soni 32


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
How CORS Works

Given below the step by step working of CORS:

What is CORS?
CORS is a security feature implemented by web browsers to control how web pages can request
resources from a different domain than the one that served the web page. This is crucial for preventing
malicious websites from accessing sensitive data from another site.

Why is CORS Important?


CORS allows servers to specify who can access their resources and how they can be accessed. Without
CORS, websites would be unable to interact with APIs or resources on different domains, severely
limiting the functionality of modern web applications.

How CORS Works


When a web page makes a request to a different domain (a cross-origin request), the browser sends an
HTTP request with an Origin header. The server then responds with specific CORS headers to indicate
whether the request is allowed. Here are the main headers involved:

 Access-Control-Allow-Origin: Specifies which origins are permitted to access the resource.


 Access-Control-Allow-Methods: Indicates the HTTP methods allowed for the resource.
 Access-Control-Allow-Headers: Lists the headers that can be used during the actual request.
Simple Request vs. Preflight Request
Simple Request
A simple request is one that meets certain criteria, such as using one of the GET, POST, or HEAD
methods without custom headers. For these requests, the server responds directly with the appropriate
CORS headers.

By: Pooja Soni 33


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
Preflight Request
For more complex requests (e.g., those that use methods other than GET/POST or include custom
headers), the browser first sends an OPTIONS request to the server. This is known as a preflight
request, and it checks whether the actual request is safe to send.

Example: Setting Up CORS in a [Link] Express Server


Let's walk through an example to see how CORS is implemented in a [Link] Express server.

Step 1: Set Up Your [Link] Project


First, create a new [Link] project and install the necessary dependencies:

mkdir cors-example
cd cors-example
npm init -y
npm install express cors
Step 2: Create the Server
Create a new file named [Link] and add the following code:

const express = require('express');


const cors = require('cors');
const app = express();

// Enable CORS for all routes


[Link](cors());

[Link]('/data', (req, res) => {


[Link]({ message: 'Hello, CORS!' });
});

const PORT = [Link] || 3000;


[Link](PORT, () => {
[Link](`Server is running on port ${PORT}`);
});
In this example, we use the cors middleware to enable CORS for all routes. This allows any domain to
access the /data endpoint.

Step 3: Test the CORS Configuration


To test the CORS configuration, create an HTML file ([Link]) with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CORS Test</title>
</head>
<body>
<h1>Testing CORS</h1>

By: Pooja Soni 34


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
<button id="fetchData">Fetch Data</button>
<div id="result"></div>

<script>
[Link]('fetchData').addEventListener('click', () => {
fetch('[Link]
.then(response => [Link]())
.then(data => {
[Link]('result').textContent = [Link];
})
.catch(error => {
[Link]('Error:', error);
});
});
</script>
</body>
</html>
Open [Link] in your browser and click the "Fetch Data" button. You should see the message "Hello,
CORS!" displayed on the page.

Routing in [Link]

 Routing in [Link] is the process of mapping incoming HTTP requests (defined by method and
URL) to specific handler functions. It enables developers to configure endpoints for various paths and
operations, such as rendering views, processing form data, or performing CRUD actions on resources.
Syntax:
[Link](PATH, HANDLER);
In the above syntax:

 app: Represents an instance of an Express application.

 METHOD: Represents an HTTP method like GET, POST, PUT, and DELETE.
 PATH: Defines the endpoint (route) where the request will be handled.
 HANDLER: A function that executes when the route is accessed.
How Routing Work in [Link]?

Routing in [Link] follows a simple flow to handle client requests:

 HTTP Request: Shows the incoming request with method and path (e.g., GET /users).
 Route Matching: Lists all defined routes and shows which route matches the request (green
check) and which don’t (red cross).
 Handler Execution: Indicates that the matching route’s handler function is executed (req, res).
 Sending Response: Shows how the server sends a response back to the client using methods like
[Link](), [Link](), or [Link]().

By: Pooja Soni 35


Shree Uttar Gujarat BCA College Unit-2 [FFWD]

Now let's understand this with the help of example:


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

[Link]('/', (req, res) => {


[Link]('Welcome to Express Routing!');
});

[Link](3000, () => {
[Link]('Server is running on port 3000');
});

Output

In this example

 express is imported and an app instance is created.


 [Link]('/', ...) defines a route for GET requests to the root URL / and sends a response “Welcome to
Express Routing!”.
 [Link](3000, ...) starts the server on port 3000 and logs a message when it’s running.

Types of Routes

Here are the different types of routes

1. Basic Routes in ExpressJS

Basic routing involves defining a URL and specifying an HTTP method.

[Link]('/home', (req, res) => {


[Link]('Welcome to the Home Page!');
});
By: Pooja Soni 36
Shree Uttar Gujarat BCA College Unit-2 [FFWD]
[Link]('/submit', (req, res) => {
[Link]('Form Submitted Successfully!');
});
 /home handles GET requests.
 /submit handles POST requests.

2. Route Parameters in ExpressJS

Route parameters allow capturing dynamic values from URLs, making routes flexible and reusable.
[Link]('/users/:userId', (req, res) => {
[Link](`User ID: ${[Link]}`);
});
 :userId is a route parameter.
 [Link] extracts the value.

3. Optional and Multiple Route Parameters

Express allows defining optional parameters and multiple parameters in a single route.
[Link]('/products/:productId?', (req, res) => {
[Link](`Product ID: ${[Link] || 'No product selected'}`);
});
 /products/123 → Product ID: 123
 /products/ → No product selected

4. Multiple Route Parameters

[Link]('/posts/:category/:postId', (req, res) => {


[Link](`Category: ${[Link]}, Post ID: ${[Link]}`);
});
 /posts/tech/456 → Category: tech, Post ID: 456

5. Query Parameters in ExpressJS

Query parameters are used for filtering or modifying requests. They appear after the ? symbol in
URLs.
[Link]('/search', (req, res) => {
[Link](`Search results for: ${[Link].q}`);
});
[Link].q extracts q from the URL.

6. Route Handlers in ExpressJS

Route handlers define how Express responds to requests.

By: Pooja Soni 37


Shree Uttar Gujarat BCA College Unit-2 [FFWD]
[Link]('/example', (req, res, next) => {
[Link]('First handler executed');
next();
}, (req, res) => {
[Link]('Response from second handler');
});
The next() function passes control to the next handler.

7. Route Chaining in ExpressJS

Chaining allows defining multiple handlers for a route using .route().


[Link]('/user')
.get((req, res) => [Link]('Get User'))
.post((req, res) => [Link]('Create User'))
.put((req, res) => [Link]('Update User'))
.delete((req, res) => [Link]('Delete User'));
/user supports multiple HTTP methods using .route().

Implementing Routing in Express

To implement routing in an ExpressJS application, follow these steps:

Step 1: Initialize the [Link] Application

Open your terminal, navigate to your project directory, and initialize the application:
npm init -y
Step 2: Install ExpressJS

Install ExpressJS as a dependency:

npm install express

Step 3: Create the Server File

Create a file named [Link] and add the following code:

const express = require('express');


const app = express();
const PORT = 4000;
[Link]('/', (req, res) => {
[Link]('<h1>Welcome to the Home Page!</h1>');
});
[Link]('/about', (req, res) => {
[Link]('<h1>About Us</h1><p>This is the About page.</p>');
});
[Link]('/contact', (req, res) => {
[Link]('<h1>Contact Us</h1><p>Feel free to reach out!</p>');
});
By: Pooja Soni 38
Shree Uttar Gujarat BCA College Unit-2 [FFWD]
[Link](PORT, () => {
[Link](`Server is listening at [Link]
});

Step 4: Start the Server

In the terminal, run the server

node [Link]

By: Pooja Soni 39

You might also like