0% found this document useful (0 votes)
21 views41 pages

UNIT-2 Full Stack

This document provides an introduction to Express.js and server-side basics with Node.js, covering installation, RESTful backend creation, and handling routes and HTTP methods. It explains the roles of Node.js and Express.js in full stack development, the use of middleware, and the importance of project structuring and tools like Nodemon. Additionally, it details how to define routes using various HTTP methods and the significance of sending responses and working with parameters.

Uploaded by

popd0325
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)
21 views41 pages

UNIT-2 Full Stack

This document provides an introduction to Express.js and server-side basics with Node.js, covering installation, RESTful backend creation, and handling routes and HTTP methods. It explains the roles of Node.js and Express.js in full stack development, the use of middleware, and the importance of project structuring and tools like Nodemon. Additionally, it details how to define routes using various HTTP methods and the significance of sending responses and working with parameters.

Uploaded by

popd0325
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

Unit 2:

Introduction to [Link] and Server-Side Basics with [Link]


2.1 Introduction to [Link] and [Link]
2.1.1 Installing [Link] (v20+) and setting up Express server
2.1.2 Creating a RESTful backend using [Link]
2.1.3 Introduction to nodemon and project structuring
2.2 Handling Routes and HTTP Methods
2.2.1 Defining routes using GET, POST, PUT, DELETE
2.2.2 Sending responses and working with route/query parameters
2.2.3 Connecting routes to controller logic
2.3 Middleware and API Basics
2.3.1 Understanding middleware in Express
2.3.2 Using built-in and custom middleware
(e.g., body-parser, static files)
2.3.3 Introduction to CORS and environment variables

2.1 Introduction to [Link] and [Link]

Introduction

Web applications are generally divided into two main parts: frontend and
backend. The frontend is responsible for user interface and interaction, while
the backend handles data processing, database operations, authentication, and
business logic. To build the backend efficiently, modern developers use
technologies like [Link] and [Link].

[Link] allows JavaScript to run on the server, and [Link] is a framework


that makes backend development easier and faster. Together, they are widely
used for building scalable and high-performance web applications and APIs.
What is Server-Side Programming

Server-side programming refers to writing code that runs on the server instead
of the user’s browser. The server processes user requests, interacts with
databases, performs calculations, and sends responses back to the client.

Examples of server-side tasks:


• Handling form submissions
• User authentication
• Database operations
• API creation

[Link] is a popular server-side technology used for these tasks.

What is [Link]

[Link] is an open-source, cross-platform JavaScript runtime environment that


allows developers to execute JavaScript code outside the browser. It is built on
Google Chrome’s V8 JavaScript engine.

Before [Link], JavaScript was mainly used for frontend development. [Link]
made it possible to use JavaScript for backend development, allowing
developers to use a single language for both frontend and backend.

Features of [Link]

• Asynchronous and non-blocking I/O


[Link] handles multiple requests at the same time without waiting for one
request to finish.

• Single-threaded and event-driven


It uses an event loop to manage multiple client requests efficiently.

• High performance
Built on V8 engine, [Link] executes code very fast.

• Large package ecosystem


[Link] uses npm (Node Package Manager), which provides thousands of free
libraries.

Advantages of [Link]

• Faster development using JavaScript


• Handles large number of concurrent users
• Suitable for real-time applications
• Easy integration with frontend frameworks

Use Cases of [Link]

• Web servers
• RESTful APIs
• Chat applications
• Streaming applications

What is [Link]

[Link] is a fast, minimal, and flexible web application framework built on


top of [Link]. It simplifies the process of creating web servers and APIs by
providing easy-to-use methods and tools.

[Link] reduces the complexity of writing backend code using pure [Link]
by offering built-in support for routing, middleware, and request handling.

Why [Link] is Needed

Using [Link] alone requires writing large amounts of code for handling
requests and responses. [Link] provides a simpler structure and reduces
boilerplate code.

[Link] helps in:


• Handling routes easily
• Managing HTTP requests and responses
• Using middleware functions
• Creating RESTful APIs

Features of [Link]

• Simple routing system


• Middleware support
• Lightweight and fast
• Easy integration with databases
• Supports JSON and REST APIs

Difference Between [Link] and [Link]


[Link] is a runtime environment that allows JavaScript execution on the server.
[Link] is a framework that runs on [Link] to simplify backend
development.

