Unit 2
Unit 2
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
Why [Link]?
[Link] uses asynchronous programming.
Downloading [Link]
Step-1: Downloading the [Link] ‘.msi’ installer.
Destination Folder
o Set the Destination Folder where you want to install [Link] & Select “Next”
o “Administrator”
Installing [Link].
(Do not close or cancel the installer until the install is complete)
Complete the [Link] Setup Wizard.
o Click “Finish”
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.
Before adding Express to your project, ensure that [Link] is installed on your system.
Setting up Express
Open your terminal or command prompt and move to your project's root directory
cd path-to-your-porject
npm init -y
This command initializes the project with default settings, creating a [Link] file that manages
your project's dependencies and metadata.
This installs the [Link] framework and adds it to the dependencies section of your [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
Install [Link]
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
Explanation:
Explanation:
It watches your files when you save code, it restarts the server automatically.
"scripts": {
"start": "node [Link]",
"dev": "nodemon [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.
Use the script you defined in [Link] to start your application with Nodemon.
nodemon [Link]
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:
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.
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
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
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.
[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.
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.
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.
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)
[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.
[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:
// add student
[Link]("/students", function (req, res) {
var student = [Link];
[Link](student);
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]().
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)
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]().
[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]({ 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]().
[Link](data);
};
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
Example:
5.1. Backend (Node with Express)
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]().
[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
// database
var students = [
{ id: 1, name: "Drashti" },
{ id: 2, name: "Aarana" },
];
// 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" });
});
// 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
[Link](data);
};
[Link](data);
};
[Link](data);
};
// delete student
const deleteStudent = async (URL) => {
const response = await fetch(URL, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
});
// Function Calls
getStudents(BASEURL + "/students");
updateStudentPatch(BASEURL + "/students/2", {
name: "Aarana Updated using Patch",
});
deleteStudent(BASEURL + "/students/3");
2.2.2 Sending responses and working with route/query parameters
[Link](PORT, () => {
[Link](`Server is running at [Link]
});
Output: Accessing [Link] will display
[Link](PORT, () => {
[Link](`Server is running at [Link]
});
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.
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.
[Link](PORT, () => {
[Link](`Server is running at [Link]
});
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.
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.
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.
Types of Middleware
ExpressJS offers different types of middleware and you should choose the middleware based on
functionality required.
1. Application-level Middleware
2. Router-level Middleware
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
// Filename: [Link]
const express = require('express');
const app = express();
const port = [Link] || 3000;
[Link](port, () => {
[Link](`Listening on port ${port}`);
});
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
// 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
[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.
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))
[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.
[Link]([Link]());
Example:
[Link]("/api/student", (req, res) => {
[Link]([Link]); // JSON data
[Link]("Student Added");
});
3. [Link]() (Static Files): Used to serve static files (HTML, CSS, images)
Folder structure:
public/
├── [Link]
├── [Link]
[Link]([Link]("public"));
middleware/[Link]
Use it:
const logger = require("./middleware/logger");
[Link](logger);
Application-level
[Link](logger);
Route-level
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];
}
This JavaScript function makes an HTTP GET request to the provided URL (urlLink) and returns the
response text from the resource.
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.
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:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CORS Test</title>
</head>
<body>
<h1>Testing CORS</h1>
<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:
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]?
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]().
[Link](3000, () => {
[Link]('Server is running on port 3000');
});
Output
In this example
Types of Routes
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.
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
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.
Open your terminal, navigate to your project directory, and initialize the application:
npm init -y
Step 2: Install ExpressJS
node [Link]