[Link] provides core functionality, while [Link] adds structure and features
for web applications.

Role of [Link] and [Link] in Full Stack Development

In full stack development:


• Frontend is built using Angular, React, or Vue
• Backend is built using [Link] and [Link]
• Database is connected to store data

[Link] and [Link] act as the bridge between frontend and database.

Simple Example Explanation

When a user sends a request from the browser, [Link] receives the request,
processes it using [Link], and sends the response back to the user.

Example:
User → Browser → Express Server → Response → Browser

2.1.1 Installing [Link] (v20+) and Setting up Express Server

Introduction

[Link] is a JavaScript runtime environment that allows developers to run


JavaScript code outside the browser. It is mainly used to build fast, scalable, and
efficient server-side applications. [Link] is a lightweight web framework
built on top of [Link] that simplifies server creation and handling HTTP
requests.

Installing [Link] (v20+)


Step 1: Download [Link]
[Link] can be downloaded from its official website [Link]
Select the LTS (Long Term Support) version, preferably [Link] v20 or
higher, because it is stable and recommended for production use.

Step 2: Install [Link]


Run the downloaded installer and follow the installation steps. Keep all default
settings and complete the installation.

Step 3: Verify Installation


After installation, open Command Prompt or Terminal and type:

node -v
npm -v

If version numbers are displayed, [Link] and npm (Node Package Manager)
are installed successfully.

Understanding npm

npm is a package manager that comes with [Link]. It is used to install libraries
and frameworks such as [Link]. npm helps manage project dependencies
easily.

Setting Up a Basic Express Server

Step 1: Create Project Folder


Create a new folder for the project, for example:

express-demo

Open the folder in Command Prompt or VS Code terminal.

Step 2: Initialize Node Project

Run the following command:

npm init -y
This creates a [Link] file, which stores project information and
dependencies.

Step 3: Install [Link]

Install Express using npm:

npm install express

Express will be added to the node_modules folder and listed in [Link].

Step 4: Create Server File

Create a file named [Link] or [Link].

Example code for Express server:

const express = require('express');


const app = express();

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


[Link]('Hello World from Express Server');
});

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

Explanation of Code

• require('express') imports Express framework


• app is an instance of Express
• [Link]() handles HTTP GET requests
• req represents request, res represents response
• [Link]() starts the server on port 3000

Step 5: Run the Server

Run the server using:


node [Link]

Open browser and visit:

[Link]

The message “Hello World from Express Server” will be displayed.

Advantages of Using [Link]

• Simple and fast server creation


• Handles routing easily
• Supports middleware
• Widely used in real-world applications
• Easy integration with databases and frontend frameworks

Conclusion

Installing [Link] and setting up an Express server is the first step in backend
development. [Link] provides a powerful runtime, while [Link] makes
server-side coding simple and efficient. This setup is widely used for building
RESTful APIs and full-stack web applications.

2.1.2 Creating a RESTful Backend using [Link]

Introduction

A RESTful backend is a server-side application that provides data and services


to clients (such as web or mobile applications) using HTTP requests.

REST stands for Representational State Transfer.

It is a popular architectural style used to build web services. [Link] is


commonly used to create RESTful backends because it is simple, fast, and
flexible.

What is REST?

REST is an architectural style that follows certain rules for communication


between client and server.

Main principles of REST:


• Uses HTTP methods like GET, POST, PUT, DELETE
• Stateless communication (server does not store client session)
• Data is usually exchanged in JSON format
• Each resource is identified by a URL

Example of resource:
/users
/products

What is a RESTful API?

A RESTful API is an API that follows REST principles. It allows the client to
perform CRUD operations on resources.

CRUD operations:
• Create – POST
• Read – GET
• Update – PUT
• Delete – DELETE

Creating a RESTful Backend Using [Link]

Step 1: Create Project and Install Express

Create a project folder and initialize it:

npm init -y

Install Express:

npm install express

Step 2: Create Server File

Create a file named [Link].

Basic server setup:

const express = require('express');


const app = express();

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

Explanation:
• [Link]() middleware is used to read JSON data
• [Link]() starts the server

Defining RESTful Routes

Example: User Resource

GET – Read Data

Used to fetch data from server.

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


[Link]({ message: 'User list' });
});

POST – Create Data

Used to add new data.

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


const user = [Link];
[Link]({ message: 'User created', user });
});

PUT – Update Data

Used to update existing data.

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


const id = [Link];
[Link]({ message: 'User updated', userId: id });
});

DELETE – Delete Data

Used to remove data.

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


const id = [Link];
[Link]({ message: 'User deleted', userId: id });
});

Data Format – JSON

RESTful APIs commonly use JSON format for sending and receiving data.

Example JSON:

{
"name": "Amit",
"email": "amit@[Link]"
}

Testing RESTful APIs

REST APIs can be tested using tools like:


• Postman
• Thunder Client (VS Code extension)
• Browser (for GET requests)

Advantages of RESTful Backend

• Simple and scalable architecture


• Easy integration with frontend frameworks
• Stateless and lightweight
• Platform independent
• Widely used in industry

Conclusion
Creating a RESTful backend using [Link] allows developers to build
powerful APIs using simple JavaScript code. RESTful services make
communication between frontend and backend efficient and standardized.
[Link] makes backend development easy and fast.

2.1.3 Introduction to Nodemon and Project Structuring

Introduction

While developing a backend application using [Link] and [Link],


developers need to restart the server every time they make changes in the code.
This becomes time-consuming and inconvenient. Nodemon is a tool that helps
solve this problem by automatically restarting the server whenever file changes
are detected. Along with nodemon, proper project structuring is important to
make the application easy to manage, readable, and scalable.

What is Nodemon?

Nodemon is a development tool for [Link] applications. It automatically


monitors changes in the project files and restarts the server whenever a file is
modified. Nodemon is used only during development and not in production.

Advantages of Nodemon

• Automatically restarts server on code changes


• Saves development time
• Improves developer productivity
• Easy to install and use
• Useful for large projects

Installing Nodemon

Nodemon can be installed in two ways.

Global installation:
npm install -g nodemon

Local installation (recommended for projects):

npm install nodemon --save-dev

The --save-dev flag installs nodemon as a development dependency.

Using Nodemon

Instead of running the server using:

node [Link]

Use nodemon:

nodemon [Link]

Now, whenever the server file is changed, nodemon automatically restarts the
server.

Using Nodemon with npm Scripts

In [Link] file, add:

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

Run the server using:

npm run dev

What is Project Structuring?

Project structuring means organizing files and folders in a proper way. A good
structure makes the code easy to understand, maintain, and scale. It is very
important for medium and large backend applications.
Basic Express Project Structure

Example structure:

project-folder

├── node_modules
├── [Link]
├── [Link]
├── routes
│ └── [Link]
├── controllers
│ └── [Link]
├── models
│ └── [Link]
├── middleware
│ └── [Link]
└── config
└── [Link]

Explanation of Folders

[Link]
This is the main entry file that starts the Express server.

routes
This folder contains route definitions and maps URLs to controller functions.

controllers
Controllers contain the main logic for handling requests and responses.

models
Models define the data structure and database schema.

middleware
Middleware functions handle tasks like authentication, logging, and validation.

config
Configuration files such as database connection and environment settings are
stored here.
Benefits of Proper Project Structuring

• Code becomes clean and readable


• Easy debugging and maintenance
• Better teamwork
• Scalable architecture
• Follows industry standards

Difference Between Small and Large Projects

Small project:
All code in one file ([Link])

Large project:
Separate files for routes, controllers, models, and middleware

Conclusion

Nodemon is an essential development tool that improves productivity by


automatically restarting the server on code changes. Proper project structuring
helps in building clean, scalable, and maintainable backend applications.
Together, nodemon and structured coding practices are important for
professional backend development.

2.2 Handling Routes and HTTP Methods

Introduction

In a web application, the client (browser or frontend app) communicates with


the server by sending HTTP requests. These requests are sent to specific URLs
called routes. [Link] provides a simple and efficient way to handle routes
and HTTP methods. Routing is one of the core features of [Link] and is
essential for building RESTful APIs.

What is Routing?

Routing refers to the process of determining how an application responds to a


client request for a specific URL and HTTP method. Each route consists of
three parts:
• HTTP method
• URL path
• Callback function
Example:
GET /users

What are HTTP Methods?

HTTP methods define the type of operation that the client wants to perform on
the server.

Common HTTP methods used in RESTful applications:


• GET
• POST
• PUT
• DELETE

These methods are mainly used to perform CRUD operations.

CRUD Operations and HTTP Methods

Create → POST
Read → GET
Update → PUT
Delete → DELETE

2.2.1 Defining Routes using GET, POST, PUT, DELETE

GET Method

The GET method is used to fetch or read data from the server. It does not
change the data on the server.

Example:

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


[Link]({ message: 'Student list' });
});

Use case:
• Fetch list of students
• Retrieve user details

POST Method

The POST method is used to send data to the server and create new records.
Example:

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


const student = [Link];
[Link]({ message: 'Student added', student });
});

Use case:
• Register a new user
• Add new data to database

PUT Method

The PUT method is used to update existing data on the server.

Example:

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


const id = [Link];
[Link]({ message: 'Student updated', studentId: id });
});

Use case:
• Update user profile
• Modify existing record

DELETE Method

The DELETE method is used to remove data from the server.

Example:

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


const id = [Link];
[Link]({ message: 'Student deleted', studentId: id });
});

Use case:
• Delete user account
• Remove unwanted records
Route Parameters

Route parameters are used to capture values from the URL.

Example:

/students/:id

Here, id is a route parameter.

Accessing parameter:

[Link]

Why Routing is Important

• Controls application flow


• Connects client requests to server logic
• Helps in building RESTful APIs
• Makes code organized and readable

Advantages of Express Routing

• Simple syntax
• Supports all HTTP methods
• Easy to manage large applications
• Fast and lightweight

Conclusion

Handling routes and HTTP methods is a fundamental part of [Link]. Using


GET, POST, PUT, and DELETE methods, developers can create RESTful APIs
that perform CRUD operations efficiently. [Link] provides an easy and
structured way to define routes and manage server-side logic.

2.2.2 Sending Responses and Working with Route / Query Parameters


Introduction

After receiving a request from the client, the server must send a response. In
[Link], responses are sent using the response object. Along with responses,
many times the server needs to read data sent through the URL.

This data is accessed using route parameters and query parameters.

Sending Responses in [Link]

[Link] provides different methods to send responses to the client.

[Link]()
Used to send simple text or HTML response.

Example:
[Link]('/', (req, res) => {
[Link]('Welcome to Express Server');
});

[Link]()
Used to send data in JSON format, mostly used in REST APIs.

Example:
[Link]('/api', (req, res) => {
[Link]({ message: 'API response' });
});

[Link]()
Used to send HTTP status codes.

Example:
[Link](200).json({ message: 'Success' });

Common HTTP status codes:


200 – OK
201 – Created
400 – Bad Request
404 – Not Found
500 – Server Error

Route Parameters

Route parameters are values embedded in the URL path. They are mainly used
to identify specific resources.

Example route:
/students/:id

Code example:

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


const id = [Link];
[Link]('Student ID is ' + id);
});

Use cases:
• Fetch data by ID
• Update or delete specific record

Query Parameters

Query parameters are sent after the ? symbol in the URL. They are optional and
used for filtering, searching, or sorting data.

Example URL:
/students?course=BCA&year=2

Accessing query parameters:

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


const course = [Link];
const year = [Link];
[Link]({ course, year });
});

Use cases:
• Search functionality
• Pagination
• Filtering results

Difference Between Route and Query Parameters

Route Parameters
• Part of URL path
• Mandatory
• Used for resource identification

Query Parameters
• Sent after ? in URL
• Optional
• Used for filtering and searching

2.2.3 Connecting Routes to Controller Logic

Introduction

In large applications, writing all logic inside route files makes code messy and
difficult to manage. To solve this, [Link] follows a separation of concerns
using controllers. Routes handle URL mapping, while controllers handle
business logic.

What is a Controller?

A controller is a JavaScript file that contains functions to handle requests and


send responses. Controllers keep route files clean and organized.

Why Use Controllers?

• Clean and readable code


• Easy maintenance
• Better scalability
• Follows MVC architecture

Basic Folder Structure

project

├── routes
│ └── [Link]
├── controllers
│ └── [Link]
└── [Link]

Example Controller File

[Link]

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


[Link]({ message: 'Student list' });
};

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


[Link]({ message: 'Student added' });
};

Example Route File

[Link]

const express = require('express');


const router = [Link]();
const studentController = require('../controllers/studentController');

[Link]('/students', [Link]);
[Link]('/students', [Link]);

[Link] = router;

Connecting Routes in Main Server File

[Link]

const studentRoutes = require('./routes/studentRoutes');


[Link]('/api', studentRoutes);

Flow of Request
Client → Route → Controller → Response

Advantages of Route-Controller Pattern

• Code reusability
• Easy debugging
• Organized project structure
• Industry standard practice

Conclusion

Sending responses and handling route and query parameters are essential parts
of [Link] applications. Using controllers helps separate routing from
business logic, making applications clean, scalable, and easier to maintain.

2.3 Middleware and API Basics

Introduction

In [Link] applications, middleware plays a very important role in handling


requests and responses. Middleware functions sit between the client request and
the server response. They are used to perform common tasks such as logging,
authentication, validation, parsing data, and error handling. Understanding
middleware is essential for building secure and efficient APIs.

What is Middleware?

Middleware is a function that has access to three objects:


• Request (req)
• Response (res)
• Next (next)

Middleware functions execute before the final response is sent. They can
modify the request or response or stop the request from moving further.

Syntax of Middleware

function middlewareName(req, res, next) {


// perform task
next();
}

The next() function passes control to the next middleware or route handler.
Flow of Middleware

Client Request → Middleware → Route → Controller → Response

Why Middleware is Important

• Executes common logic in one place


• Improves code reusability
• Enhances security
• Helps in request validation
• Makes application modular

Types of Middleware in [Link]


There are mainly four types of middleware:

1. Application-Level Middleware

This middleware is applied to the entire application.

Example:

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

{
[Link]('Request received');
next();
});

Use cases:
• Logging
• Authentication
• Data parsing

2. Route-Level Middleware

This middleware is applied to specific routes.

Example:
[Link]('/admin', authMiddleware, (req, res) => {
[Link]('Admin page');
});

Use cases:
• Route protection
• Authorization

3. Built-in Middleware

Express provides some built-in middleware functions.

[Link]()

Used to parse JSON data sent in request body.

[Link]([Link]());

[Link]()

Used to parse form data.

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

[Link]()

Used to serve static files such as images, CSS, and JavaScript.

[Link]([Link]('public'));

4. Error-Handling Middleware

Used to handle errors in application.

Syntax:

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


[Link](500).send('Something went wrong');
});

2.3.1 Understanding Middleware in Express

Introduction
Middleware is one of the most important concepts in [Link]. Middleware
functions act as a bridge between the client request and the server response.
Every request made to an Express application passes through one or more
middleware functions before reaching the final route handler. Middleware helps
in performing common tasks such as authentication, logging, validation, parsing
data, and error handling.

Definition of Middleware

Middleware is a function that has access to the following objects:


• Request object (req)
• Response object (res)
• Next function (next)

Middleware can:
• Execute code
• Modify request or response objects
• End the request-response cycle
• Call the next middleware function

Syntax of Middleware

function middlewareName(req, res, next) {


// perform operation
next();
}

The next() function passes control to the next middleware in the stack.

Middleware Execution Flow

Client Request

Middleware 1

Middleware 2

Route Handler

Response Sent to Client
Role of next() Function

The next() function is very important in middleware.


• If next() is called, the request moves to the next middleware or route.
• If next() is not called, the request stops and no response is sent.

Example:

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


[Link]('Request received');
next();
});

Why Middleware is Needed

• Avoids code duplication


• Improves application security
• Handles common logic in one place
• Makes code modular and clean
• Enhances application performance

Types of Middleware in Express

1. Application-Level Middleware

Applied to the entire application.

Example:

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


[Link]([Link], [Link]);
next();
});

Use cases:
• Logging
• Authentication
• Request parsing

2. Route-Level Middleware

Applied to specific routes.


Example:

function authMiddleware(req, res, next) {


if ([Link]) {
next();
} else {
[Link](401).send('Unauthorized');
}
}

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


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

3. Built-in Middleware

Express provides built-in middleware functions.

Examples:
• [Link]() – Parses JSON request body
• [Link]() – Parses form data
• [Link]() – Serves static files

4. Error-Handling Middleware

Used to handle application errors.

Syntax:

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


[Link](500).send('Server Error');
});

Middleware Order Matters

Middleware is executed in the order it is defined in the code.

Example:

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


[Link]('Middleware 1');
next();
});
[Link]((req, res, next) => {
[Link]('Middleware 2');
next();
});

Output order:
Middleware 1 → Middleware 2

Real-Life Example of Middleware

Think of middleware like security checks at an airport.


Before boarding (route handler), passengers (requests) must pass through
security checks (middleware).

Advantages of Middleware

• Centralized logic
• Easy debugging
• Code reusability
• Improved security
• Scalable application

Conclusion

Middleware is the backbone of [Link] applications. It allows developers to


intercept and process requests before sending responses. Understanding
middleware is essential for building secure, scalable, and maintainable backend
applications.

MIDDLEWARE FLOW DIAGRAM IN [Link]

CLIENT
(Browser / Angular App / Postman)

│ HTTP Request

APPLICATION-LEVEL MIDDLEWARE
(logging, body parsing)

│ next()

CUSTOM / ROUTE-LEVEL MIDDLEWARE
(authentication, validation)

│ next()

ROUTE HANDLER
(GET / POST / PUT / DELETE)


CONTROLLER LOGIC
(business logic, database)


RESPONSE SENT
(JSON / HTML / Status Code)


CLIENT RECEIVES RESPONSE

STEP-BY-STEP DIAGRAM EXPLANATION

1. Client

The client sends an HTTP request to the server.


Example:
GET /students/101

2. Application-Level Middleware

This middleware runs for every request.

Examples:
• Logging request details
• Parsing JSON data
• Handling CORS

Example code:

[Link]([Link]());

3. Custom / Route-Level Middleware


This middleware runs only for specific routes.

Examples:
• Authentication check
• Authorization
• Validation

Example:

[Link]('/dashboard', authMiddleware, handler);

4. Route Handler

The route matches the URL and HTTP method.

Example:

[Link]('/students/:id', controllerFunction);

5. Controller Logic

The controller performs business logic such as:


• Fetching data
• Processing request
• Sending response

6. Response

The response is sent back to the client using:


• [Link]()
• [Link]()
• [Link]()

IMPORTANT POINTS FOR EXAM

• Middleware runs before route handler


• next() passes control forward
• Order of middleware matters
• Middleware improves security and structure
• Used for authentication, logging, validation
ONE-LINE CONCLUSION

Middleware in [Link] acts as a processing layer between client requests and


server responses, allowing reusable and organized handling of application logic.

2.3.2 Using Built-in and Custom Middleware


(body-parser, Static Files)

Introduction

In [Link], middleware is used to process requests before sending responses.


Express provides built-in middleware for common tasks such as reading
request data and serving static files. Developers can also create custom
middleware to perform application-specific tasks like authentication and
logging. Using built-in and custom middleware makes backend applications
clean, secure, and efficient.

Built-in Middleware in [Link]

Built-in middleware is provided directly by Express and does not require extra
coding. These middleware functions help handle common operations.

1. [Link]()

This middleware is used to read and parse JSON data sent in the request body. It
is commonly used in REST APIs when data is sent from frontend or Postman.

Example:

[Link]([Link]());

Use cases:
• Reading form data
• Handling POST and PUT requests
• Parsing API request bodies
2. [Link]()

This middleware is used to read data sent from HTML forms.

Example:

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

Use cases:
• Handling form submissions
• Processing login and registration forms

3. body-parser Middleware

Earlier versions of Express used body-parser as an external library. Now its


features are included in Express itself.

Older method:

npm install body-parser

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


[Link]([Link]());

Modern method (recommended):

[Link]([Link]());

4. [Link]() – Static Files Middleware

This middleware is used to serve static files such as:


• HTML
• CSS
• Images
• JavaScript

Example:

[Link]([Link]('public'));

Folder structure:
project

├── public
│ ├── [Link]
│ ├── [Link]
│ └── [Link]
└── [Link]

Access example:
[Link]

Benefits of Static Middleware

• Serves files efficiently


• Reduces server load
• Simplifies frontend-backend integration

Custom Middleware

Custom middleware is written by developers to perform specific tasks.

Syntax of Custom Middleware

function middlewareName(req, res, next) {


// custom logic
next();
}

Example 1: Logging Middleware

function logger(req, res, next) {


[Link]([Link], [Link]);
next();
}

Usage:

[Link](logger);

Example 2: Authentication Middleware

function authMiddleware(req, res, next) {


if ([Link]) {
next();
} else {
[Link](401).send('Unauthorized Access');
}
}

Usage:

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


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

Difference Between Built-in and Custom Middleware

Built-in Middleware
• Provided by Express
• Handles common tasks
• Easy to use

Custom Middleware
• Written by developer
• Handles application logic
• Highly flexible

Order of Middleware

Middleware executes in the order it is written in code.


If next() is not called, the request stops.

Advantages of Using Middleware

• Centralized request handling


• Improved security
• Clean and modular code
• Reusable logic
• Easy maintenance

Real-Life Example

Middleware works like security checks in an office building. Everyone must


pass security before entering.

Conclusion
Built-in and custom middleware are essential parts of [Link] applications.
Built-in middleware simplifies common tasks like parsing data and serving
static files, while custom middleware allows developers to implement
application-specific logic. Proper use of middleware improves performance,
security, and code structure.

2.3.3 Introduction to CORS and Environment Variables


PART A: CORS (Cross-Origin Resource Sharing)

1. What is CORS?

CORS (Cross-Origin Resource Sharing) is a security mechanism used by web


browsers to control access to resources from different origins (domains).

Definition

CORS allows or restricts web applications running on one origin to access


resources from another origin.

2. What is an Origin?
An origin consists of:

 Protocol (http / https)


 Domain (localhost, [Link])
 Port (3000, 4200)

Example

URL Origin
[Link] Origin A
[Link] Origin B

👉 If origin is different → Cross-Origin Request

3. Why CORS is Needed?


Browsers follow Same-Origin Policy for security.

Same-Origin Policy

 A web page can only access resources from the same origin
 Prevents malicious attacks

Problem

Frontend and backend usually run on different ports

Frontend Backend
Angular → localhost:4200 Express → localhost:3000

➡ Browser blocks request ❌


➡ CORS solves this problem ✅

4. How CORS Works (Flow Diagram – Explanation)


Browser (Frontend)
|
| Request (different origin)
|
Express Server
|
| CORS Headers
|
Browser allows request
Browser checks:

 Is access allowed?
 Are headers present?

5. CORS Headers

Header Description
Access-Control-Allow-Origin Allowed domain
Access-Control-Allow-Methods GET, POST, PUT, DELETE
Access-Control-Allow-Headers Content-Type, Authorization

6. Using CORS in [Link]


Step 1: Install CORS package
npm install cors

Step 2: Import and use CORS


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

const app = express();

[Link](cors());

✔ Allows all origins

7. Allow Specific Origin


[Link](cors({
origin: '[Link]
}));

✔ Best practice for security

8. Real-Life Example
 Frontend: Angular website
 Backend: Express API
 Data: Student details
Without CORS → ❌ Request blocked
With CORS → ✅ Data fetched successfully

9. Advantages of CORS
 Secure communication
 Controls access
 Allows frontend-backend integration
 Prevents unauthorized access

PART B: Environment Variables

1. What are Environment Variables?


Environment variables are key-value pairs used to store configuration data
outside the source code.

Definition

Environment variables store sensitive or changeable data securely.

2. Why Use Environment Variables?

❌ Hardcoding values is dangerous


✔ Environment variables are secure & flexible

Used for:

 Port number
 Database password
 API keys
 Secret tokens

3. Examples of Environment Variables

Variable Value
PORT 3000
DB_PASSWORD mySecret123
JWT_SECRET abc@123
4. Using .env File in [Link]
Step 1: Install dotenv
npm install dotenv

Step 2: Create .env file


PORT=3000
DB_NAME=studentDB
SECRET_KEY=mysecret

Step 3: Load Environment Variables


require('dotenv').config();

Step 4: Use Variables in Code


const port = [Link];

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

5. Important Rules

✔ .env file should not be uploaded to GitHub


✔ Add .env to .gitignore
✔ Used in production and development both

6. Environment Variables Flow Diagram


.env file
|
| dotenv
|
[Link] Process
|
[Link].VARIABLE_NAME

7. Advantages of Environment Variables


 Improves security
 Easy configuration change
 Separate code and configuration
 Industry standard practice

7. CORS vs Environment Variables


Feature CORS Environment Variables
Purpose Security between origins Store configuration
Used in Browser & Server Server
Example Allow frontend Hide passwords

9. Short Exam Answers


Q1. What is CORS?
CORS is a security mechanism that allows or restricts cross-origin requests
between frontend and backend servers.

Q2. Why are environment variables important?


They store sensitive data securely and prevent hardcoding values in the source
code.

10. Summary
 CORS controls cross-origin communication
 Environment variables secure configuration data
 Both are essential for modern backend development
 Commonly used in [Link] applications

You might also like