0% found this document useful (0 votes)
94 views293 pages

IT3501-Full Stack Web Development Notes

The document is a study material for the Full Stack Web Development course (IT3501) at Mailam Engineering College, covering key topics such as web development frameworks, Node.js, MongoDB, Express, Angular, and React. It includes an outline of course units, textbooks, references, and the vision and mission statements of the institute and department. Additionally, it provides a series of questions and answers related to the course content to aid student learning.

Uploaded by

yusufshabana22
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)
94 views293 pages

IT3501-Full Stack Web Development Notes

The document is a study material for the Full Stack Web Development course (IT3501) at Mailam Engineering College, covering key topics such as web development frameworks, Node.js, MongoDB, Express, Angular, and React. It includes an outline of course units, textbooks, references, and the vision and mission statements of the institute and department. Additionally, it provides a series of questions and answers related to the course content to aid student learning.

Uploaded by

yusufshabana22
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

Mailam (PO), Villupuram (Dt) Pin:604304

Approved by AICTE, New Delhi, Affiliated to Anna University, Chennai,


(

Accredited by NAAC with ‘A’ Grade& TATA Consultancy Services)

IT3501-FULLSTACK WEB DEVELOPMENT


[REGULATION-2021]

STUDY MATERIAL

DEPARTMENT OF INFORMATION TECHNOLOGY

NAME OF THE STUDENT:…………………………………………………………………….

REGISTER NUMBER:…………………………………………………………………………....

YEAR / SEM:………………………………………………………………………………………...

ACADEMIC YEAR:………………………………………………………………………………

PREPARED BY
[Link], AP/IT
MAJLAM
Engineering College
Mailam (PO), Villupuram (Dt) Pin:604304
Approved by AICTE, New Delhi, Affiliated to Anna University, Chennai,
Accredited by NAAC with 'A' Grade& TATA Consultancy Services)
DEPARTMENT OF INFORMATION TECHNOLOGY

SEM/YEAR: III/V BATCH: 2024-2027


SUB CODE: IT3501 SUB NAME: FULL STACK WEB DEVELOPMENT

UNIT I BASICS OF FULL STACK


Understanding the BasicWeb Development Framework - User - Browser - Webserver -
Backend Services - MVC Architecture - Understanding the different stacks -The role of
Express - Angular - Node - Mongo DB - React
UNIT II NODE JS
Basics of Node JS nstallation- Working with Node packages - Using Node package
manager - Creating a simple [Link] application Using Events - Listeners -Timers -
Callbacks - Handling Data I/0 - Implementing HTTP services in [Link]
UNIT III MONGO DB

Understanding NoSQL and MongoDB - Building MongoDB Environment - User


accounts - Access control - Administering databases - Managing collections -
Connecting to MongoDB from [Link] - sinmple applications
UNIT IV EXPRESS AND ANGULAR

Implementing Express in [Link] - Configuring routes - Using Request and Response


objects - Angular - Typescript -Angular Components- Expressions - Data binding -
Built-in directives
UNIT V REACT

MERN STACK - Basic React applications - React Components - React State - Express
REST APls - Modularization and Webpack - Routing with React Router - Server-side
rendering
TEXT BOOKS

1. Brad Dayley, Brendan Dayley, Caleb Dayley, [Link], MongoDB and Angular Web
Development', Addison-Wesley, Second Edition, 2018
2. Vasan Subramanian, Pro MERN Stack, Full Stack Web App Development with
Mongo, Express, React, and Node', Second Edition, Apress, 2019.
R E F E R E N C E S

to the Everyday
.hris Northwood, The Full Stack Developer: Your Essential Guide edition, 2018
Apress; 1st
at-lls Expected of a Modern Full Stack Web Developer', Building Web
Chinnathambi, Learning React: A Hands-On Guide to
2. Kirupa 2nd edítion, 2018
Using React and Redux', Addison-Wesley Professional,
Applications

3. [Link] . t u t o r i a l s p o i n t . c o m / t h e _ f u l l _ s t a c k _ w e b _ d e v e l o p m e n t / i n d e x . a s p

a h t t p s : / / w w w . c o u r s e r a . o r g / s p e c i a l i z a t i o n s / f u l l - s t a c k - r e a c t

E bttps://[Link]/course/the-full-stack-web-development/

PAPERS UPDATION
ANNA UNIVERSITY QUDSTION

Part - B Part C
Part - A Nov/Dec 2024/
April/ May
Q. Page Page Page Q. No Page 2025
Unit Page Q. Page Q. No No.
No No. No No. No.
No No. No No.
Nov/ Dec 2024
1 6 2 3 11.a 20 11.b 44,47
01 16.b 50 April/May
7 11.a 13 11.b 20 16.a 49 2025
6 2
Nov/ Dec 2024
3 1,12 4 5 12.a 40,44 12.b 66

02
April/ May
4 6 12.a 40 12.b 37 2025
1

59 Nov/Dec 2024
5 4 6 7 13.a 20 13.b 16.a 57

03 April/May
10,13 2025
5 7 6 13.a 20 13.b

00 Nov/ Dec 2024


7 14.a 12,13 14.b 40,50
04 April/ May
7 14.a 46 14.b 10,59 2025

16.b 105
63 10 64 15.a 98 15.b 85,92 Nov/ Dec 2024
05
April/ May
64 10 62 15.a 72 15.b 103 2025

PREPARED BY
[Link]., AP/IT

BATCHco-ORDINATOR VERIFIED BY PRINCIPAL


Mr. R. Gajendiran., ASP/T Dr. S. Kalaivany
HOD/IT
VISION OF THE INSTITUTE
 To bring forth prosperity through modern technology by means of
imparting value based education, innovation and become a world
class technical institution
MISSION OF THE INSTITUTE
 M1: To provide necessary technical skills through excellent
standards of quality education, keeping pace with ever changing
technologies.
 M2: To develop the spirit of entrepreneurship among the students
through entrepreneurial awareness campaign, training, research
and development etc
 M3: To bring students together to be trained in leadership skills,
engage in activities that promote ethical manners, exhibit social
liabilities and inspire a dedication to excellence
VISION OF THE DEPARTMENT
 To foster eminent information technologist, researchers and
innovators competent to meet current challenges of the modern
computing Industry with professional expertise.
MISSION OF THE DEPARTMENT
 M1: To impart quality education that incubate students with firm
foundation in IT domain to meet ever-changing Industry trends.
 M2: To inculcate spirit of leadership and entrepreneurship skills
to meet dynamic industrial needs while emphasizing human values
and ethics for the betterment of society
 M3: To encourage and guide the students to participate in research
oriented activities and pursue lifelong learning.
----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

UNIT I - BASICS OF FULL STACK


Understanding the Basic Web Development Framework - User - Browser – Web server
- Backend Services – MVC Architecture - Understanding the different stacks –The
role of Express – Angular – Node – Mongo DB – React

Two Marks
1. What is web development framework? (Nov/Dec – 2023)
A web development framework is a collection of tools, libraries and
technologies that are used to create web applications and websites. It
provides a basic structure and set of conventions for developers to build
web applications quickly and efficiently.
2. Why do we use web framework? Give any two reasons.
a) Saves time
The most striking feature of web framework is that It saves time and
energigy in developing any app because the developer doesnot need to worry
about session handling, error handling and authentication logic. These
functions are taken care of by web framework
b) Flexibility and customizable
Add-ons, themes, plugins, widgets enable rapid customixation
on the web application. This brings out a lot of flexibility in code
development
3. What are the components of web development framework?
The component of web development framework are
l. User
2. Browser
3. Web Server
4. Backend services
Draw the diagram to visualize the components in a website/web application.
The above diagram is to provides a basic diagram to make it easier to visualize the
components in a website/web application.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 1


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

4. What is a Web Browser? List out the example of web server.

 The web browser is an application software to explore www (World Wide


Web). It provides an interface between the server and the client and it
requests to the server for web documents and services.
 It works as a compiler to render HTML which is used to design a webpage.
 Whenever we search for anything on the internet, the browser loads a web
page written in HTML, including text, links, images, and other items such
as style sheets and JavaScript functions. Google Chrome, Microsoft Edge,
Mozilla Firefox, and Safari are examples of web browsers.

5. Give the importance of browser.


The browser plays three roles in web framework -
1. It provides communication to and from the server.
2. It interprets the data from the server and displays the visual
output.
3. The browser handles user interaction through the key board,
mouse, touchscreen or other input devices and takes the
appropriate action.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 2


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
6. What is GET and POST request?
i. GET: The GET request is typically used to retrieve data from the server.
This data can be in the .html files or images.
ii. POST: The POST request is used for sending the data to the server. For
example - Credit card details while performing online shopping.

7. What is web server?


Web server is a special type of server to which the web browser submits
the request of a web page which is desired by the client.

8. Enlist the functions of web server


Various functions of web server are -
1. The web servers accept the requests from the web browsers.
2. The user request is processed by the web server.
3. The web servers respond to the users by providing the services which they
demand for over the web browsers.
4. The web servers serve the web based applications.

9. What do you mean by backend services? (Nov/Dec-2025)


What is the role of backend services? (April/May -2025)
1. Backend services are the services that run behind the web server. These
services the data to the web server which is requested by the web browser.
2. The most commonly used backend service is a database that stores the information.

10. What is MVC?


i. Model
a. This part of the architecture is responsible for managing the
application data. This module responds to the request made from
view. The model gives instructions to the controller to update when
the response is made.
ii. View
a. This part takes care of the presentation of data. The data is presented
in desired format with the help of view. This is a script based system

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 3


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
using ISP, ASP, PHP and so on.

iii. Controller
The controller receives input, validates it and then performs business
operations that modify the state of the data model. The controller basically
responds to user requests and performs interaction with the model.

11. What is Full-Stack Development? (April/May -2023)


Full-stack development refers to the development of both the front-end and
back-end of a web application or website. But first,
what’s ‘full stack’?
A full stack is made up of the front-end that deals with the user interface,
the back-end that deals with data validation, and the database that acts as
storage—a repository of information from the front-end through the logic
layer.
‘Full stack’ refers to the collection of multiple components in a software application
that work together to ensure its smooth running—this includes software products,
patches, coding frameworks, servers, operating systems, database tools, and more.

12. List out the benefit of full stack Development.


 Time and money saver
 Rounded solution
 Higher visibility
 Complete ownership
 More learning and greater opportunity

13. Who is eligible for the full-stack developer position?


A person to be a full-stack developer, If you can write HTML, CSS,
JavaScript, SQL, and Java.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 4


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

14. What are the responsibilities of a full-stack developer?


Full-stack developers are responsible for building and maintaining
the entire application from top to bottom. This means they need to have a
good understanding of how each part of the system works to support it.
Full-stack developers should be familiar with all aspects of web
development, including front-end (JavaScript, HTML, CSS), back-end (PHP,
Ruby, Python), databases (MySQL), and more. They also need to be able to
communicate effectively with both designers and other developers
throughout the process.
15. What is Express in full stack? (Nov/Dec-2023)
 Express is used for server side development in full stack.
 As it is running in [Link], it is easy to configure, implement and control the
web application.
 The Express module acts as the webserver in the [Link]-to-Angular stack.
 The fact that it is running in [Link] makes it easy to configure, implement,
and control.
16. Outline the roles of backend services (April/May – 2024)
Backend services play a critical role in the architecture of web applications
and are responsible for various essential functions that ensure the smooth
operation and functionality of the application.
Here are some key roles of backend services:
1. Data Storage and Management
2. Business Logic
3. User Authentication and Authorization
4. API Endpoint Management
5. Data Validation and Security

17. Define AngularJS:


AngularJs is a JavaScript open source front-end framework that is mainly
used to develop single page web applications(SPAs). It is a continuously
growing and expanding framework which provides better ways for developing

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 5


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
web applications. It changes the static HTML to dynamic HTML. It is an open
source project which can be freely used and changed by anyone. It extends
HTML attributes with Directives, and data is bound with HTML.
18. What is [Link]
React is a declarative, efficient, and flexible JavaScript library for building user
interfaces. ReactJS is an open-source, component-based front end library
responsible only for the view layer of the application. It is maintained by
Facebook.
19. List out the Popular Stacks in full stack web development.
 MEAN Stack: MongoDB, Express, AngularJS and [Link].
 MERN Stack: MongoDB, Express, ReactJS and [Link]
 Django Stack: Django, python and MySQL as Database.
 Rails or Ruby on Rails: Uses Ruby, PHP and MySQL.
 LAMP Stack: Linux, Apache, MySQL and PHP.

20. Expand the term MERN in full stack web development


The MERN stack consists of the following technologies:
 MongoDB: A document-based open source database.
 Express: A web application framework for [Link].
 React: A JavaScript front-end library for building user interfaces.
 [Link]: JavaScript run-time environment that executes JavaScript code
outside of a browser (such as a server).

[Link] between browser and server in web (Nov/Dec-2024) (April/May-2025)


Key Differences

 Purpose: A web browser is used to browse and display web pages, while a web
server provides these documents when requested by browsers1.
 Function: Browsers send HTTP requests and receive HTTP responses, whereas
servers receive HTTP requests and send HTTP responses2.
 Installation: Browsers are installed on the client’s device, while servers can be
remote machines or local computers3.
 Data Storage: Browsers store cookies locally, while servers provide storage for web pages

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 6


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

[Link] do we need the backend services in web development? (Nov/Dec-2025)

Backend services are essential in web development because they handle the
core functionality and data management that happens behind the scenes
of a web application. The key reasons for need the backend services are:-

1. Data Storage and Management

 Web apps often need to store data like user information, orders, blog posts,
messages, etc.
 Backend services connect to databases (like MySQL, MongoDB, PostgreSQL) to
read/write this data.
 Example: When a user signs up, their info is saved in the database via backend
logic.

2. Authentication and Authorization

 They manage user login, signup, password security, and access control.
 Example: Only logged-in users can access their dashboard—this is enforced by
backend logic.

3. Business Logic

 Backend handles the rules and logic of the app (e.g., validating forms, calculating
totals, processing payments).
 Example: In an e-commerce app, the backend calculates tax, shipping costs, and
applies discounts.

4. APIs and Integration

 Backend services expose APIs (Application Programming Interfaces) that frontend


apps can call.
 They also connect to external services like payment gateways (Stripe), email
providers (SendGrid), etc.

5. File Management

 Handle uploads, storage, and retrieval of files like images, documents, etc.
 Example: When a user uploads a profile picture, the backend stores it and links it
to the user account.

6. Security

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 7


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
 Backend protects sensitive data and implements server-side validation, rate
limiting, and encryption.
 Example: Credit card numbers are handled securely on the backend, not exposed
to the frontend.

7. Scalability and Performance

 Backend services can be designed to handle high traffic, load balancing, and
background jobs.
 Example: A notification system that sends emails or pushes messages without
blocking the frontend.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 8


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
Part -B
1. Describe the concept about Full Stack Development in Detail.
Full Stack Development refers to the development of both front end (client side)
and back end(server side) portions of web application.

Full stack web Developers


Full stack web developers have the ability to design complete web
applications and websites. They work on the frontend, backend, database and
debugging of web applications or websites.

Fig 1.1 Full Stack Development


Technology Related to Full Stack Development
Front-end Development
It is the visible part of website or web application which is responsible for user
experience. The user directly interacts with the front end portion of the web
application or website.

Front-end Technologies
The front end portion is built by using some languages which are discussed below:
 HTML
HTML stands for Hyper Text Markup Language. It is used to design the front
end portion of web pages using markup language. HTML is the combination
of Hypertext and Markup language. Hypertext defines the link between the

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 9


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
web pages. The markup language is used to define the text documentation
within tag which defines the structure of web pages.
 CSS
Cascading Style Sheets, fondly referred to as CSS, is a simply designed
language intended to simplify the process of making web pages presentable.
CSS allows you to apply styles to web pages. More importantly, CSS enables
you to do this independent of the HTML that makes up each web page.
 JavaScript
JavaScript is a famous scripting language used to create the magic on the
sites to make the site interactive for the user. It is used to enhancing the
functionality of a website to running cool games and web-based software.
Front End Libraries and Frameworks
 AngularJS:
AngularJs is a JavaScript open source front-end framework that is mainly
used to develop single page web applications(SPAs). It is a continuously
growing and expanding framework which provides better ways for developing
web applications. It changes the static HTML to dynamic HTML. It is an open
source project which can be freely used and changed by anyone. It extends
HTML attributes with Directives, and data is bound with HTML.
 [Link]
React is a declarative, efficient, and flexible JavaScript library for building user
interfaces. ReactJS is an open-source, component-based front end library
responsible only for the view layer of the application. It is maintained by
Facebook.
 Bootstrap
Bootstrap is a free and open-source tool collection for creating responsive
websites and web applications. It is the most popular HTML, CSS, and
JavaScript framework for developing responsive, mobile-first web sites.
 jQuery
jQuery is an open source JavaScript library that simplifies the interactions
between an HTML/CSS document, or more precisely the Document Object
Model (DOM), and JavaScript. Elaborating the terms, jQuery simplifies HTML
Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 10
----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
document traversing and manipulation, browser event handling, DOM
animations, Ajax interactions, and cross-browser JavaScript development.
SASS
It is the most reliable, mature and robust CSS extension language. It is used
to extend the functionality of an existing CSS of a site including everything
from variables, inheritance, and nesting with ease.
Some other libraries and frameworks are: Semantic-UI, Foundation,
Materialize, [Link], [Link], [Link] etc.
Back-end Technologies
It refers to the server-side development of web application or website with a primary
focus on how the website works. It is responsible for managing the database through
queries and APIs by client-side commands. This type of website mainly consists of
three parts front end, back end, and database.

The back end portion is built by using some libraries, frameworks, and languages
which are discussed below:
 PHP
PHP is a server-side scripting language designed specifically for web
development. Since, PHP code executed on server side so it is called server side
scripting language.
 C++
It is a general purpose programming language and widely used now a days for
competitive programming. It is also used as backend language.
 Java
Java is one of the most popular and widely used programming language and
platform. It is highly scalable. Java components are easily available.
 Python
Python is a programming language that lets you work quickly and integrate
systems more efficiently.
 [Link]
 [Link] is an open source and cross-platform runtime environment for
executing JavaScript code outside of a browser.
Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 11
----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
 NodeJS is not a framework and it’s not a programming language.
 We often use [Link] for building back-end services like APIs like Web
App or Mobile App.
 It’s used in production by large companies such as Paypal, Uber, Netflix,
Walmart and so on.
Back End Frameworks
The list of back end frameworks are: Express, Django, Rails, Laravel, Spring etc.
The other back end program/scripting languages are: C#, Ruby, REST, GO etc.
Structuring the data in efficient way.
Handle request-response of APIs for storing and retrieve data.
Security of data is important.
Note: JavaScript is essential for all stacks as it is dominant technology on Web.
 Database
Database is the collection of inter-related data which helps in efficient
retrieval, insertion and deletion of data from database and organizes the data
in the form of tables, views, schemas, reports etc.
 Oracle
Oracle database is the collection of data which is treated as a unit. The purpose
of this database is to store and retrieve information related to the query. It is
a database server and used to manages information.
 MongoDB
MongoDB, the most popular NoSQL database, is an open source document-
oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that
MongoDB isn’t based on the table-like relational database structure but
provides an altogether different mechanism for storage and retrieval of data.
 Sql
Structured Query Language is a standard Database language which is used to
create, maintain and retrieve the relational database.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 12


-----
IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
2. Explain web development framework with suitable block diagram. Also explain
the components of it.
Describe the major functions of web browser, web server and outline the working
of web server. (Nov/Dec – 2023)
Explain the component of web development framework. (April/May – 2024)
(April/May-2025)

What is Framework?
 Framework is a platform for developing applications which provides a
foundation on which software applications can be built.
 The front end frameworks are the software packages that provide-The
Reusable code modules, standardized front end technologies and Readymade
interface blocks for making the front end development faster and simple.
Basic concept:
 A web development framework is a collection of tools, libraries and
technologies that are used to create web applications and websites.
 It provides a basic structure and set of conventions for developers to build web
applications quickly and efficiently.
 To understand the benefits of utilizing [Link], MongoDB, and Angular as in
web framework, this section provides an overview of the basic components of
most websites.
 The main components of any given web framework are: -
i. User,
ii. Browser,
iii. Webserver,
iv. Backend services.

 Although websites vary greatly on appearance and behavior, all have these
basic components in one form or another.
 This section is not intended to be in-depth, comprehensive, or technically exact,
but rather a high level perspective of the parts involved in a functional website.

 The components are described in a top-down manner from user down to


backend services.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 13


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

Figure 1.2 The components of a basic website/web application

Figure 1.2 provides a basic diagram to make it easier to visualize the components in
a website/web application.
1. User
 Users are a fundamental part of all websites; they are, after all, the reason
websites exist in the first place.
 User expectations define the requirements for developing a good website, and
these expectations have changed a lot over the years.
 Users used to accept the slow, cumbersome experience of the “world-wide-wait,”
but no longer.
 They expect websites to behave closer to applications installed on their
computers and mobile devices.
 The user role in a web framework is to sit on the visual output and interaction
input of webpages.
 That is, users view the results of the web framework processing and then
provide interactions using mouse clicks, keyboard input, and swipes and taps on
mobile devices.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 14


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

2. Browser
Browser is an application for accessing websites. User interacts with the
browser in the web development framework.
The browser plays three roles in the web framework, They are:
1. It provides communication to and from the webserver.
2. It interprets the data from the server and renders it into the view that the user
actually sees.
3. The browser handles user interaction through the keyboard, mouse,
touchscreen, or other input device and takes the appropriate action.
2.1 Browser to Webserver Communication
 Browser-to-webserver communication consists of a series of requests using
the HTTP and HTTPS protocols.
 Hypertext Transfer Protocol (HTTP) defines communication between the
browser and the webserver.
 It is a request/response model.
 HTTP defines what types of requests can be made by the user as well as the
format of those requests and the HTTP response.
 HTTPS adds an additional security layer, SSL/TLS, to ensure secure connections
by requiring the webserver to provide a certificate to the browser.
 The user then can determine whether to accept the certificate before allowing
the connection.
 The browser makes three main types of requests to the server:
i. GET: The GET request is typically used to retrieve data from the server,
such as .html files, images, or JSON data.
ii. POST: POST requests are used when sending data to the server, such as
adding an item to a shopping cart or submitting a web form.
iii. AJAX: Asynchronous JavaScript and Extensible markup language,
In AJAX, the GET or POST request is done directly by JavaScript running
in the browser.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 15


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

The screen that the user actually views and interacts with is often made up of several
different pieces of data retrieved from the webserver.
The browser reads data from the initial URL and then renders the HTML document
to build a Document Object Model (DOM).
2.2 Difference between GET and POST requests
 When a user submits his request using the GET method then the URL string
displays the request submitted by the user. But if the POST method is used
then URL string does not show the submitted contents.
 The common browsers are Internet Explorer, Mozilla Firefox, Google Chrome,
Safari.
2.3 Rendering the bowser view :
 The browser reads data from initial URL and then renders the HTML document
to build the Document Object Model (DOM).
 The DOM is a tree structured object. The browser interprets each
DOM element and renders it to user's screen to build a webpage
view.
 For example, the document will have html as a child, and html will have head
and body as children, and body may have div, p, or other elements as children,
like this:
 document
+ html
+ head
+ body
+ div
+p
 Browsers get different types of data from multiple web server
requests to build the webpage.
 The browser interprets each DOM element and renders it to the user’s screen
to build the webpage view.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 16


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
 The browser often ends up getting various types of data from multiple webserver
requests to build the webpage.

The following are the most common types of data the browser uses to render the final
user view as well as define the webpage behavior.
 HTML files: These provide the fundamental structure of the DOM.
 CSS files: These define how each of the elements on the page is to be styled;
for example, font, color, borders, and spacing.
 Client-side scripts: These are typically JavaScript files. They can provide added
functionality to the webpage, manipulate the DOM to change the look of the
webpage, and provide any necessary logic required to display the page and provide
functionality.
 Media files: Image, video, and sound files are rendered as part of the webpage.
 Data: Any data, such as XML, JSON, or raw text, can be provided by the
webserver as a response to an AJAX request.
 HTTP headers: The HTTP protocol defines a set of headers that can be used
by the browser and client-side scripts to define the behavior of the webpage. For
example, cookies are contained in the HTTP headers. The HTTP headers also define
the type of data in the request as well as the type of data expected to be returned
back to the browser.
2.4 User Interaction
 The user interacts with the browser via input devices such as mice, keyboards,
and touchscreens.
 The browser has an elaborate event system that captures these users input
events and then takes the appropriate action.
 Actions vary from displaying a popup menu to loading a new document from
the server to executing client-side JavaScript.
3. Webserver
 Web server is a special type of server to which the web browser submits the request of a
web page which is desired by the client

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 17


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
 The webserver’s main focus is handling requests from browsers. As described
earlier, the browser may request a document, post data, or perform an AJAX
request to get a data. The webserver uses the HTTP headers as well as the URL
to determine
 what action to take. This is where things get different depending on the
webserver, configuration, and technologies used.
 Most out-of-the-box webservers, such as Apache and IIS, are made to serve
static files such as .html, .css, and media files. To handle POST requests that
modify server data and AJAX requests to interact with backend services,
webservers need to be extended with server-side scripts.
 A server-side program is really anything that can be executed by the webserver
to perform the task the browser is requesting. These can be written in PHP,
Python, C, C++, C#, Java, ... the list goes on and on. Webservers such as
Apache and IIS provide mechanisms to include server-side scripts and then wire
them up to specific URL locations requested by the browser.
 Functions of web server
Various functions of web server are
1. The web servers accept the requests from the web browsers.
2. The user request is processed by the web server.
3. The web servers respond to the users by providing the services which they
demand for over the web browsers.
4. The web servers serve the web based applications.
5. The DNS translates the domain names into the IP addresses.
6. The servers verify given address exists, find necessary files, run appropriate
scripts, exchange cookies if necessary and return back to the browser.
7. Some servers actively participate in session handling techniques.
3.1 Apache
 It is an excellent server because of its two important features: Reliability and
Efficiency.
 Secondly it is more popular because it is an open source software. That
means it is freely available to anybody. Apache web server is best suitable for
UNIX systems but it can also be used on window box the apache web server

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 18


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
can be configured as per the requirements using the file [Link]. This file
is present in the Apache software package.

3.2 IIS

The internet in information services or internet information server is a kind of web


server provided by Microsoft. This server is most popular on the Windows platform.
Following are some differnces between Apache and IIS servers –

[Link] Apache web server IIS web server

Apache web server is useful on


1. both unix based systems and IIS web server is used on windows platform.
on windows platform.
It is a vendor specific product and can be
2. It is an open source product.
used on windows products only.
For the IIS server, the behavior is controlled
The Apache web server can be by modifying the window based
3. controlled by editing the management programs called IIS snap in.
configuration file [Link] We can access IIS snap-in through the
Control-Panel->Administrative Tools.
Table 1.1 Differnces between Apache and IIS servers
4. Backend Services
 Backend services are services that run behind the webserver and provide data
used to build responses to the browser.
 The most common type of backend service is a database that stores
information.
 When a request comes in from the browser that requires information from the
database or other backend service, the server-side script connects to the
database, retrieves the information, formats it, and then sends it back to the
browser.
 Similarly, when data comes in from a web request that needs to be stored in
the database, the server-side script connects to the database and updates
the data.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 19


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

[Link] the detail about Understanding the MVC Architecture in the MERN Stack
What is MVC Architecture? Explain the components of MVC and how data flow
takes place in MVC Architecture with suitable example. (Nov/Dec-2023)
Explain the major components of MVC architecture and also summarizes the
benefits and disadvantages of MVC model in application development.
(April/May- 2024)

With neat diagram, Illustrate in detail about MVC architectural design pattern of development
with its components and design principles. (Nov/Dec -2024)
Illustrate in detail about MVC architecture with neat diagram. (April/May-2025)
The Model-View-Controller (MVC) is an architectural pattern that separates
an application into three basic components: the model, the view, and the controller.
Each of these components are built to handle specific development aspects of an
application. MVC is one of the most frequently used industry-standard web
development framework to create scalable and extensible projects.

Fig 1.3 Model View Controller Architecture

Let’s discuss about the three basic logic components in a little bit more detail:
1. Model:
 This part of the architecture is responsible for managing the data of the
application domain.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 20


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
  This module responds to requests for information about its state

 (usually from the view).

  This model gives instructions to the controller to update when the
 response is made.

  In event — driven systems, the model notifies observers (usually views)
when the information changes so that they can react.

2. View:
 This part takes care of the presentation of data.
 The data is presented in desired format with help of view.
 renders the model into a form suitable for interaction, typically a user
interface element.
 Multiple views can exist for a single model for various purposes.
 A viewport typically has one to one correspondence with a display
surface and knows how to render to it.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 21


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
3. Controller:
 The controller receives input, validates it and then performs business
operations that modify the state of the data model. The controller
basically responds to user requests and performs interaction with the
model
 receives user input and initiates a response by making calls on model
objects.


A controller accepts input from the user and instructs the model and
viewport to perform actions based on that input.
In MVC Architecture,
 Model represents the data
 View is the user interface
 Controller is the request handler.
Features or benifits of MVC framework
1. Separation of logic
There is a separation of application tasks such as input logic, business logic
and UI logic. This makes testing and debugging easy. modification in one
component does not affect the other.
2. Ability to provide multiple views
In MVC model, we can create multiple views.
3. Faster development process
MVC supports rapid and parallel development. If an MVC model is used to
develop any particular we application, then it is possible that one programmer
can work on the view while the other can work on the controller to create the
business logic of the web application.
4. Returns data without formatting
MVC pattern returns data without applying any formatting. Hence, the same
components can be used and called for use with an interface.
5. Customization
It is an extensible and pluggable framework. MVC framework are designed so
that the components can be placed or customized.
Disadvantages of the MVC Model

1. Complexity:

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 22


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
o Initial Setup: Setting up an MVC framework can be complex and time-
consuming, especially for smaller projects. It requires a clear
understanding of the pattern and how to properly separate concerns.
o Learning Curve: For beginners, understanding and implementing the
MVC pattern can be challenging. It often requires more experience and
knowledge compared to simpler architectures.
2. Overhead:
o Increased Development Time: The initial development phase can be
slower due to the need to create separate components and ensure they
interact correctly.
o Boilerplate Code: MVC frameworks often require a significant amount
of boilerplate code, which can make the codebase larger and more
cumbersome to manage.
3. Performance:
o Potential Performance Hits: The additional layers of abstraction and
separation can introduce latency and overhead, potentially impacting
the application's performance, particularly in resource-constrained
environments.
4. Complex Debugging:
o Complex Interactions: Debugging an MVC application can be
challenging due to the complex interactions between the Model, View,
and Controller. Tracing the flow of data and control through the layers
can be difficult.
5. Inconsistent Implementation:
o Varied Interpretations: The MVC pattern can be implemented in
different ways, leading to inconsistencies and confusion, especially
when multiple developers or teams are involved. This inconsistency can
affect the maintainability and scalability of the application.
6. Tight Coupling of Components:
o Interdependencies: While MVC aims to decouple components, in
practice, the Controller can become tightly coupled with the View and
Model, leading to a "God Object" scenario where the Controller handles
too much logic and coordination.

Brief Introduction to the MERN Stack


The MERN Stack is a JavaScript Stack that is used for easier and faster deployment of
full-stack web applications.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 23


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

Fig 1.4 MERN Stack


The MERN stack consists of the following technologies:
 MongoDB: A document-based open source database.
 Express: A web application framework for [Link].
 React: A JavaScript front-end library for building user interfaces.
 [Link]: JavaScript run-time environment that executes JavaScript code
outside of a browser (such as a server).
It is also common to use Mongoose, which is a simple, schema-based solution to model
application data.
MVC and MERN
MERN isn’t an MVC framework in the traditional sense, because it spans both the
server and the browser. MVC can also be achieved by sticking to server-side templating
in Node, and just sending the HTML to the browser and treating the browser as the
View layer i.e. doing things the way things have always been done forever.
Although, when React is combined with a javascript backend, then it is MVC. React
serves as the “V” in the MVC
 Mongoose’ models defines the data part. This is where we will store all of the
crucial data our application needs to function.
 Express & [Link] does all the functional programming and will be used to write
the Business Logic Tier (controller). This tier represents the Application Server
that will act as a bridge of communication for the Client and Database. This tier
will serve the React components to the user’s device and accept HTTP requests
from the user and follow with the appropriate response.
 React serves as the “V” in the MVC. Our Client tier (View) will be written in
JavaScript, HTML, and CSS, using ReactJS as the framework. This level of the
architecture is what the user will interact with to access the features of our
application.
 With this, we come to the end of this article. in this article, we have discussed
how the traditional MVC architecture is implemented in the very trending MERN
Stack.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 24


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
-------------------------------------------------------------------------------------------------------------------
4. Explain about understanding the [Link]-to-Angular Stack Components

Now that you have the basic structure of the web framework fresh in your mind, it is
time to discuss the [Link]-to-Angular stack. The most common—and we believe
the best—version of this stack is the [Link]-to-Angular stack comprised of
MongoDB, Express, Angular, and [Link].
In the [Link]-to-Angular stack,
 [Link] provides the fundamental platform for development. The backend services
and server-side scripts are all written in [Link].
 MongoDB provides the data store for the website but is accessed via a MongoDB
driver [Link] module.
 The webserver is defined by Express, which is also a [Link] module.
 The view in the browser is defined and controlled using the Angular framework.
 Angular is an MVC framework where the model is made up of JSON or JavaScript
objects, the view is HTML/CSS, and the controller is made up of Angular
JavaScript.

Figure 1.5 Basic diagram showing where [Link], Express, MongoDB, and
Angular fit in the web paradigm

Figure 1.5 provides a basic diagram of how the [Link]-to-Angular stack fits into the
basic website/web application model.
The following sections describe each of these technologies and why they were chosen

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 25


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
as part of the [Link]-to-Angular stack.

4.1. [Link]
 [Link] is a development framework based on Google’s V8 JavaScript
engine. Therefore, [Link] code is written in JavaScript and then compiled
into machine code by V8 to be executed.
 Many of your backend services can be written in [Link], as can the server-
side scripts and any supporting web application functionality.
 The nice thing about [Link] is that it is all just JavaScript, so you can easily
take functionality from a client-side script and place it in a server-side script.
Also, the webserver can run directly within the [Link] platform as a [Link]
module, so it makes it much easier than, say, Apache at wiring up new services
or server-side scripts.
 The following are just a few reasons why [Link] is a great framework to start
from:
 JavaScript end-to-end:
 One of the biggest advantages to [Link] is that it allows you to write both
server- and client-side scripts in JavaScript.
 There have always been difficulties in deciding where to put scripting logic.
 Too much on the client side makes the client cumbersome and unwieldy, but
too much on the server side slows down web applications and puts a heavy
burden on the webserver.
 With [Link] you can take JavaScript written on the client and easily adapt it for
the server and vice versa. Also, your client developers and server developers will
be speaking the same language.
 Event-driven scalability:
 [Link] applies a different logic to handling web requests. Rather than having
multiple
 threads waiting to process web requests, they are processed on the same thread
using a basic event model.
 This allows [Link] webservers to scale in ways that traditional webservers
never can.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 26


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

 Extensibility:
 [Link] has a great following and an active development community. New
modules to extend [Link] functionality are being developed all the time.
 Also it is simple to install and include new modules in [Link], making it easy
to extend a [Link] project to include new functionality in minutes.
Time:
 Let’s face it, time is valuable. [Link] is super easy to set up and develop in. In
only a few minutes, you can install [Link] and have a working webserver.

4.2 MongoDB
 MongoDB is a part of backend services.
 MongoDB is an agile and scalable NoSQL database.
 The name Mongo comes from “humongous.”
 It is basically a scalable NoSQL database. The data is stored in the database as a
form of JSON objects.
 MongoDB provides great website backend storage for high traffic websites that
need to store data such as user comments, blogs, or other items because it is
fast, scalable, and easy to implement.
 [Link] supports a variety of DB access drivers, so the data store could just as
easily be MySQL or some other database.
 However, the following are some of the reasons that MongoDB really fits in the
[Link] stack well:
 Document orientation:
The Data is stored in the document form in the MongoDB.
 High performance:
 MongoDB is one of the highest performing database.
 Especially today when more and more people interact with websites, it is
important to have a backend that can support heavy traffic.
 High availability:
 MongoDB’s replication model makes it easy to maintain scalability while
keeping high performance. That means it creates multiple copies of the

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 27


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
data and sends these copies to a different server so that if one server fails,
then the data is retrieved from another server.
 High scalability:
 MongoDB’s structure makes it easy to scale horizontally by sharing the data
across multiple servers.
 No SQL injection:
 MongoDB is not susceptible to SQL injection (putting SQL statements in web
forms or other input from the browser that compromises the DB security)
because objects are stored as objects, not using SQL strings.

4.3 Express
 Express is used for server side development in full stack.
 As it is running in [Link], it is easy to configure, implement and control the web
application.
 The Express module acts as the webserver in the [Link]-to-Angular stack.
 The fact that it is running in [Link] makes it easy to configure, implement, and
control.
 The Express module extends [Link] to provide several key components for handling
web requests.
 This allows you to implement a running webserver in [Link] with only a few lines
of
code.
For example, the Express module provides the ability to easily set up destination routes
(URLs) for users to connect to.
 It also provides great functionality on working with the HTTP request and response
objects, including things like cookies and HTTP headers.
 The following is a partial list of the valuable features of Express:
 Route management:
Express makes it easy to define routes (URL endpoints) that tie directly to
[Link] script functionality on the server.
 Error handling:
Express provides built-in error handling for documents not found and other
Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 28
----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
errors.
 Easy integration:
An Express server can easily be implemented behind an existing reverse
proxy system such as Nginx or Varnish. This allows it to
be easily integrated into your existing secured system.
 Cookies
Express provides easy cookie management.
 Session and cache management
Express also enables session management and cache management.

4.4 Angular
 Angular is a client-side framework developed by Google.
 It is written in TypeScript.
 Angular provides all the functionality needed to handle user input in the
browser, manipulate data on the client side, and control how elements are
displayed in the browser view.
 The entire theory behind Angular is to provide a framework that makes it easy
to implement web applications using the MVC framework.
 Other JavaScript frameworks could be used with the [Link] platform, such as
 Backbone, Ember, and Meteor. However, Angular has the best design, feature
set, and trajectory at this writing.
 Here are some of the benefits of Angular:
 Data binding: Angular has a clean method to bind data to HTML elements
using its powerful scope mechanism.
 Extensibility: The Angular architecture allows you to easily extend almost every
aspect of the language to provide your own custom implementations.
 Clean: Angular forces you to write clean, logical code.
 Reusable code: The combination of extensibility and clean code makes it easy to
write reusable code in Angular. In fact, the language often forces you to do

so when creating custom services.


 Support: Google is investing a lot into this project, which gives it an advantage over

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 29


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
other similar initiatives.
Compatibility: Angular is based on Type Script, which makes it easier to begin
integrating Angular into your environment and to reuse pieces of

 Your existing code within the structure of the Angular framework.

4.5 REACT JS
 ReactJS is a declarative, efficient, and flexible JavaScript library for building
reusable UI components.
 It is an open-source, component-based front end JavaScript library. This library
responsible only for the view layer of the application. That means this JavaScript
is for building for interfaces.
 It was created by Jordan Walke, who was a software engineer at Facebook.
 It was initially developed and maintained by Facebook and was later used in its
products like WhatsApp & Instagram.
 Today, most of the websites are built using MVC (model view controller)
architecture. In MVC architecture,
 React is the 'V' which stands for view, whereas the architecture is provided by
the Redux or Flux.
 A ReactJS application is made up of multiple components, each component
responsible for outputting a small, reusable piece of HTML code.
 The components are the heart of all React applications. These Components can
be nested with other components to allow complex applications to be built of
simple building blocks.
 ReactJS uses virtual DOM based mechanism to fill data in HTML DOM. The
virtual DOM works fast as it only changes individual DOM elements instead of
reloading complete DOM every time.
 To create React app, we write React components that correspond to various
elements. We organize these components inside higher level components which
define the application structure.
 For example, we take a form that consists of many elements like input fields,
labels, or buttons. We can write each element of the form as React components,

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 30


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
and then we combine it into a higher-level component,
i.e., the form component itself. The form components would specify the
structure
of the form along with elements inside of it.

Why learn ReactJS?


 Today, many JavaScript frameworks are available in the market (like angular,
node), but still, React came into the market and gained popularity amongst
them.
 The previous frameworks follow the traditional data flow structure, which uses
the DOM (Document Object Model).
 DOM is an object which is created by the browser each time a web page is
loaded. It dynamically adds or removes the data at the back end and when any
modifications were done, then each time a new DOM is created for the same
page. This repeated creation of DOM makes unnecessary memory wastage and
reduces the performance of the application. Therefore, a new technology
ReactJS framework invented which remove this drawback.
 ReactJS allows you to divide your entire application into various components.
ReactJS still used the same traditional data flow, but it is not directly operating
on the browser's Document Object Model (DOM) immediately; instead, it
operates on a virtual DOM.
 It means rather than manipulating the document in a browser after changes to
our data, it resolves changes on a DOM built and run entirely in memory. After
the virtual DOM has been updated, React determines what changes made to the
actual browser's DOM. The React Virtual DOM exists entirely in memory and is
a representation of the web browser's DOM.
 Due to this, when we write a React component, we did not write directly to the
DOM; instead, we are writing virtual components that react will turn into the
DOM.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 31


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
5. Outline the trending technologies for full stack developer. Also develop a simple web
based online registration system to register for the cultural events organized by the
students of an education institution using full stack technologies considering client
side and server side components. (April/May-2024)

As a full stack developer, staying up-to-date with the latest technologies and
trends is crucial for building modern, efficient, and scalable applications. Here’s an
outline of trending technologies and tools across different aspects of full stack
development:

Front-End Technologies

1. JavaScript Frameworks/Libraries
o [Link]: A popular library for building user interfaces with a
component-based architecture.
o [Link]: A progressive framework for building UIs, known for its
simplicity and flexibility.
o Angular: A comprehensive framework for building dynamic web
applications with a two-way data binding and a powerful CLI.
2. TypeScript: A superset of JavaScript that adds static typing, improving code
quality and development experience.
3. [Link]: A React-based framework that provides server-side rendering (SSR)
and static site generation (SSG) capabilities.
4. Tailwind CSS: A utility-first CSS framework that allows for rapid styling of
web pages without leaving the HTML.
5. Sass/LESS: CSS preprocessors that add features like variables, nesting, and
mixins to CSS.

Back-End Technologies

1. [Link]: A JavaScript runtime built on Chrome's V8 JavaScript engine,


popular for building scalable network applications.
2. [Link]: A minimal and flexible [Link] web application framework that
provides a robust set of features for web and mobile applications.
3. Django: A high-level Python web framework that encourages rapid
development and clean, pragmatic design.
4. Ruby on Rails: A full-stack Ruby framework that follows the convention over
configuration (CoC) and the DRY (Don't Repeat Yourself) principles.
5. Spring Boot: A Java-based framework that simplifies the development of
production-ready applications with a focus on microservices.
6. FastAPI: A modern, fast (high-performance) web framework for building APIs
with Python 3.6+ based on standard Python type hints.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 32


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
Databases

1. Relational Databases
o PostgreSQL: An advanced, open-source relational database with
strong support for SQL standards and extensions.
o MySQL/MariaDB: Popular relational databases known for their
reliability and performance.
2. NoSQL Databases
o MongoDB: A document-oriented NoSQL database that stores data in
flexible, JSON-like documents.
o Redis: An in-memory key-value store used for caching and real-time
analytics.
3. GraphQL: An API query language that allows clients to request only the data
they need, improving efficiency over traditional REST APIs.

DevOps and Deployment

1. Docker: A platform for developing, shipping, and running applications in


containers, ensuring consistency across different environments.
2. Kubernetes: An orchestration system for automating the deployment,
scaling, and management of containerized applications.
3. CI/CD Tools
o Jenkins: An open-source automation server for building, deploying,
and automating any project.
o GitHub Actions: CI/CD workflows integrated into GitHub, allowing
automation of the software development lifecycle.
4. Cloud Platforms
o AWS (Amazon Web Services): A comprehensive cloud platform offering
a wide range of services for computing, storage, and databases.
o Azure: Microsoft’s cloud computing platform that provides services
similar to AWS with integrations into Microsoft products.
o Google Cloud Platform (GCP): Offers various cloud computing
services, including computing, storage, and machine learning.

Development Tools

1. Version Control
o Git: A distributed version control system for tracking changes in source
code.
o GitHub/GitLab/Bitbucket: Platforms for hosting Git repositories and
collaborating on code.
2. IDEs and Code Editors
o Visual Studio Code: A popular, lightweight code editor with a rich
ecosystem of extensions.
o IntelliJ IDEA: An IDE primarily used for Java development but
supports multiple languages and frameworks.
3. Testing Frameworks

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 33


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
Jest: A JavaScript testing framework maintained by Facebook, suitable
o
for testing React applications.
o Mocha/Chai: JavaScript testing frameworks used for testing [Link]
applications.
o Selenium: A tool for automating web browsers for testing purposes.
4. API Testing
o Postman: A tool for API development and testing that helps to send
requests, view responses, and automate testing.

Emerging Technologies

1. WebAssembly (Wasm): A binary instruction format that allows high-


performance execution of code on web browsers.
2. Serverless Architectures: Cloud services that run code in response to events
and automatically manage the infrastructure.
3. Machine Learning and AI Integration: Tools and frameworks for integrating
machine learning models into applications (e.g., TensorFlow, PyTorch).
4. Progressive Web Apps (PWAs): Web applications that offer a native app-like
experience and can work offline.

Summary

 Front-End: React, [Link], Angular, TypeScript, Tailwind CSS.


 Back-End: [Link], [Link], Django, Ruby on Rails, Spring Boot, FastAPI.
 Databases: PostgreSQL, MySQL, MongoDB, Redis, GraphQL.
 DevOps: Docker, Kubernetes, CI/CD tools (Jenkins, GitHub Actions), Cloud
Platforms (AWS, Azure, GCP).
 Development Tools: Git, GitHub/GitLab/Bitbucket, Visual Studio Code,
IntelliJ IDEA, Jest, Mocha/Chai, Postman.
 Emerging: WebAssembly, Serverless, Machine Learning, Progressive Web
Apps (PWAs).

Staying informed about these technologies and trends can help full stack developers
build more efficient, scalable, and modern applications.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 34


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
[Link] develop a simple web-based online registration system for cultural events,
we'll use a full stack approach. This example will include client-side and
server-side components and will leverage the following technologies:(Nov/Dec-
2024)

 Frontend: HTML, CSS, JavaScript with React


 Backend: [Link] with Express
 Database: MongoDB (using Mongoose for data modeling)
 Authentication: Basic form submission without advanced authentication for
simplicity

Here’s a step-by-step guide to building this registration system:

1. Setup the Project


1. Create the Project Structure

Initialize the Backend

Initialize the Frontend


Backend Development
2. 1. Set Up Express Server

File: server/[Link]

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 35


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 36


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

3. Frontend Development
3.1. Create React Components

File: client/src/[Link]

import React, { useState } from 'react';


import axios from 'axios';

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 37


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
function App() {
const [formData, setFormData] = useState({
name: '',
email: '',
phone: '',
event: ''
});

const handleChange = (e) => {


setFormData({ ...formData, [[Link]]: [Link] });
};

const handleSubmit = async (e) => {


[Link]();
try {
const response = await [Link]('[Link] formData);
alert([Link]);
setFormData({ name: '', email: '', phone: '', event: '' });
} catch (error) {
alert('Registration failed');
}
};

return (
<div className="App">
<h1>Event Registration</h1>
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" name="name" value={[Link]}
onChange={handleChange} required />
</label>
<br />
<label>
Email:
<input type="email" name="email" value={[Link]}
onChange={handleChange} required />
</label>
<br />
<label>
Phone:
<input type="tel" name="phone" value={[Link]}
onChange={handleChange} required />
</label>
<br />
<label>
Event:

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 38


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
<input type="text" name="event" value={[Link]}
onChange={handleChange} required />
</label>
<br />
<button type="submit">Register</button>
</form>
</div>
);
}

export default App;

Run the Application

Start the Backend Server

Output

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 39


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

[Link] is full stack development? Assume that you are assigned the responsibility of
developing online web application for vehicle booking system for jungle safari in
wildlife sanctuaries located in Tamil Nadu. As a web developer clearly explain how to
choose a technology stack for this web application development. Also outline the key
features to be included in the application. (April/May-2024)

Full stack development refers to the practice of developing both the front-end and
back-end parts of a web application. A full stack developer is proficient in working
with all layers of a web application, from the user interface (UI) to the server-side
logic and database management.

Key Components of Full Stack Development

1. Front-End Development:
o Definition: This is the client-side of a web application where users
interact directly with the application. It involves everything that users
see and experience in their web browser.
o Technologies:
 HTML (HyperText Markup Language): The standard language
for creating web pages.
 CSS (Cascading Style Sheets): Used for styling and layout of
web pages.
 JavaScript: A programming language for creating interactive
effects and dynamic content on web pages.
 Front-End Frameworks/Libraries: [Link], [Link], Angular.
2. Back-End Development:

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 40


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
o Definition: This is the server-side of the web application that processes
requests, performs operations, and manages data. It’s responsible for
the application’s logic, database interactions, and server configuration.
o Technologies:
 Programming Languages: JavaScript ([Link]), Python, Ruby,
Java, PHP, C#.
 Frameworks: [Link] ([Link]), Django (Python), Ruby on
Rails (Ruby), Spring Boot (Java).
 Databases:
 Relational Databases: MySQL, PostgreSQL.
 NoSQL Databases: MongoDB, Redis.
 Server Management: Apache, Nginx.
3. Database Management:
o Definition: This involves designing, managing, and querying the
database to store and retrieve data.
o Types:
 Relational Databases: Use SQL for querying data (e.g., MySQL,
PostgreSQL).
 NoSQL Databases: Use flexible data models (e.g., MongoDB,
CouchDB).
4. APIs (Application Programming Interfaces):
o Definition: APIs allow different software components to communicate
with each other. In full stack development, APIs are often used to
connect the front-end to the back-end or to integrate third-party
services.
o Types:
 REST (Representational State Transfer): A common
architectural style for designing networked applications.
 GraphQL: A query language for APIs that allows clients to request
exactly the data they need.
5. DevOps and Deployment:
o Definition: DevOps practices involve automating the development,
deployment, and operations of software applications.
o Technologies:
 Version Control: Git.
 Containerization: Docker.
 Continuous Integration/Continuous Deployment (CI/CD):
Jenkins, GitHub Actions.
 Cloud Services: AWS, Azure, Google Cloud Platform.
6. Security:
o Definition: Ensuring that the web application is secure from threats
and vulnerabilities.
o Practices:
 Authentication and Authorization: Ensuring that users are
who they claim to be and have the right permissions.
 Data Encryption: Protecting data both at rest and in transit.
 Security Best Practices: Implementing secure coding practices
and regular security audits.
Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 41
----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
Skills of a Full Stack Developer

1. Proficiency in Front-End Technologies: Ability to build responsive and


interactive UIs.
2. Understanding of Back-End Technologies: Knowledge of server-side
programming, APIs, and database interactions.
3. Database Management: Ability to design schemas, write queries, and
manage data.
4. API Development: Skill in creating and integrating APIs.
5. DevOps Knowledge: Experience with deployment, monitoring, and
continuous integration.
6. Problem-Solving: Ability to troubleshoot and debug issues across the entire
stack.
----------------------------------------------------------------------------------------------------------------------------
[Link] a vehicle booking system for a jungle safari in wildlife
sanctuaries requires careful selection of a technology stack to ensure the
application is robust, scalable, and user-friendly. Below is a structured
approach to choosing the technology stack and outlining the key features for
the application.(April/May-2024)

Choosing a Technology Stack

1. Requirements Analysis:
o User Requirements: Understand the needs of users, including booking
vehicles, checking availability, and viewing booking history.
o Business Requirements: Determine the needs for administrative
control, reporting, and integration with payment systems.
o Technical Requirements: Consider factors such as scalability,
security, and ease of maintenance.
2. Front-End Technologies:
o [Link]: For building a dynamic and responsive user interface. React’s
component-based architecture allows for reusable UI components and
a smooth user experience.
o [Link]: An alternative to React, known for its simplicity and flexibility.
o Tailwind CSS or Bootstrap: For styling, to create a clean, responsive,
and modern design.
3. Back-End Technologies:
o [Link] with Express: Ideal for handling asynchronous operations and
building a RESTful API to manage bookings, vehicle availability, and
user data.
o Django: A robust Python-based framework offering built-in features
like authentication and an admin interface.
o Spring Boot: If using Java, Spring Boot is a strong choice for building
enterprise-level applications with extensive features.
4. Database:
o PostgreSQL: A relational database that supports complex queries and
transactions. Suitable for managing structured data such as bookings,
user profiles, and vehicle details.
Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 42
----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
o MongoDB: A NoSQL database can be used if you expect flexible schema
designs or need to handle unstructured data.
5. Authentication and Security:
o JWT (JSON Web Tokens): For secure authentication and session
management.
o OAuth: For third-party authentication if you want to support login via
social accounts.
o HTTPS: Ensure all communication between the client and server is
encrypted.
6. Payment Gateway Integration:
o Stripe or PayPal: For handling online payments securely.
7. Deployment and DevOps:
o Docker: Containerize the application to ensure consistency across
different environments.
o Kubernetes: Manage containerized applications with scaling and
orchestration.
o AWS or Azure: Cloud services for hosting the application, managing
databases, and scaling resources.
8. Additional Tools:
o Git: For version control and collaboration.
o CI/CD Tools: Jenkins, GitHub Actions, or GitLab CI/CD for automated
testing and deployment.

Key Features to Include

1. User Features:
o User Registration and Login: Secure user authentication and account
management.
o Search and Filter: Users can search for vehicles based on type,
availability, and dates.
o Booking System: Users can book vehicles, select pickup and drop-off
points, and choose safari packages.
o Real-Time Availability: Check vehicle availability in real-time.
o Payment Integration: Secure online payment gateway for booking
payments.
o Booking History: View and manage past and upcoming bookings.
o Notifications: Email/SMS notifications for booking confirmations and
reminders.
2. Admin Features:
o Dashboard: Overview of bookings, vehicle availability, and user
statistics.
o Vehicle Management: Add, update, and delete vehicle listings. Manage
vehicle details and availability.
o Booking Management: View and manage all bookings, including
cancellation and modifications.
o Reporting and Analytics: Generate reports on bookings, revenue, and
user activity.
3. Operational Features:
Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 43
----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
o Location Integration: Map integration to show vehicle pickup and
drop-off points.
o User Feedback: Allow users to leave reviews and ratings for vehicles
and services.
o Accessibility: Ensure the application is accessible to all users,
including those with disabilities.
o Scalability: Design the application to handle increasing traffic and
bookings as the user base grows.
---------------------------------------------------------------------------------------------------------------------------------
[Link] in detail about web development stacks and their roles in building web
functional web applications. (7) Nov/Dec-2024)

What Is a Web Development Stack?

A web development stack is a combination of technologies, frameworks, and tools


used to build both the frontend (client side) and backend (server side) of a web
[Link] stack typically includes:

 A Frontend framework/library
 A Backend framework
 A Database system
 Sometimes a runtime environment, server, or middleware

Full-Stack Example: MERN Stack

MERN stands for:

 MongoDB – Database
 [Link] – Backend framework
 React – Frontend library
 [Link] – Runtime environment for JavaScript on the server

Let’s break down the roles of each:

1. Frontend (React)

What the user sees and interacts with

 Built using React, a JavaScript library for building dynamic UIs.


 It handles routing (via React Router), component-based architecture, and state
management (Redux, Context API, etc).
 It communicates with the backend via HTTP requests (e.g., fetch() or axios).

Role:

 Render user interfaces


 Handle client-side navigation
 Send/receive data from backend APIs
Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 44
----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
2. Backend Framework ([Link])

Handles logic, routing, and API services

 [Link] is a minimal [Link] framework for building APIs and server-side


routes.
 It receives requests from the frontend and processes them (e.g., authenticate user,
fetch data from database).

Role:

 Define RESTful API endpoints (e.g., POST /login, GET /products)


 Implement business logic
 Perform server-side validation

3. Runtime Environment ([Link])

JavaScript running on the server

 [Link] allows developers to write backend code in JavaScript, which


traditionally runs only in browsers.
 It uses a non-blocking, event-driven architecture—great for building scalable
applications.

Role:

 Execute server-side JS code


 Manage I/O operations like file handling, networking, and database access
 Run the Express app

4. Database (MongoDB)

Stores application data

 MongoDB is a NoSQL database that stores data as JSON-like documents.


 It integrates easily with [Link] through the mongoose or mongodb libraries.

Role:

 Store user accounts, posts, transactions, etc.


 Allow reading, updating, deleting documents via backend logic

How These Parts Work Together?

Let’s say you build a task manager app using MERN:

1. User visits your site → React app loads in the browser


2. User logs in → React sends a POST request to /login (Express API)
Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 45
----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
3. Express receives the request → checks the credentials from MongoDB
4. If successful, backend responds with a token → frontend stores it
5. User creates a task → React sends POST /tasks with task data
6. Express validates the data → saves it in MongoDB
7. React updates the UI based on the response

Other Common Web Development Stacks

Stack Frontend Backend Database Notes


Traditional stack; great for
LAMP HTML/CSS/JS PHP MySQL
CMS like WordPress
MEVN [Link] [Link] MongoDB Vue instead of React in MERN
Django HTML/CSS/JS or Django PostgreSQL / High-level, batteries-included
Stack React (Python) SQLite Python framework
Ruby on HTML/CSS/JS or PostgreSQL /
Rails (Ruby) Convention over configuration
Rails React MySQL

Why Use a Full Stack?

 Seamless communication between front and back


 Easier to manage by full-stack developers
 Efficient development with shared data models and APIs

A web development stack provides structure and division of responsibilities for


building apps. A typical stack:

 Frontend: Engages users


 Backend: Processes data and logic
 Database: Stores persistent information

Runtime/Server: Executes backend logic and serves content

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 46


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

[Link] and contrast between MEAN stack and MERN Stack (6) Nov/Dec-2024)

Web development is a procedure or process for developing a website. A website


basically contains three ends: the client side, the server side, and the database.
These three are different sides of an application that combine together to deliver an
application; all ends are implemented separately with different technologies. MEAN
and MERN are the technologies responsible for developing all ends of a web
application. Also, this kind of development is called full-stack development. These
stacks contain tools and technologies to build a web application at all ends.

MEAN Stack

Mean stack stands for Mongo DB, Express JS, Angular, and Node JS. It is a set of
these technologies that are used to develop each end of a web application. Further
details about these technologies are given as follows:

 Mongo DB : Its a database which is using BSON format to store data.


 Express JS : Its a framework of JavaScript which enables developer to
establish server.
 Angular : Angular is client side framework which is used to develop User
Interface.
 Node JS :Node JS is a run time environment of JavaScript which allows
developer to execute JS code directly in console

Working of MEAN Stack:

Angular handles the implementation of the user interface (UI). Whenever the UI
requires data, it sends a request to the server, prompting the server to retrieve the
necessary information from MongoDB. Once the server successfully locates the
required data, it sends the response back to the client side.

Advantages of MEAN Stack:


 Whole technologies requires only JavaScript to implement programs.
 Improved re-usability of code.
 Easy to learn.

MERN Stack

Mern stack stands for Mongo DB, Express JS, React JS, and Node JS. It is a set of
these technologies that are used to develop each end of a web application. Further
details about these technologies are given as follows:
Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 47
----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

 Mongo DB : Its a database which is using BSON format to store data.


 Express JS : Its a framework of JavaScript which enables developer to
establish server.
 React JS : React JS is client side library of JavaScript which is used to
develop User Interface.
 Node JS :Node JS is a run time environment of JavaScript which allows
developer to execute JS code directly in console

Working of MERN Stack:

Just like in the MEAN stack, in this stack, we will utilize React JS for the frontend.
React JS will be responsible for initiating requests to the server to facilitate specific
data exchanges.

Advantages of MERN Stack:

 React Router provides client side navigation.


 It enables user to implement single pager application.
 All technologies in this stack requires only JavaScript.
 East to learn & explore.
 It enables user to implement real time applications.

Difference between MEAN and MERN stacks:

[Link] MEAN Stack MERN Stack

It's technology stack


It's technology stack
comprises of MongoDB,
1 comprises of MongoDB,
Angular, Express and
React, Express and Node.
Node.

It is a javascript
2 It is open source JS library.
framework.

It uses Typescript
3 It uses JavaScript, JSX.
language.

It offers better
4 Its offers low productivity.
productivity.

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 48


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester

[Link] MEAN Stack MERN Stack

Its learning curve is It offers far better


5
steep. documentation.

It helps in managing It facilitates smooth


6
and rendering the code. rendering.

It's flow of data is It's flow of data is


7
bidirectional. unidirectional.

It does not support It supports mobile


8
mobile application. application.

11. Develop a simple online system to book a slot for vehicle water washing. Assume that
the carriage as facilities to wash only four wheeler vehicle and it can house maximum of
three of vehicles only. Send a confirmation SMS and service completion SMS to the
registered mobile number after successful booking and completion of water washing. Use
suitable full stack technologies to implement the above system considering client-side
and server-side components. Also summarize the reasons for selecting particular
technologies for development.(April/May-2025)

System Features

 Users can book a slot for water washing for a four-wheeler.


 Maximum of three vehicles can be accommodated at the same time.
 SMS notifications sent:
o ✅ After successful booking
o ✅ After service completion

Client-Side ([Link])

Key Components:

 Booking Form: Inputs for vehicle details, date/time, mobile number


 Availability Checker: Validates open slots
 Confirmation Page

jsx
// Sample React booking form snippet

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 49


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
<form onSubmit={handleSubmit}>
<input type="text" name="vehicleModel" placeholder="Vehicle Model" required />
<input type="datetime-local" name="bookingTime" required />
<input type="text" name="mobileNumber" placeholder="Mobile Number" required />
<button type="submit">Book Slot</button>
</form>

Server-Side ([Link] + Express)

Routes:

 POST /book-slot: Checks availability, saves booking, sends confirmation SMS


 POST /complete-service: Updates status, sends completion SMS

javascript
// Twilio SMS sending example
const twilio = require('twilio');
const client = new twilio(accountSid, authToken);

[Link]({
body: 'Your vehicle washing is booked successfully!',
to: userPhone,
from: 'YourServiceNumber'
});

Database Schema (MongoDB)

json
{
"vehicleModel": "Hyundai i20",
"bookingTime": "2025-07-15T[Link]",
"mobileNumber": "+911234567890",
"status": "booked"
}

[Link] a weh based online registration system to register state level athletic events organized by
the Government of Tamil Nadu Perform the following operations in dashboard.
(i) Create a new event registration.
(ii) Delete the registration
(iii) Update the registration.(April/May-2025)

MongoDB is excellent for this kind of flexible, evolving schema.

Directory Structure
project/
├── client/ # React frontend
└── server/ # Express backend
🚀 Backend ([Link] + Express + MongoDB)
server/[Link]

const express = require("express");


const mongoose = require("mongoose");
const cors = require("cors");

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 50


----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
const app = express();
[Link](cors());
[Link]([Link]());

[Link]("mongodb://localhost:27017/athleticEvents");

const RegistrationSchema = new [Link]({


name: String,
age: Number,
contact: String,
event: String
});
const Registration = [Link]("Registration", RegistrationSchema);

// Create
[Link]("/register", async (req, res) => {
const registration = new Registration([Link]);
await [Link]();
[Link]({ message: "Registration created", data: registration });
});

// Update
[Link]("/register/:id", async (req, res) => {
const updated = await [Link]([Link], [Link], { new:
true });
[Link]({ message: "Registration updated", data: updated });
});

// Delete
[Link]("/register/:id", async (req, res) => {
await [Link]([Link]);
[Link]({ message: "Registration deleted" });
});

// Get all
[Link]("/register", async (req, res) => {
const registrations = await [Link]();
[Link](registrations);
});

[Link](5000, () => [Link]("Server running on port 5000"));


Frontend ([Link])
📁 client/src/[Link]

import React, { useEffect, useState } from "react";


import axios from "axios";

function App() {
const [registrations, setRegistrations] = useState([]);
const [form, setForm] = useState({ name: "", age: "", contact: "", event: "" });

const loadRegistrations = async () => {


const res = await [Link]("[Link]
setRegistrations([Link]);
};

const handleSubmit = async () => {


await [Link]("[Link] form);
setForm({ name: "", age: "", contact: "", event: "" });
Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 51
----- IT3501-FULL STACK DEVELOPMENT UNIT-I BASICS OF FULLSTACK III Year IT/V Semester
loadRegistrations();
};

const handleDelete = async (id) => {


await [Link](`[Link]
loadRegistrations();
};

const handleUpdate = async (id) => {


await [Link](`[Link] form);
setForm({ name: "", age: "", contact: "", event: "" });
loadRegistrations();
};

useEffect(() => {
loadRegistrations();
}, []);

return (
<div>
<h2>Event Registration</h2>
<input placeholder="Name" value={[Link]} onChange={e => setForm({...form, name:
[Link]})} />
<input placeholder="Age" value={[Link]} onChange={e => setForm({...form, age:
[Link]})} />
<input placeholder="Contact" value={[Link]} onChange={e => setForm({...form,
contact: [Link]})} />
<input placeholder="Event" value={[Link]} onChange={e => setForm({...form,
event: [Link]})} />
<button onClick={handleSubmit}>Register</button>

<h3>Dashboard</h3>
{[Link](reg => (
<div key={reg._id}>
<p>{[Link]} - {[Link]}</p>
<button onClick={() => handleUpdate(reg._id)}>Update</button>
<button onClick={() => handleDelete(reg._id)}>Delete</button>
</div>
))}
</div>
);
}

export default App;

Prepared By: [Link], AP/IT MAILAM ENGINEERING COLLEGE 52


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

UNIT II NODE JS
Basics of Node JS – Installation – Working with Node packages – Using Node
package manager – Creating a simple [Link] application – Using Events –
Listeners –Timers - Callbacks – Handling Data I/O – Implementing HTTP
services in [Link]

PART-A - Two marks questions and Answers


1. What is [Link]? Give its uses.
Node JS is an open source technology for server. Using [Link] we can run
JavaScript on server.
It can perform various tasks such as
1) It can create, open, read, delete, write and close files on the server.
2) It can collect form data.
3) It can also add, delete, modify data in databases.
4) It generate dynamic web pages.
2. What is NPM? Write a short notes on a Node Package Manager (Nov/Dec-
2024)(April/May-2025)
The NPM stands for Node Package Manager. NPM consists of two main parts:
1) A CLI (command-line interface) tool for publishing and downloading
packages,
2) An online repository that hosts JavaScript packages.
3. Explain the ues of ‘cluster’ module in [Link]
The cluster module helps in creating a child process. Both the main and child
processes can run simultaneously and share the same server port.
4. Explain the [Link] statement in [Link] with suitable example.
[Link]([data]|, ...]): It is used for printing to stdout with newline. This
function can take multiple arguments similar to a printf statement in C.
For Example-
var emp_name = ‘Ankita',
emp depts ={dept1: 'Sales, dept2: 'Accounts'
};[Link] (Name: %s'+\n'+ Departments: %j,emp name, emp depts);

Prepared by: [Link] , AP/IT MAILAM ENGINEERING COLLEGE 5


3
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

5. What is Event Emitter?


The emitter objects performs following tasks -
1) It emits named events.
2) Registed and unregisted listener functions.
 Basically EventEmitter is a class which can be used to raise and
handle custom events.
6. What is the purpose of addlistener method?
Adds a listener to the end of the listeners array for the specified event. No
checks are made to see if the listener has already been added.
7. Explain the setMaxListener and getMaxListener methods of [Link]
List and mention the purpose of any four timer methods in node js
(April/May-2023)
1. setMaxListeners(int): This method sets the number of listeners to the
particular event. By default, a maximum of 10 listeners can be registered
for any single event.
2. getMaxListeners(): It will return the max listeners value set by Or default
value 10.
3. setMaxListeners()
8. Explain the setTimeout function in [Link] with suitable example.
This function is used to set one time callback after delaying by some
milliseconds.
Syntax
setTimeout(function,delay_in_milliseconds)
Example Code
console log("Task1");
setTimeout(function()
{[Link] ("Taks2: Executing After 4 seconds") },4000);
console. log("Task3');

Prepared by: [Link] , AP/IT MAILAM ENGINEERING COLLEGE 5


4
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

9. How callback functions are handled in [Link]?


What are callbacks in [Link]?(Nov/Dec-2023).
What are callback in [Link] (April/May-2024)

Callbacks is a function which is usually passed as an argument to another


function and it is usually invoked after some kind of event.
var fs = require("fs");
[Link]('Serving User1")
fs. IeadFile('[Link], function (err, data) {
if (err) return [Link](err);
[Link]("* Contents of the File are.
[Link]([Link] ();
console. log(Serving User2)
[Link]('Serving User3"):
[Link](Good Byell");

10 What is pipe operation in [Link].


The pipe operation is a kind of operation in which output of one stream
acts as an input of another stream. There is no limit on pipe operation that
means, all the output of one stream can be fed as input to another stream.
[Link]
var fs= require(fs' );
var rs = [Link]');
[Link] ('utf8');
var ws = [Link]('[Link]');
[Link]('utf8");
[Link](ws);
[Link]('Data is transfered from '[Link] to '[Link]’

11. What is QueryString?


The query string specifies the parameters of the data that is being queried
from a website's database. Each query string is made up of a parameter and a
value joined by the equals (=) sign. In case of multiple parameters, query strings

Prepared by: [Link] , AP/IT MAILAM ENGINEERING COLLEGE 5


5
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

are joined using the ampersand (&) Sign. The parameter can be a number,
string, encrypted value or any other form of data on the database.

12. Explain the use of ClientRequest object.


ClientRequest object is used to monitor and handle the response from
the [Link] implementing the ClientRequest object the call to the
[Link]() is made. The syntax to this method is as follows-
[Link](options,callback)

13. Explain the incomingMessage object.


The IncomingMessage object is created either by HTTP server or the HTTP
client When this object is used at the server side, the client request is
represented by the Incoming Message object.
 When this object is used at the client side, the server response is
represented by the IncomingMessage object.
 The Incoming Message implements Readable stream. Using this object
client request server response is read as a streaming source.
14. List the primitive types in [Link] (Nov/Dec-2023)
1. Boolean 4. Undefined
2. String 5. NULL
3. Boolean 6. infinity and
7. Symbol
15. What is an Event in Node js? ( April/May -2024)
Every time when a user interacts with the webpage, an event occurs when the
user clicks the mouse button or presses some key on the keyboard.
When events are triggered, some functions associated with these events get
executed.

Prepared by: [Link] , AP/IT MAILAM ENGINEERING COLLEGE 5


6
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

[Link] between event callbacks and threaded Models in [Link]


(Nov/Dec-2024)

In [Link], event callbacks and threaded models represent two distinct approaches to
handling concurrency and asynchronous operations. Here's a concise comparison:

1. Event Callbacks

 Definition: A core feature of [Link], where asynchronous operations are handled


using event-driven programming. Functions (callbacks) are executed when specific
events occur.
 Mechanism: Relies on the event loop and non-blocking I/O.
 Advantages:
o Lightweight and efficient for I/O-bound tasks.
o Scales well with high-concurrency applications.
o Simplifies handling of asynchronous operations using patterns like Promises
or async/await.
 Disadvantages:
o Callback Hell: Nested callbacks can make code harder to read and maintain.
o Single-threaded: CPU-intensive tasks can block the event loop, reducing
performance.

2. Threaded Models

 Definition: Uses worker threads (introduced in [Link] v10.5.0) to execute tasks in


parallel, leveraging multiple threads for CPU-intensive operations.
 Mechanism: Spawns separate threads for heavy computations, offloading work from
the main thread.
 Advantages:
o Ideal for CPU-bound tasks like data processing or machine learning.
o Prevents blocking the event loop, ensuring responsiveness.
o Can utilize multi-core processors effectively.
 Disadvantages:
o Higher memory usage due to thread overhead.
o More complex to implement and manage compared to event callbacks.
o Communication between threads requires message passing, which can
introduce latency.
Prepared by: [Link] , AP/IT MAILAM ENGINEERING COLLEGE 5
7
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester
When to Use Each

 Event Callbacks:
o Best for I/O-bound tasks (e.g., file operations, database queries, API calls).
o Suitable for real-time applications like chat apps or streaming services.
 Threaded Models:
o Ideal for CPU-intensive tasks (e.g., image processing, cryptography).
o Useful when you need to leverage multi-core systems for parallel processing.
In summary, event callbacks are the backbone of [Link] for handling asynchronous I/O
efficiently, while threaded models provide a way to handle CPU-heavy tasks without
blocking the event loop. The choice depends on the nature of your application and the type
of workload it handles.

[Link] [Link]() method with an example(APRIL/mAY-2025)

we've imported the HTTP module, it's time to use its createServer() method to
create an instance of an HTTP server. This method returns an [Link] object,
which we can configure to handle incoming requests and send responses.

Prepared by: [Link] , AP/IT MAILAM ENGINEERING COLLEGE 5


8
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

PART B
1. Write about basics of [Link] in detail.
[Link] is a JavaScript runtime environment that runs on the Chrome V8 engine
and is used for server-side scripting. It takes requests from users, processes those
requests, and returns responses to the corresponding users.
What is [Link]?
 [Link] is an open source technology for server.
 Using [Link] we can run JavaScript on the server.
 [Link] runs on various platforms such as Windows, Linux, Unix, Mac OS.
What Can [Link] Do?
 [Link] can create, open, read, write, delete, and close files on the server
 [Link] can generate dynamic web page content
 [Link] can collect form data
 [Link] can add, delete, modify data in your database
Features of [Link]
Following are some remarkable features of [Link] -
a. Non-blocking thread execution
Non-blocking means while we are waiting for a response for
something during our execution of tasks, we can continue
executing the next tasks in the stack.
b. Efficient
The [Link] is built on V8 JavaScript engine and it is very
fast in code execution.
c. Open source packages
The Node community is enormous and the number of
permissive open source projects available to help in
developing your application in much faster manner.
d. No buffering
The [Link] applications never buffer the data.
e. Single threaded and highly scalable
[Link] uses a single thread model with event looping.
Similarly, the non-blocking response of [Link] makes it
highly scalable to sever large number of requests.

-------------------------------------------------------------------------------------------------------------------

Prepared by: [Link] , AP/IT 59


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

2. How to Installation the [Link] and execute the simple [Link] program
Illustrate creating, publishing and installing [Link] packaged modules with
suitable example ( April/May-2024)
 For executing the [Link] scripts we need to install it. we can get it downloaded
from [Link]
 The installation can be done on Linux or windows OS. It has very simple
installation procedure.

Prepared by: [Link] , AP/IT 60


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

 Click Next button to read and accept the License Agreement and the click
install. It will install [Link] quickly on your computer. Finally, click finish to
complete the installation.
 Verify installation
 In order to verify the installation, we have to pen a command prompt and type
the following command-

Prepared by: [Link] , AP/IT 61


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

 If the [Link] successfully installed, then some version number of the [Link]
which you have installed, then some version number of the [Link] which you
have installed in your PC will be displayed.
 After successful installation we can now execute the [Link] document. The
[Link] file has [Link]

Following is a simple [Link] program which can be written in notepad.


 Create a new folder in the of NodeJsexamples in concern drive.
 Goto notepad, create a new file, then save as in the name of [Link]

[Link]
[Link]("Welcome to first [Link] Application program");

 run the above program in command prompt with the command node [Link]

Prepared by: [Link] , AP/IT 62


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

-------------------------------------------------------------------------------------------------------------
3. Write about Working with node Packages
 A node packaged module is a packaged library that can be easily shared, reused
and installed in different projects.
 The node packages include a [Link] file that defines the packages.
 The [Link] is an important file of any node project. It records the
important metadata about a [Link] [Link] file consists of-
 name: The name of the application/project.
 version: The version of application. The version should follow sematic versioning
rules.
 description: The description about the application, purpose of the application,
Technology used like React, MongoDB, etc.
 main: This is the entry/starting point of the app. It specifies the main file of the
application that triggers when application starts. Application can be started
using npm start.
 scripts: The scripts which need to be included in the application to run
properly.
 engines: The versions of the node and npm used. These versions are specified
in ease the application is deployed on cloud like heroku or google-cloud.
 keywords: It specifies the array of strings that characterizes the application.
 author: It consists of the information about the author like name, email and
other author related information.
 license: The license to which the application confirms is mentioned in this key-
value pair. 
---------------------------------------------------------------------------------------------------------------------
4. Explain about Using Node Package Manager with their various command line
option that npm uses.(April/May-2025)
 A package in [Link] contains all the files you need for a module.
 Modules are JavaScript libraries you can include in your project.
 The NPM stands for node package manager.
 NPM consists of two main parts:
l) A CLI (command-line interface) tool for publishing and
downloading packages.
2) An online repository that hosts JavaScript packages.

Prepared by: [Link] , AP/IT 63


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

 NPM gets installed along with the installation of [Link]. To verity the presence
of npm package on your machine install following command –

Prepared by: [Link] , AP/IT 64


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

There are various command line options that npm uses. These options are as follows -
Option Purpose Example
install Installs the packages either using a npm install express.
[Link] or from the repository or npm install.
from a local location.
Search Searches the module packages in the npm search express.
repository.
install -g Installs the package globally. npm install express -g.
remove Removes the specific module. npm remove express.
View Displays the module details. npm view express.
Publish Publishes the module defined by a npm publish.
[Link] file to registry.
unpublish Unpublished the module which is npm unpublish
published already. testModule
Owner Manages the ownership of published
packages.
ls: List all the users who have access to npm owner Is
modify a package and push new <package-spec>
versions, Handy when you need to know
who to bug for help.
add: Add a new user as a maintainer of a npm owner add<user>
package. This user is enabled to modify <package-spec>
metadata, publish new versions and add npm owner rm <user>
other owners. <package-spec>
rm: Remove a user from the package
owner list. This immediately

Table 2.1 various command line options that npm uses

Prepared by: [Link] , AP/IT 65


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

5. Give the detail about JSON.

What is JSON?
 JSON stands for JavaScript Object Notation
 JSON is a lightweight data-interchange format
 JSON is plain text written in JavaScript object notation
 JSON is used to send data between computers
 JSON is language independent
 The JSON syntax is derived from JavaScript object notation, but the JSON
format is text only.
 Code for reading and generating JSON exists in many programming languages.
Why Use JSON?
The JSON format is syntactically similar to the code for creating JavaScript objects.
Because of this, a JavaScript program can easily convert JSON data into JavaScript
objects.
JSON Syntax Rules
JSON syntax is derived from JavaScript object notation syntax:
 Data is in name/value pairs
 Data is separated by commas
 Curly braces hold objects
 Square brackets hold arrays
JSON
{"name":"John"}
Both JSON and XML can be used to receive data from a web server.
The following JSON and XML examples both define an employees object, with an array
of 3 employees:

JSON Example
{"employees":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}
XML Example

Prepared by: [Link] , AP/IT 66


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>

JSON is Like XML Because


 Both JSON and XML are "self describing" (human readable)
 Both JSON and XML are hierarchical (values within values)
 Both JSON and XML can be parsed and used by lots of programming languages
 Both JSON and XML can be fetched with an XMLHttpRequest

JSON is Unlike XML Because


 JSON doesn't use end tag
 JSON is shorter
 JSON is quicker to read and write
 JSON can use arrays

The biggest difference is:


XML has to be parsed with an XML parser. JSON can be parsed by a standard
JavaScript function.

Why JSON is Better Than XML


XML is much more difficult to parse than JSON.
JSON is parsed into a ready-to-use JavaScript object.

For AJAX applications, JSON is faster and easier than XML:


Using XML
 Fetch an XML document

Prepared by: [Link] , AP/IT 67


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

 Use the XML DOM to loop through the document


 Extract values and store in variables
Using JSON
 Fetch a JSON string
 [Link] the JSON string

JSON Objects
Values in JSON can be objects.
Example
{
"employee":{"name":"John", "age":30, "city":"NewYork"}
}

Using [Link]
All Node modules must include a [Link] file in their root directory. The
[Link]
file is a simple JSON text file that defines the module including dependencies. The
package.
json file can contain a number of different directives to tell the Node Package Manager
how to handle the [Link] following is an example of a [Link] file with a
name, version, description, and dependencies:
{
"name": "my_module",
"version": "0.1.0",
"description": "a simple [Link] module",
"dependencies" : {
"express" : "latest"
}
}

Prepared by: [Link] , AP/IT 68


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

6. How to Installing node Package Modules.


Illustrate creating, publishing and installing [Link] packaged modules with
suitable example ( April/May-2024)

for installing any [Link] module we have to use the install [Link] example-
node

Example of using the existing module


Step1: We will install the module upper-case by issuing the install command

Prepared by: [Link] , AP/IT 69


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Step2: You can locate this module inside the folder nodeJsexamples.
[Link]
var upp_ch = require('upper-case');
[Link](upp_ch.upperCase('i am proud of you"));
Output

Usin [Link](Use of npm init)


We can create a own package using following steps
Step 1
Create a folder as a name of nodeJsexamples.
Open in command prompt Run the command npm [Link] raises

Prepared by: [Link] , AP/IT 70


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Prepared by: [Link] , AP/IT 71


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Step2: Now fill the information about the

packages
Once you execute the above commands, the [Link] gets created.

Prepared by: [Link] , AP/IT 72


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Prepared by: [Link] , AP/IT 73


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

7. Write about [Link] Built in Modules


Module is nothing but the set of functions that can be used in our application.
[Link] has various built in modules that can be used in our application without any
installation.
To include the module, we use require() function with the name of the module. Let us
discuss some important built-in modules.

(1) assert
This module is used during the testing of expressions. If an expression evaluates to 0
or
false, an error is thrown and the program gets terminated.

Step 1 : Open Notepad and create a .js file as follows. I have created an application
using the name [Link]. Here is the code.

[Link]
var assert = require(‘assert’);
assert(10 <2);

Step 2 : Now, open the command prompt and issue the [Link] [Link]

Output is

Prepared by: [Link] , AP/IT 74


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

• Note that as the 10 is not less than 2, the above code will raise the error names
Assertion Error.

(2) Cluster

The cluster module helps in creating a child process. Both the main and child
processes
can run simultaneously and share the same server port.

Let us see its use with the help of


a demo example.
Step 1 : Open Notepad and create a js file as follows. I have created an application
using h.
name

[Link].

var cluster = require(‘cluster’);


if ([Link]) {
[Link](‘Child Process');
[Link]('Main Process');
[Link]();
[Link]();
[Link]);

}
Step 2: Now, open the command prompt and issue the command.
Output is

C:\Node JSExamples\modules>node [Link]


Main Process
Child Process
Child Process
Child Process

(3) OS
The os module provides information about the operating system of your computer.
and create a [Link] file as follows,
[Link]

Prepared by: [Link] , AP/IT 75


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

var os = require(‘os’);
[Link]("Platform on My Computer: + [Link]());
[Link](“Architecture of My Computer:" + [Link]()):
Output is

E: \NodeJSExamples\modules>node [Link]
Platform on My Computer: win32
Architecture of My Computer: X64

8. Write about Creating a Simple [Link] Application with an example

The console object is a global object which is used to print different levels of
messages to stdout and stderr.

The most commonly used methods console object are


1. [Link]
2. [Link],
3. [Link] and
4. [Link].

Let us discuss them with illustrative examples,


1) [Link]([data][,..]) :
 It is used for printing to stdout with newline.
 This function can take multiple arguments similar to a printf statement in
C.

[Link]
var emp name ='Ankita’,
application using the
emp_depts = {
dept1:'sales', dept2: 'Accounts’
};
[Link]('Name: %s'+\n'+ Departments: %j',emp_name, emp depts);
2) [Link]([data][, ..]) : This method is similar to [Link].
[Link]

Prepared by: [Link] , AP/IT 76


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

var emp namne = Ankita',


emp_depts= {
dept1: 'Sales,
dept2: 'Accounts'};
[Link](Name: %s' +\n'+ Departments: %j,emp name, emp_depts);
Output

Name: Ankita
Departments: ("dept1":"Sales","dept2":"Accounts'}
3) [Link] ([data][,..]) : This method prints to stderr with newline
[Link]
var code = 401
[Link](Error!!!, code)
Output is

Error!!! 401
4) [Link](([data][,..]) :This method is similar to [Link]() method.
Consider following example - In which using the fs module we open a text file. If
the file does not open successfully then [Link]() method displays the
warning message.
[Link]
var fs = require(ís');
[Link]('[Link]",'r,function(er,fs)(
Output
if(err)
[Link](err);
else
Output
console. log('File opening successful!!");

----------------------------------------------------------------------------------------------------

Prepared by: [Link] , AP/IT 77


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

9. Give the concept of using events in [Link]


Explain event-driven, blocking and non-blocking I/O model in
Node JS.(Nov/Dec-2023)
Explain event-driven, non- blocking model in [Link] with suitable example.
(April/May -2024)
Event-driven programming is a programming paradigm in which the flow of
the program IS determined by events such as user actions (mouse clicks, key
presses). sensor outputs. or messages from other programs/threads.

Fig. 2.1 Event driven architecture in [Link]


What is an Event?

• Every time when a user interacts with the webpage, an event occurs when the
user clicks the mouse button or presses some key on the keyboard.

▪ When events are triggered, some functions associated with these events get
executed.
▪ Event driven programming makes use of the following concepts -
▪ When some events occur, an event handler function is called. This is basically a
call back function.

▪ The main program listens to every event getting triggered and calls the
associated event handler that event.

Concept of Event Emitter


The Even emitter is a module that facilitates communication between objects.
The emitter objects perform following tasks-
1) It emits named events.
2) Registed and unregisted listener functions.
Basically EventEmitter is a class which can be used to raise and handle custom
events.

Prepared by: [Link] , AP/IT 78


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Following are some commonly used methods of EventEmitter class.


Method Purpose
on(event, listener) This function adds the listener function to the end of the
listeners array for the specified event.
once(event, listener) Adds a one-time listener for the event. This listener is
invoker only the next time the event is fired, after which
it is removed

emit(event, [arg1], [arg2], Raise the specified events with the supplied arguments.
[...)

Table 2.2 some commonly used methods of EventEmitter class.

Steps for using event handling in [Link]


Step 1: import the 'events' module and create an instance of it using following code -
var events = require('events');
Step2 :Then create an instance of EventEmitter( ) class. This instance is created
because we have to call on() and emit() functions using this instance.
Step3 : Then define a callback function which should be called on occurrence of an
event, This function is also called as event listener function.
Step4: Then register the event using the on() function. To this function name of the
even callback function is passed as arguments.
Step5: Finally raise the event using the emit() function.
Example Code
[Link]
cd..cd
Output
D:|NodeJSExamples>node
eventDemo!.js When event occurs, My
Function is called.

program Explanation: In above program,


l ) We have to import the 'events' module.

Prepared by: [Link] , AP/IT 79


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

2) Then we create an object of the EventEmitter class.


3) For specifying the event handler function, we need to use the on() function.
4) The on() function requires two parameters - Name of the event to be handled
and the callback function which is called when an event is raised.
5) The emit() function raises the specified event.
Example code for passing data along with event
We can pass some data inside the event, following example illustrate the
same -
[Link]
// get the reference of EventEmitter
class of events module var events =
require('events');
//create an object of EventEmitter class by
using above eference var em = new
[Link]();
var myfunction = function(data1,data2) {
[Link]("When event occurs, My
Function is called"); [Link]("Data
passed is: "+datal+" "+data2);//Bind
FirstEvent with myfunction
[Link](‘FirstEvent , myfunction);

// Raising FirstEvent

Output
D:\NodeJSExamples>node [Link]
When event occurs, My Function is
called
Data passed is: datal data2

Prepared by: [Link] , AP/IT 80


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Concept of Event Loop


 Node js is a Single threaded stem. So It executes the next task only
after completion previous task .
 The event loop allows [Link] to perform non-blocking I/O
operations evenif the JavaScript is single threaded.
 Event loop is an endless loop which waits for tasks, executes these
tasks and sleeps until it receives next task.
 The event loop allows us to use callback functions.
 The event loop executes task from event queue only when the call
stack is empty. Empty call stack means there is no ongoing task.
 Event loop makes execution fast.
Event Loop Execution Model

Fig. 2..2 Event loop execution


 The Event Loop is a main loop running continuously for executing the
callback functions. When an async function executes, the callback
function is pushed into the queue. The JavaScript engine doesn't start
processing the event loop until the code after an async function has
executed.
Example code
[Link](“Task1”);
[Link](“Task2”);
settimeout(function(){ [Link](“Task3”) }.1000);
[Link](“Task4”);
Output
D:\NodeJSExamples> node [Link]
Task1
Task2
Task3
Task4

Prepared by: [Link] , AP/IT 81


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Phases of Event Loop


Various phases of event loop are –

Fig 2.3 Phases of Event Loop


1) Timers:
This is the first phase in the event loop. It finds expired timers in every
iteration (also known as Tick) and executes the timers callbacks created by
setTimout and setlnterval.
2) Pending callbacks:
It handle I/O callbacks deferred to the next iteration, such as
handling TCP socket connection error.
3) Idle, prepare : It is used internally.
4) Poll:
The Poll phase calculates the blocking time in every iteration to handle to
callbacks.
5) Check :
This phase handles the callbacks scheduled by setImmediate(), and the
callbacks will be executed once the Poll phase becomes idle.
6) Close callback:
This phase handles callbacks if a socket or handle is closed suddenly
and the 'close' event will be emitted.

Prepared by: [Link] , AP/IT 82


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

10. Explain the listeners in [Link] with suitable examples.


• An event listener is a technique or a function that waits for an event to occur.
listener is programmed to react to an input or signal by calling the event's
handler.
• The event module allows us to create and handle custom events in [Link].
• The EventEmitter class is used to raise and handle the events.
• Following are some commonly used properties and methods that implements
the event listeners.
Method Purpose
addListener(event, listener) Adds a listener to the end of the listeners array for
the specified event. No checks are made to see if
the listener has
already been added.
on(event, listener) It can also be called as an alias of
[Link]()
removeListener(event, Removes a listener from the listener array for the
listener) specified event.
Caution: Changes array indices in the listener
array) behind the listener.
remove AIIListeners([event]) Removes all listeners, or those of the specified
event.
listeners(event) It returns an array of listeners for specified event.

listenerCount(event) It returns the number of listeners listening to the


specified Events.
prependOnceListener(event, It will add the one-time listener to the beginning of
listener) the array

setMaxListeners(int) This method sets the number of listeners to the


particular event. By default a maximum of 10
listeners can be registered for any single event.
getMaxListeners() It will return the max listeners value set by
setMaxListeners() or default value 10.

Table2.3 properties and methods that implements the event listeners.

Example Code
var events = require('events');
Var eventEmitter = new [Link] ();

Prepared by: [Link] , AP/IT 83


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

//Event listener #1
var listener1 = function listener1() {
[Link] ('Event listener#1 executed.');

// Event listener #2
var listener2 = function listener2(){
[Link]('Event listener#2 executed.’ );
}
// Event listener #3
var listener3 = function listener3(){
[Link]('Event listener#3 executed.’ );
}

[Link]('myevent);
// Bind the 'myevent' event with the listener1 function
eventEmitter. addListener('myevent’, listener1);
// Bind the 'myevent' event with the listener2 function
eventEmitter. on ('myevent’, listener2);:
[Link]('myevent’, listener3);
//Raise the events
[Link](‘myevent’);
//Display the total number events
[Link]("'Number of Eventlisteners are:
"+[Link](‘myevent'));
//Display the current status of event queue
[Link]('Following are the events in the queue..\n");
console. log([Link] ('myevent)):
//Remove the binding of listener1 function
[Link]('myevent’, listener1);
[Link] ('Event Listener#1 is removed"):
//Display the current status of event queue
[Link]('Following are the events in the queue...\n");
[Link](eventEmitter. listeners ('myevent'));
[Link] ("Number of Eventlisteners
are:"+[Link]('myevent'));
//Removing all the events
[Link]("'Remnoving all the events.");
eventEmitter. removeAllListeners ('myevent’);
//Display the current status of event queue

Prepared by: [Link] , AP/IT 84


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

[Link] ('Following are the events in the queue...\n'");


[Link](eventEmitter. listeners(myevent'));
[Link]('Number of Eventlisteners
are:"+[Link]('myevent'));
Output
Event listener#1 executed.
Event listener#2 executed.
Event listener#3 executed.
Number of Eventlisteners are: 3
Following are the events in the queue...
[ [Function: listener 1 ], (Function: listener2], (Function: listener3] ]
Event Listener#1 is removed
I[Function: listener2], [Function: listener3] )
Number of Eventlisteners are: 2
Removing all the events.
Following are the events in the queue...
[]
Number of Eventlisteners are: 0
Program Explanation: In above program,
1. Three functions are created as event listeners. Then using
[Link]() and [Link]() methods are used to
bind the events with the corresponding functions.
2. Then using [Link]() method,the events are raised.
3. We have used the eventEmitter. listener Count() method to get the
total number of events that are active.
4. The event [Link]() method is used to display the array of
registered events.
5. We have also used removeListener() method to remove one listener and
removeAllisteners() method to remove all the listeners.
-------------------------------------------------------------------------------------------------------------

Prepared by: [Link] , AP/IT 85


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

11. Explain the concept about timers in [Link] wit an example


Timers module in Node js provides a way for scheduling the functions to be
executed on some given time.
For using the timers module in [Link] it is not required to import it via
require() function as all the methods are globally available to JavaScript API.
Hence we do not have to use "require" in the source code while using timer
functions.
There are three set timer functions used in [Link]

[Link]() 2. setlmmediate() 3. setlnterval()

.
Let us understand them with suitable examples -
1. setTimeout(): This function is used to set one-time callback after
delaying by some milliseconds.
Syntax
set Timeout (function, delay in milliseconds)
Example program:

[Link]("Task1");

setTimeout(function() {[Link]("Taks2:Executing After 4 seconds")},4000);

[Link]("Task3");

[Link]
Output

Prepared by: [Link] , AP/IT 86


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Example code for the function having some parameters


We will now discuss to use setTimeout function for accepting a function
with parameters. The function that will be passed to setTimeout along with
parameters has following syntax -

setTimeout(function_name,delay_in_milliseconds,parameter1,parameter2, ...);

Example [Link]

[Link]("Greeting message will be displayed soon... ");

var myfun = (user) => {

[Link]("Good Morning "+user);

};

setTimeout (myfun, 1000, "Ankita");

Output

2) setlmmediate()
This function schedules the immediate execution of the callback function
after I/O event.

The syntax is

setImmediate () => {

//function body

})

Prepared by: [Link] , AP/IT 87


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

 We don't need to pass any time interval to this method. The first
argument is the function
to execute. We can also pass any extra arguments to this function.
 This method will execute a function right after the next code block which
is present after the setImmediate function.
For Example

[Link]("'Started!!");

setImmediate(() => {

[Link]("Now Executing setImmediate Block...");

});

[Link]("Task1");

[Link]("Taks2");

3) setInterval() : This function helps to execute a task in a loop after some time
interval.
This function has the same syntax as that of setTimeout.
Syntax

timerld = setInterval(func | code, [delay], larg1], larg2], ...)

var myfun = () =>{


[Link] ('Hello');
};
setInterval(myfun, 1000);

Prepared by: [Link] , AP/IT 88


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

The above code present in the function myfun gets executed after every 1000
millisec
To break this program running in a loop we have to press control+c.

------------------------------------------------------------------------------------------------------------

Prepared by: [Link] , AP/IT 89


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

12. Explain the callbacks in node js with suitable example.


What are callbacks in [Link] and how are callbacks useful in handling
asynchronous operations? Explain with suitable examples.
(April/May-2025)

What is callbacks?
Callbacks is a function which is usually passed as an argument to
another function and it is usually invoked after some kind of event.
How it works?
The callback function is passed as an argument to another function.
when particular event occurs then only it is invoked.
By the time callback function is executing another task gets executed.
Hence execution of call backs is asynchronous execution.
Example Code
Step 1: Create a simple text file named “[Link]" as follows -
[Link]
How are you?

Jack and Jill went up the hill,

to fetch a glass of water

Step 2: Create a JavaScript file(.js) that contains the callback function


[Link]

var fs = require("fs'):

[Link]('Serving User1")

[Link] ('[Link]', function (err, data){

if (err) return [Link](err);

console. log (“*** Contents of the File are.. ***”);

[Link] ([Link]());

});

[Link]("Serving User2");

[Link]("Serving User3");

[Link]("Good Bye!!!");

Prepared by: [Link] , AP/IT 90


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Prepared by: [Link] , AP/IT 91


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Program Explanation: In above program,


1) We have to read a file named [Link], but while reading a file it should not
block the execution of other statements, hence a call back function is called in
which the file is read.
2) By the time file gets read, the remaining two console functions indicating
"Serving user 1” and “Serving user 2" are not blocked, rather they are executed,
once the contents are read in the buffer, then those contents of the file are
displayed on the console.

Prepared by: [Link] , AP/IT 92


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

13. With necessary source code, explain how to use file I/O operations in
[Link].
Describe about the methods of Reading buffer and writing buffer objects with
examples (6) (Nov/Dec-2024)
Explain in detail about methods in handling data input/output operations using [Link]
(April/May-2025)

Buffers
• Buffer is class that allows us to store raw data similar to arrays.
• It is basically a class that provides the instances for storing the data.
• It is a global class so we can use it without any need of importing a buffer
module.
1. Creation of Buffer
Creating a buffer is very simple. For example,

var buffer = new Buffer (10):

This will create a buffer of 10 units.


Similarly, we can create a buffer as follows -

var buffer= new Buffer ([1,2,3,4,5|, "'utf8");

The second parameter which we have passed here is encoding scheme. It


allows various encodings such as utf8(this is default one),
ascii,ucs2,base64, or hex.

2. Writing to Buffer
The syntax for writing to the buffer is

Write(string[,offset], [length] [,encoding|)

where,
string: t is the string to be written to the buffer.
offset: It is the index from where we can start writing. The default value
is 0.
length: It indicates the number of bytes to be written to the buffer.
Prepared by: [Link] , AP/IT 93
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Encoding: It indicates the desired encoding. The default one is “utf8”

Example Code
Following is a simple node js program that shows how to write data to the
buffer.
[Link]

var buffer = new Buffer(50);


[Link]([Link]('utf8'));

[Link]("Good Morning");

Output

Prepared by: [Link] , AP/IT 94


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Program Explanation: In above program,


We have used write method for writing to the buffer. For displaying the string
written to the buffer we have to use toString method along with the encoding
scheme.

3. Reading from Buffer


The syntax for reading from buffer is as follows

toString([encoding][,start][,end])

where
encoding: It indicates the encoding scheme. The default one is utf8".
start: Beginning index is indicated by this value. The default is 0.
end: Ending index is indicated by this value.

4. Copying Buffers
 An important part of working with buffers is the ability to copy data from
one buffer into another buffer.
 [Link] provides the copy(targetBuffer, [targetStart],[sourceStart],
[sourceIndex]) method on Buffer objects.
 The targetBuffer parameter is another Buffer object, and targetStart,
sourceStart, and sourceEnd are indexes inside the source and target
buffers.
 You can also copy data from one buffer to the other by indexing them directly,
for example:
sourceBuffer[index] = destinationBuffer[index]

5. Slicing Buffers
 Another important aspect of working with buffers is the ability to divide
them into slices.

Prepared by: [Link] , AP/IT 95


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

 A slice is a section of a buffer between a starting index and an ending


index. Slicing a buffer allows you to manipulate a specific chunk.
 Slices are created using the slice([start], [end]) method, which returns a
Buffer object that points to start index of the original buffer and has a
length of end – start.
 Keep in mind that a slice is different from a copy. If you edit a copy, the
original does not change.
 However, if you edit a slice, the original does change.
buffer_slice.js:
Creating and manipulating slices of a Buffer object
var numbers = new Buffer("123456789");
[Link]([Link]());
var slice = [Link](3, 6);
[Link]([Link]());
slice[0] = '#'.charCodeAt(0);
slice[[Link]-1] = '#'.charCodeAt(0);
[Link]([Link]());
[Link]([Link]());

Output
buffer_slice.js: Slicing and modifying a Buffer object
123456789
456
#5#
123#5#789
6. Concatenating Buffers
 You can also concatenate two or more Buffer objects together to form a
new buffer.

Prepared by: [Link] , AP/IT 96


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

 The concat(list, [totalLength]) method accepts an array of Buffer objects


as the first parameter, and totalLength defines the maximum bytes in
the buffer as an optional second argument.
 The Buffer objects are concatenated in the order they appear in the list,
and a new Buffer object is returned containing the contents of the original
buffers up to totalLength bytes.
buffer_concat.js: Concatenating Buffer objects
var af = new Buffer("African Swallow?");
var eu = new Buffer("European Swallow?");
var question = new Buffer("Air Speed Velocity of an ");
[Link]([Link]([question, af]).toString());
[Link]([Link]([question, eu]).toString());
Output buffer_concat.js: Concatenating Buffer objects
Air Speed Velocity of an African Swallow?
Air Speed Velocity of an European Swallow?
-------------------------------------------------------------------------------------------------------------
14. Write about Streaming concept in [Link]. Discuss about Readable and Writable
Streams with code snippets.(7)(Nov/Dec-2024)
 Using the Stream Module to Stream Data An important module in [Link]
is the stream module. Data streams are memory structures that are
readable, writable, or both.
 Streams are used all over in [Link], for example, when accessing files or
reading data from HTTP requests and in several other areas.
 This section covers using the Stream module to create streams as well as
read and write data from them.
 The purpose of streams is to provide a common mechanism to transfer
data from one location to another.
 They also expose events, such as when data is available to be read, when
an error occurs, and so on.
 You can then register listeners to handle the data when it becomes
available in a stream or is ready to be written to.

Prepared by: [Link] , AP/IT 97


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

 Some common uses for streams are HTTP data and files. You can open a
file as a readable stream or access the data from an HTTP request as a
readable stream and read bytes out as needed.
Stream can be defined as objects that reads data from source or writes the
data to the destination in continuous fashion.
The stream is an EventEmitter instance that emits several events. Following are
the events that occur during stream operations -
1) data: This event is fired when we want to read the data from the file.
2) end: When there is no more data to read then this event is fired.
3) error: If any error occurs during reading or writing data then this event is
fired.
4) finish: When data is completely flushed out then this event occurs.
There four types of streams,
i) Readable: This stream is used for read operation only.
ii). Writable: This stream is used for write operation only.
iii) Duplex: This type of stream is used for both read and write operation.
iv) Transform: In this type of stream the output is computed using input.

Write operation
The steps that are followed to write data to the stream using [Link] are as
follows -
Step 1: Import the file stream module fs using require.
Step 2: Create a writable stream using the method createWriteStream.
Step 3: Write data to the stream using write method.
Step 4: Handle the events such as finish or error(if any)
Following [Link] script shows how to write data to the string,

writeStream [Link]

Prepared by: [Link] , AP/IT 98


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

var fs = require("fs “);


var str = "This line is written to myfle";

var ws = [Link]('[Link]');

[Link](str,'utf8');

[Link]();

[Link]("The data is written to the file..");

Output

Read operation
For reading from the stream we use createReadStream. Then using the data
event the data can be read in chunks.

Prepared by: [Link] , AP/IT 99


IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

var fs = require(“fs”);
var str = "";
var rs = [Link]('[Link]');
[Link](“utf8");

//handling stream event 'data'


[Link](‘data',function(chunk) {
str += chunk;
});

handling stream event 'end'


[Link]('end’,function(){
[Link](str)
});
/I/handling stream event 'error’
[Link]('error’, function(err){
[Link] (err. stack);
});
[Link]

This line is written to myfile

Output
D:\NodeJSExamples>node [Link]
This line is written to myfile
Pipe operation
The pipe operation is a kind of operation in which output of one stream acts as
an input of another stream.
There is no limit on pipe operation that means, all the output of one stream can
be fed as input to input to another stream.
Following are the steps used for using the pipe operation in your [Link]
program
Step 1: Import the fs' module using require.
Step 2: Create readable stream using createReadStream function.
Step 3: Create writable stream using createWriteStream function.

Prepared by: [Link] , AP/IT 10


0
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Step 4: Use the pipe() function for passing the data from readable stream to
writable stream.

Following example shows the use of pipe operation -


pipeExample,js

var fs = require("fs");

var rs = [Link]('[Link]');

[Link] ("utf8");

var ws = [Link]('[Link]');

[Link]('utf8');

[Link](ws);

[Link]("Data is transfered from '[Link]' to 'output. txt'");

[Link]

Hello friends,

[Link] is really amazing.

Really enjoying it.

[Link]

Hello friends,

[Link] is really amazing.

Really enjoying it.

Prepared by: [Link] , AP/IT 10


1
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Duplex Streams
 A Duplex stream combines Readable and Writable functionality. A good
example of a duplex stream is a TCP socket connection.
 You can read and write from the socket connection once it has been
created.
 To implement your own custom Duplex stream object, you need to first
inherit the functionality for Duplex streams. The simplest way to do that
is to use the util module’s inherits() method:
var util = require('util');
[Link](MyDuplexStream, [Link]);
Then you create an instance of the object call:
stream. [Link](this, opt);
 The opt parameter when creating a Duplex stream accepts an object with
the property allowHalfOpen set to true or false.
 If this option is true, then the readable side stays open even after the
writable side has ended and vice versa.
 If this option is set to false, ending the writable side also ends the
readable side and vice versa.

Prepared by: [Link] , AP/IT 10


2
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

 When you implement a Duplex stream, you need to implement both a


_read(size) and a _write(data, encoding, callback) method when
prototyping your Duplex class.
Transform Streams
Another type of stream is the Transform stream. A Transform stream
extends the Duplex stream but modifies the data between the Writable stream
and the Readable stream. This can be useful when you need to modify data
from one system to another. Some examples of Transform streams are
■ zlib streams
■ crypto streams
A major difference between the Duplex and the Transform streams is that for
Transforms you do not need to implement the _read() and _write() prototype
methods. These are provided as pass-through functions.
---------------------------------------------------------------------------------------------------------
15. With necessary source code, explain how to use file I/O operations in
[Link].
File system fs is implemented in the [Link] using require function.

var fs require(‘fs’);

The common operations used with the file system module are -
1. Read file
2. Create file
3. Update file
4. Delete file
1. Read Operation
 The read file operation can be performed synchronously or
asynchronously.
 For reading the file synchronously we use readFileSync method. And for
reading the synchronously readFile
 Normally while reading the file using asynchronous form we use callback
function as the last parameter to the readFile function.
 The form of this callback function is.

Prepared by: [Link] , AP/IT 10


3
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

function(err, data)
{
//function body
}

Example code

var fs = require("fs");
[Link]('[Link]',function(err,data) {
if(err)
[Link](err);
[Link]([Link]());
});

[Link]
Helo friends,
Node js is really amazing.
Really enjoying it.
Output

Similarly we can read the file synchronously using following command-


Syntax
require("fs");
var data= [Link]('[Link]');
[Link]([Link]());

Prepared by: [Link] , AP/IT 10


4
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

2. Create File Operation


We can create an empty file using the command open()
Syntax

open(path, flags[, mode],callback)


where
path: It is the path of the filename.
flag: It indicates, the behaviour on opening a file. That means “r” is open file for
reading,"w" is for writing, “rs” is for synchronous mode, “rt” or “w+” means
open a file for both read and write purpose and so on
mode: It indicates readable or writable mode.
Callback: It is basically a function which has two arguments(err,data)
Example Code

var fs = require("fs");
[Link]('[Link]', 'w',function(err,file){
if(err)
[Link](err)
[Link] ('File created!!!');
});

Prepared by: [Link] , AP/IT 10


5
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

3. Update / Write File Operation


For writing to the file two operations are used most commonly -
1. appendFile() and
2. writeFile()
The appendFile() method is used to write the contents at the end of the specified
file.
Example Code
var fs = require("'fs");
str = "This line is written to the file";
[Link] ('[Link]', str,function(err){
if(err)
console. log (err)
[Link] (File appended!!!);
});

Example Code
The writeFile() method is used to write the contents to the file
var fs = require(“fs”);
str = "This line is replacing the previous contents”;
[Link]('[Link]’, str,function(err) {
if(err)
[Link] (err)
[Link]('File Writing Done!!!');
});

Prepared by: [Link] , AP/IT 10


6
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Output:
D:\NodeJSExamples>node [Link]
File Writing Done!!!
D:\Node3SExamples>type [Link]
This line is replacing the previous contents
D: \NodeJSExamples>

4. Delete File Operation


To delete the file, we use unlink() method.

unlink(path, callback()
where
path: Is a path of the file to be deleted.
callback: It is a callback function with the only one argument for 'error’.

Example Code
var fs = require("fs");
[Link]('[Link]', function(err){
if(err)
throw err;
[Link]("File is deleted!!!");
});

Output

Prepared by: [Link] , AP/IT 10


7
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Deleting a file

Checking if file gets deleted or not

Again trying to delete a deleted file, hence exception is thrown.

Prepared by: [Link] , AP/IT 10


8
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

16. Write about Understanding the URL Object Implementing HTTP


Services in [Link] in detail.
Understanding the URL Object
• URL is a unique identifier that provides a way to access information from
rent computers, like a web server and cloud storage.
• HTTP server makes use of URLs to handle the requests from clients.
 The Uniform Resource Locator (URL) acts as an address label for the
HTTP server to handle requests from the client.
 It provides all the information needed to get the request to the correct
 server on a specific port and access the proper data.
 The URL can be broken down into several different components, each
providing a basic piece of information for the webserver on how to route
and handle the HTTP request from the client.
 HTTP requests from the client include the URL string with the information
shown in Figure 7.1. To use the URL information more effectively,
 [Link] provides the url module that provides functionality to convert the
URL string into a URL object.
 To create a URL object from the URL string, pass the URL string as the
first parameter to the following method:
[Link](urlStr, [parseQueryString], [slashesDenoteHost])
 The [Link]() method takes the URL string as the first parameter.
 The parseQueryString parameter is a Boolean that when true also
parses the query string portion of the URL into an object literal. The
default is false.
 The slashesDenoteHost is also a Boolean that when true parses a URL
with the format of //host/path to {host: 'host', pathname: '/path'} instead
of {pathname: '//host/path'}. The default is false.
 you can also convert a URL object into a string form using the following
[Link]() method.

Prepared by: [Link] , AP/IT 10


9
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

• Basic components of URL are as follows -


[Link]
3889 180800-5?Pr_prod start-descriptiont#myorder

1) Protocol:
This is the request protocol used by the client while making the
request. The popular protocols in web-based applications are http and https
which display the page in HyperText(HTML) format. Some other protocols are -
FTP i.e. file transfer protocol which is used for file transfer, SMTP i.e. Single
Mail Transfer Protocol which is used for sending emails.
2) Subdomain:
It is a specific type of resource to be delivered to the client. The
subdomain www is a general symbol for any resource on the web.
3) Hostname:
The host name identifies the host that holds the resource.
4) Port number:
A port number specifies the type of service that is requested by theclient,
since servers often deliver multiple services. Some default port numbers
includes 80 for HTTP and 443 for HTTPS servers.
5) Pathname:
It specifies the exact location of the web page, file or any resource that
the user wants to access.

6) QueryString:
The query string specifies the parameters of the data that is being queried
from a website's database. Each query string is made up of a parameter and a
value joined by the equals () sign. In case of multiple parameters, query strings

Prepared by: [Link] , AP/IT 11


0
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

are joined using the ampersand (&) sign. The parameter can be a number,
string, encrypted value or any other form of data on the database.
7) Hash:
It is optional and always appears at the end of the URL. It indicates a
specific location within a page such as the 'id' or 'name' attribute for an HTML
element.

Resolving the URL Components


 Another useful feature of the url module is the ability to resolve URL
components in the same manner as a browser would.
 This allows you to manipulate the URL strings on the server side to make
adjustments in the URL.
 For example, you might want to change the URL location before
processing the request because a resource has moved or changed
parameters.
 To resolve a URL to a new location use the following syntax:
[Link](from, to)
 The from parameter specifies the original base URL string.
 The to parameter specifies the new location where you want the URL to
resolve.
Query String and Form Parameters
The query string specifies the parameters of the data that is being queried from
a website's database. Each query string is made up of a parameter and a value
joined by the equals (=) [Link] query string and form parameter are just like
key-value pairs. To parse the query string in order to obtain the values that are
passed to it, the method is used.
[Link]( qrystr[, Sep[, Eq[, options]]])
where
qrystr: lt is a string that specifies the URL query to be parsed.
Sep: lt is a string that specifies the substring used to delimit the key and value

Prepared by: [Link] , AP/IT 11


1
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

pairs in the specified query string & The default value is “&”.
Eq: It is a string that specifies the substring used to delimit keys and values in
a
specified query string. The default value is *=".
Options: It is an object which enables us to change the function's behavior with
respect to the maximum number of keys and percent-encoded
characters.
Example Code
const querystr = require('querystring');
var str = "User= admin&password pass1234";
//calling the parse function to obtain the values
[Link]("Parsed Object:",[Link](str))
Output

Prepared by: [Link] , AP/IT 11


2
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

17. Explain about Request, Response, incomingmessage object and Server


Object in detail
Request, Response and Server Object
The web module is mainly controlled by a web server that handles the
requests and provides the responses. These requests and responses are
handled by HTTP(Hyper Text Transfer Protoco) protocol.
The user submits the request using a web browser. Thus the
communication between web server and web browser is handled by HTTP
protocol.
Following steps explain this communication -
 When a user submits a request for a web page, he/she is actually
demanding for a pay present on the web server.
 When a web browser submits the request for a web page, the web
server responds to this request by sending back the requested page
to the web browser of the client's machine.
Step1
Web client requests for the desired wveb page by providing the IP
address of the website
Step2
The web server locates the desired web page on the website and
responds by sending back the requested page. If the page doesn't
exist, it will send back the appropriate error page.
website.
Step 3
The web browser receives the page and renders it as required.
The request and response objects of the HTTP module in [Link]
are the important objects of client server communication.

Following are important objects that we will learn in this section


1. [Link]
2. [Link]
3. [Link]
4. [Link]

1. The [Link] Object


 This object is useful to monitor the in-progress request.
 The ClientRequest object is used to monitor and handle the response from
the server.

Prepared by: [Link] , AP/IT 11


3
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

 For implementing the ClientRequest object the call to the [Link]() is


made. The syntax to this method is as follows -
 Syntax
[Link](options,call back)
Parameters
1) options parameter is an object which is responsible for defining how to
open and send the client HTTP request to the server. Various options
that can be specified while creating ClientRequest are as follows-

Property Purpose

host The domain name or IP address of the server to which the


request is made. Default is localhost.
port The port number. Default is 80.

method It is the HTTP request method, it can be GET, POST,


CONNECT.
Default is GET.
path A string specifying the requested resource path. Default is /

Table 2.4 http client request properties


2) callback parameter is a callback function which is called after the
request is sent to server. Then this function handles the response
obtained from the server(note that it is callback function).

2. The [Link] Object


 When the request event is received then the ServerResponse object is
created internally.
 The ServerResponse object is passed as a second parameter to the
requestListener function.
 This object makes use of Writable Stream for writing the data back to the
client.
 Following are some properties and methods that are used by
ServerResponse objects to build and send header, write the data or to
send the response.

Property Description
addTrailers() This method adds HTTP trailing headers.

Prepared by: [Link] , AP/IT 11


4
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

This method is to get the value of an HTTP header that has


getHeaders()
been set in the response.
removeHeader() This method removes the specified HTTP header.
This property allows us to specify the status response code.
setStatusCode()
For instance [Link] = 500
Sets the timeout value of the socket to the specified number
setTimeout()
of milliseconds.
write() Sends the text, or a text stream to the client.
writelHead() Sends the status and response headers to the client.
This property is used to when to the connection to the client
close
is closed nri to the [Link]) method.
This method is an indication for the server that the response
end()
is now complete.
Table 2.5 http server request properties
[Link] Object
 The IncomingMessage object is created either by HTTP server or the HTTP
client.
 When this object is used at the server side, the client request is represented by
the IncomingMessage object.
 When this object is used at the client side, the server response is represented
by the IncomingMessage object.
 The IncomingMessage implements Readable stream. Using this object client
request or server response is read as a streaming source.
 Following are some events, properties and methods of IncomingMessage object

Method/Event/
Description
Property
headers This is an object containing the headers sent with the
request/response.
Trailers This is an object containing any trailer headers sent with the
request/response.
Method It specifies the methods for request and response. The method can
be GET,POST, CONNECT.
statusCode It specifies the three digit status code from the server.

socket This a handle to the [Link] object used to communicate with


the client and server.

Prepared by: [Link] , AP/IT 11


5
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

url The url string is sent to the server. This string can be parsed
using [Link]()
close It is used while closing the communication.

Table 2.6 http IncomingMessage object -


4 .The [Link] Object
 The HTTP module can create an HTTP server that listens to server ports
and giIves a response back to the client. The createServer() method is
used to create an HTTP server.
 This method returns the server object. Once the server object is created
then begin listening on it by calling the listen() method on the server
object.
 Once you have created the Server object, you can begin listening on it by
calling the listen() method on the Server object:
listen(port, [hostname], [backlog], [callback])
The first method listen(port, [hostname], [backlog], [callback]) is the one that
you
will most likely use.
The following list describes each of the parameters:
■ port: Specifies the port to listen on.
■ hostname: Specifies when the hostname will accept connections, and if
omitted, the
server will accept connections directed to any IPv4 address (INADDR_ANY).
■ backlog: Specifies the maximum number of pending connections that are
allowed to be queued. This defaults to 511.
■ callback: Specifies the callback handler to execute once the server has begun
listening on the specified port.

18. Explain the components of [Link] application ( Nov/Dec -2023)

[Link] Server Architecture


[Link] uses the “Single Threaded Event Loop” architecture to handle
multiple concurrent clients. [Link] Processing Model is based on the
JavaScript event-based model along with the JavaScript callback
mechanism.

Prepared by: [Link] , AP/IT 11


6
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Fig: 2.4 [Link] architecture


Now let’s understand each part of the [Link] architecture and the workflow of a
web server developed using [Link].
Parts of the [Link] Architecture:
 Requests
Incoming requests can be blocking (complex) or non-blocking (simple),
depending upon the tasks that a user wants to perform in a web application
 [Link] Server
[Link] server is a server-side platform that takes requests from users,
processes those requests, and returns responses to the corresponding users
 Event Queue
Event Queue in a [Link] server stores incoming client requests and passes
those requests one-by-one into the Event Loop
 Thread Pool
Thread pool consists of all the threads available for carrying out some tasks
that might be required to fulfill client requests
 Event Loop
Event Loop indefinitely receives requests and processes them, and then
returns the responses to corresponding clients
 External Resources
External resources are required to deal with blocking client requests. These
resources can be for computation, data storage, etc.

Prepared by: [Link] , AP/IT 11


7
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

To develop a simple web application to get and display user profiles using [Link]
<!DOCTYPE html>
<html>
<head>
<title>Create User Profile</title>
</head>
<body>
<h1>Create User Profile</h1>
<form action="/users" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" required><br>
<label for="bio">Bio:</label>
<textarea id="bio" name="bio" required></textarea><br>
<button type="submit">Create Profile</button>
</form>
</body>
</html>

Prepared by: [Link] , AP/IT 11


8
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

[Link] in detail about processing query strings and form parameters


with request, response server objects with example (April/May-2025)

Processing query strings and form parameters is a fundamental aspect of handling HTTP
requests in web development. Query strings and form parameters allow data to be sent
from the client (browser) to the server, where it can be processed and used to generate a
response.
Here’s a detailed explanation with an example:
1. Query Strings
Query strings are part of the URL and are used to send data to the server. They follow
the ? symbol in the URL and consist of key-value pairs separated by &.
Example URL:
Copy the code[Link]

 Key-Value Pairs:
o query=books
o category=fiction

How to Process Query Strings:


On the server side, query strings can be accessed using the request object. Most server-
side frameworks provide utilities to parse and retrieve query parameters.
2. Form Parameters
Form parameters are sent when a user submits a form. They can be sent via:

 GET Method: Appended to the URL as query strings.


 POST Method: Sent in the request body.
Example Form:
Copy the code<form action="/submit" method="POST">
<input type="text" name="username" value="JohnDoe">
<input type="password" name="password" value="12345">
<button type="submit">Submit</button>
</form>

 Key-Value Pairs:
o username=JohnDoe
o password=12345

How to Process Form Parameters:


Form parameters are typically accessed from the request body. Frameworks often
provide methods to parse the body and retrieve the data.

Prepared by: [Link] , AP/IT 11


9
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Example Code: Processing Query Strings and Form Parameters


Using [Link] with [Link]

const express = require('express');


const app = express();

// Middleware to parse form data (for POST requests)


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

// Route to handle query strings


[Link]('/search', (req, res) => {
const query = [Link]; // Access query string parameter 'query'
const category = [Link]; // Access query string parameter 'category'
[Link](`Search Query: ${query}, Category: ${category}`);
});

// Route to handle form parameters


[Link]('/submit', (req, res) => {
const username = [Link]; // Access form parameter 'username'
const password = [Link]; // Access form parameter 'password'
[Link](`Username: ${username}, Password: ${password}`);
});

// Start the server


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

How It Works:
1. Query Strings:
o When you visit [Link] the server
extracts the query and category parameters from the URL and sends a response.
2. Form Parameters:
o When you submit the form to /submit, the server processes
the username and password parameters from the request body and sends a response.

Key Points to Remember:

 Security: Always validate and sanitize user inputs to prevent security vulnerabilities like
SQL injection or XSS.
 Middleware: Use middleware (e.g., [Link]) to parse form data in POST requests.
 Framework-Specific Methods: Different frameworks (e.g., Flask, Django, [Link]) have
their own methods for handling query strings and form parameters.
This approach ensures efficient and secure handling of user inputs in web applications.

Prepared by: [Link] , AP/IT 12


0
IIT3501-FULLSTACK WEB DEVELOPMENT UNIT-II NODE JS III Yr IT / V Semester

Prepared by: [Link] , AP/IT 12


1
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

UNIT - III MONGO DB


Understanding NoSQL and MongoDB – Building MongoDB Environment – User
accounts – Access control – Administering databases – Managing collections –
Connecting to MongoDB from [Link] – simple applications

Part –A Questions
1. What is NoSQL?

NoSQL stands for not only SQL. It is nontabular database system that
store data differently than relational tables. There are various types of
NoSQL databases such document, key-value, wide column and graph.
Using NoSQL we can maintain flexible schemas and these schemas can
be scaled easily with large amount of data.

2. Enlist the features of NoSQL.


1. The NoSQL does not follow any relational mode
2. It is either schema free or have relaxed schema. That means it does not
require specific
3. definition of schema.
4. Multiple NoSQL databases can be executed in distributed fashion.
5. It can process both unstructured and semi-structured data
6. The NoSQL have higher scalability.

3. Enlist the features of MongoDB.

1. It is a schema-less, document based database system.


2. lt provides high performance data persistence.
3. It supports multiple storage engines.
4. It has a rich query language support.
5. MongoDB provides high availability and redundancy with the help of
replication.
That means it creates multiple copies of the data and sends these copies
to a different server so that if one server fails, then the data is retrieved from
another server.

4. What is mongoDB?

 MongoDB is an open source, document based database.


 It is developed and supported by a company named 10gen which is now
known MongoDB Inc.
 The first ready version of MongoDB was released in March 2010.
5. Why MongoDB is needed?

There are so many efficient RDBMS products available in the market, then
why do we need MongoDB? Well, all the modern applications require Big data,
faster development and flexible deployment. This need is satisfied by the
document based database like MongoDB.

1
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

6. How the terms in MongoDB are different from SQL?

The terms in SQL are treated differently in MongoDB. In MongoDB the


data is not stored in tables, instead of that, the there is a concept called
collection which is analogous to the tables. In the same manner the rows in
RDBMS are called documents in MongoDB, likewise the columns of the
record in RDBMS are called fields.

7. Define collections in MongoDB.


What is database collection and document in MongoDB?( Nov/Dec-2023)

MongoDB groups data together through collections. A collection is simply a


grouping of documents that have the same or a similar purpose.
A collection acts similarly to a table in a traditional SQL database, with one
major difference.
In MongoDB, a collection is not enforced by a strict schema; instead,
documents in a collection can have a slightly different structure from one
another as needed.
This reduces the need to break items in a document into several different
tables, which is often done in SQL implementations.

8. Define the term document in MongoDB.


What is database collection and document in MongoDB?( Nov/Dec-2023)

A document is a representation of a single entity of data in the MongoDB


database. A collection is made up of one or more related objects.
A major difference between MongoDB and SQL is that documents are
different from rows.
Row data is flat, meaning there is one column for each value in the row.
However, in MongoDB, documents can contain embedded subdocuments,
thus providing a much closer inherent data model to your applications.

9. What is User Accounts in MongoDB? List the various operations used


in UserAccounts.

MongoDB stores the information of all the users including name, password
and user authentication in the system.
Using MongoDB shell command, we can create the user accounts. Using
such user accounts, we can read and write to the databases.
The most commonly used operations are
1. List the users
2. Create the user accounts
3. Remove the users

2
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

10. Explain the createUser command in MongoDB.

The user accounts are created using the createUser() method.


Syntax
[Link] (user, writeConcern)
Parameters
user: Is a document with authentication and access information about the
user to create.
writeConcern: This document represents the level of write concern for
creation operation.

11. List and explain the roles used in creating the user.
what are the roles and permissions in MongoDB? ( April/May -2024)

Role Description

read Allows the user to read data from any collection within
database.
readAnyDatabase It is similar to read except on the local and config
database.
readWrite This role provides all the privileges of the read role plus
ability to modify data on all non-system collections.
dbAdmin This role allows the user to read from and write to the
database as well as clean, modify, compact, get
statistics profile and perform validations.
dbAdminAnyDatabase Same as dbAdmin except for all databases.

userAdmin This role allows the user to create and modify user
accounts the database.
userAdminAnyDatabase Same as userAdmin cxcept on the local and config
databases.

12. what are the permissions in MongoDB?


what are the roles and permissions in MongoDB? ( April/May -2024)

Permissions in MongoDB are the specific actions that a role grants. These actions are
defined as privileges and can be assigned to roles. The key components of permissions
in MongoDB include:

1. Resources: The database, collections, or specific namespaces that the privileges


apply to.
2. Actions: Specific operations that can be performed on the resources, such as find,
insert, update, remove, and administrative actions like createCollection,
dropDatabase, etc.
3. Privileges: A combination of resources and actions that define what a role allows
a user to do.

3
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

13. How remove users from MongoDB?

For removing the user, the [Link]() is used.


Syntax
[Link](username)

14. Enlist any four data types in MongoDB.


List the MongoDB Datatypes with its Description.(Nov/Dec-2024)

Following are various types of data types supported by MongoDB.


1. String
The most commonly used data type in MongoDB, strings are UTF-8 encoded. They are used to store
textual data.
[Link]({ name: "John Doe" })
2. Integer
MongoDB supports both 32-bit and 64-bit signed integers. They are used to store numerical values.
[Link]({ age: 21 })
3. Double
This data type is used to store floating-point values.
4. [Link]({ marks: 85.5 })
5. Boolean
Used to store true or false values.
[Link]({ passed: true })
6. Null
Stores a null value.
[Link]({ mobile: null })

15. Why mongodb is called schema less database?( Nov/Dec -2023 )

As a NoSQL database, MongoDB is considered schemaless because it does not


require a rigid, pre-defined schema like a relational database. The database
management system (DBMS) enforces a partial schema as data is written,
explicitly listing collections and indexes.

16. Summarize the advantages of mongodb over traditional databases.


( April/May -2024 )

MongoDB offers many advantages over traditional relational databases:

 Full cloud-based developer data platform


 Flexible document schemas
 Widely supported and code-native data access
 Change-friendly design
 Powerful querying and analytics
 Easy horizontal scale-out with sharding
 Simple installation

4
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
 Cost-effective
Full technical support and documentation

17. Define CRUD Operation

After creating some sample database, we must create some collection


inside that [Link] can perform various operations such as insert, delete
and update on this collection. These operations are called CRUD operations.
CRUD stands for Create, Read. Update and Delete operation.

18. How to create Create Collection in MongoDB

Syntax
We can create collection explicitly using createCollection command.
[Link] Collection(name, options)
where
name is the name of collection
options is an optional field. This field is used to specify some parameters
such as Size, maximum number of documents and so on.

5
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

19. Give the syntax for insert the document. The document is analogousto
rows in database.
The document is inserted within the collection. The document is
analogous to rows in database
Syntax
[Link] [Link]( {key, value }

20. How to insert multiple documents in a MongoDB database?

It is possible to insert multiple documents at a time using a single


command. Following command shows how to insert multiple documents in
the existing collection
> var = allStudents =
[
{
"name": AAA,
'age": 20
},
{
“name”:BBB,
“age": 21
},
{
"name": CCC
"age": 22
}
];
>[Link]
>[Link] [Link](alliStudents),

21. How to delete Documents in MongoDB

For deleting the document, the remove command is used. This is the
simplest command
Syntax
db.collection_name.remove(delete_criteria)

22. What are the methods used in Update the document in MongoDB

The methods used in Update the document in MongoDB


[Link],
2. updateMany or bulkwrite.
23. What is the method used for sorting the document in MongoDB

We can use the sort() method for arranging the documents in ascending or
descending order based on particular field of document.
Syntax
For displaying the documents in ascending order we should pass value 1
6
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

db collection name. find().sort ({field name:1})


If we pass -1 then the document will be displayed in the descending order of
the field
[Link] the MongoDBCIient in detail.

Method
Purpose

connect(url,options) This method is used to connect to the MongoDB


using the specified url.
close(force, callback) This method closes the db and underlying
connections.
db(dbname, options) It creates a new DB instance sharing the current
socket connections.
isConnected(options) It checks if MongoClient is connected.

25. How to see user roles in MongoDB? (Nov/Dec-2024)


To list all users in MongoDB, you can use the show users command or the [Link]() method. These
commands will display all users for the current database.

Example using show users


use admin
show users
This command will list all users in the admin database.

Example using [Link]()


use admin
[Link]()
This method returns detailed information about all users in the current database.

26..What are the advantages and disadvantages of NoSQL? (April/May-2025)

Advantages of NoSQL

 Scalability NoSQL databases are designed to scale horizontally across many servers, which makes
handling massive datasets and high traffic loads much easier.
 High Performance Since NoSQL systems often use optimized data formats (like key-value pairs or
document storage), they can deliver fast read and write operations.
 Flexible Data Models Schema-less design means you can store data in varying formats without
redesigning your database. Great for evolving applications or unstructured data.
 Big Data & Real-Time Use Cases Perfect for real-time applications such as social networks, IoT,
recommendation engines, and analytics platforms.
 Handles Unstructured Data Well NoSQL databases shine when it comes to storing documents, JSON,
multimedia files, and other non-relational types of data.

Disadvantages of NoSQL
7
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
 Limited ACID Transactions Unlike traditional relational databases, many NoSQL systems sacrifice
atomicity, consistency, isolation, and durability in favor of performance and scalability.
 Less Mature Query Tools NoSQL lacks the rich querying and reporting capabilities of SQL, which can
be a hurdle in complex applications.
 Data Redundancy Since relationships between data aren't handled as elegantly, NoSQL databases
sometimes duplicate data, which can lead to inconsistency.
 Complex Management for Some Use Cases Without a fixed schema, managing and validating data can
become more complicated over time.
 Learning Curve If you’re used to traditional relational databases, moving to a NoSQL approach can
take some adjustment.

[Link] to set environment for MongoDB? (April/May-2025)

Steps to Add MongoDB to Environment Variables

1. Locate MongoDB Installation Directory: Find the directory where MongoDB is installed. By default, it is
usually located at: C:\Program Files\MongoDB\Server\<version>\bin
2. Copy the Path: Copy the path of the bin directory. For example: C:\Program Files\MongoDB\Server\4.4\bin
3. Open Environment Variables: Press Win + Pause/Break to open System Properties. Click on Advanced
system settings. In the System Properties window, click on Environment Variables.
4. Edit Path Variable: In the Environment Variables window, find the Path variable in the System variables
section and select it. Click on Edit.
5. Add New Path: In the Edit Environment Variable window, click on New and paste the copied path of the
MongoDB bin directory. Click OK to save the changes.
6. Verify Installation: Open a new command prompt window and type: mongod --version If MongoDB is
correctly added to your environment variables, this command will display the version of MongoDB installed

[Link] how to create collection in MongoDB?

After creating some sample database, we must create some collection


inside that database.
Syntax
[Link] Collection(name, options)
where
We can create collection explicitly using createCollection command
name is the name of collection
options is an optional field. This field is
maximum number of documents and so on.
[Link] to Create Database in MongoDB?

The test> prompt will appear. For creating a database we need to “use” the
command.
Syntax
use Database_name

Example
test> use mystudents
Switched to db mystudents
mystudents>
8
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
switched to db mystudents
To check the currently selected database, use the command db
mystudents> db
mystudents
mystudents>

[Link] [Link]() method with an example(April/May-2025)

A basic example of how to create an HTTP server using the createServer ()


method: [Link](200, {'Content-Type': 'text/plain'}); [Link]('Hello World!');
[Link]('Server running at <[Link] In this example, we pass a
callback function to the createServer () method.

9
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

Part B & C Questions


1. Write about Understanding NoSQL and MongoDB
What is MongoDB and what are the features of
MongoDB? (April/May-2025)
NoSQL

 NoSQL stands for not only SQL.


 It is nontabular database system that store data differently than
relational tables.
are various types of NoSQL databases such as document, key-value,
wide column and graph.
 Using NoSQL we can maintaın flexible schemas and these schemas can
be scaled easily with large amount of data.
Need
The NoSỌ.L database technology is usually adopted for following reasons -
1. The NoSQL databases are often used for handling big data as a part of
fundamental
architecture.
2. The NoSQL databases are used for storing and modelling structured,
semi-structured
and unstructured data.
3. For the efficient execution of database with high availability, NoSQL is
used.
4. The NoSQL database is non-relational, so it scales out better than
relational
5. databases and these can be designed with web applications.
6. For easy scalability, the NoSQL is used.
Features
1. The NoSQL does not follow any relational model.
2. It is either schema free or have relaxed schema. That means it does not
require specific definition of schema.
3. Multiple NoSQL databases can be executed in distributed fashion.
4. It can process both unstructured and semi-structured data.
5. The NoSQL have higher scalability.
6. It is cost effective.
7. It supports the data in the form of key-value pair, wide columns and
graphs.
MongoDB
 MongoDB is an open source, document based database.
 It is developed and supported by a company named 10gen which is now
known MongoDB Inc.
 The first ready version of MongoDB was released in March 2010.
Why MongoDB is needed?
10
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

There are so many efficient RDBMS products available in the market, then
why do we need MongoDB? Well, all the modern applications require Big data,
faster development and flexible deployment. This need is satisfied by the
document based database like MongoDB.
Features of MongoDB
1. It is a schema-less, document based database system.
2. It provides high performance data persistence.
3. It supports multiple storage engines.
4. It has a rich query language support.
5. MongoDB provides high availability and redundancy with the help of
replication. That means it creates multiple copies of the data and sends
these copies to a different server so that if one server fails, then the data
is retrieved from another server.
6. MongoDB provides horizontal scalability with the help of sharding.
Sharding means to distribute data on multiple servers.
7. In MongoDB, every field in the document is indexed as primary or
secondary. Due to which data can be searched very efficiently from the
database.

2. Give the detail about collection and document in MongoDB.

Understanding Collections

 MongoDB groups data together through collections. A collection is


simply a grouping of documents that have the same or a similar
purpose.
 A collection acts similarly to a table in a traditional SQL database, with
one major difference.
 In MongoDB, a collection is not enforced by a strict schema; instead,
documents in a collection can have a slightly different structure from
one another as needed.
 This reduces the need to break items in a document into several
different tables, which is often done in SQL implementations.

Understanding Documents

 A document is a representation of a single entity of data in the MongoDB


database. A collection is made up of one or more related objects.
 A major difference between MongoDB and SQL is that documents are
different from rows.
 Row data is flat, meaning there is one column for each value in the row.
 However, in MongoDB, documents can contain embedded
subdocuments, thus providing a much closer inherent data model to
your applications.
 The records in MongoDB that represent documents are stored as BSON,
which is a lightweight binary form of JSON,
with field:value pairs corresponding to JavaScript property:value pairs.

11
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

 These field:value pairs define the values stored in the document.

 That means little translation is necessary to convert MongoDB records


back into the JavaScript object that you use in your [Link]
applications.

 For example, a document in MongoDB may be structured similarly to


the following with name, version, languages, admin, and paths fields:

{
name: "New Project",
version: 1,
languages: ["JavaScript", "HTML", "CSS"],
admin: {name: "Brad", password: "****"},
paths: {temp: "/tmp", project: "/opt/project", html:
"/opt/project/html"}
}
SQL Structure Vs. MongoDB

Following Fig. 3.1 shows the terms in SQL are treated differently in
MongoDB. In MongoDB the data is not stored in tables, instead of that, there
is a concept called collection which is analogous to the tables. In the same
manner the rows in RDBMS are called documents in MongoDB, likewise the
columns of the record in RDBMS are called fields.

Figure 3.1 SQL Structure Vs. MongoDB


Consider a student database as follows

12
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

To the left hand side we show the database in the form of table and to the
right hand side the database is shown in the form of collection,

Figure 3.2 Student Database in MongoDB


3. Explain how to create users in MongoDB? Also enlist and explain
various roles of the users.
Explain how to create and remove user in MongoDB. Also summarize
various roles assigned to users.(April/May-2025)

MongoDB stores the information of all the users including name, password
and user authentication in the system.
Using MongoDB shell command, we can create the user accounts. Using
such user accounts, we can read and write to the databases.
The most commonly used operations are
1. List the users
2. Create the user accounts
3. Remove the users
Let us discuss them one by one.
1. Listing Users

User accounts are stored in [Link] collection of each database.


There exists an object named User which contains the fields like_id, user,
13
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
pwd and roles.

14
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

For listing the users in the system, switch to admin database and then use
show users command.

test> use admin


switched to db admin
admin> show users
[]
admin>
admin>

As no user is created, it is showing empty.


Another query is using find). The [Link]() returns a cursor
object. Then using count() method we can obtain the total number of users
present in the system. For example-

test> use admin


SWitched to db admin
admin> cursor = [Link].
find()
admin> cursor. count()
0
admin>

2. Create User Accounts

The user accounts are created using the createUser() method.


Syntax
[Link](user, writeConcern)
Parameters
user: is a document with authentication and access information about the
user to create
writeConcern: This document represents the level of write concern for
creation operation
The user document has following fields
Name Description Type
user The name of the new user. string

pwd The user's password. The pwd field is not string


required if we run [Link](0 on the $
external database to create Users who have
credentials stored externally to MongoDB.
customData Any arbitrary information. This field can be documen
used to store any data an admin wishes to
associate with this particular user.
For example, this could be the user's full name
or employee id.
15
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

roles The roles granted to the user, Can specify an array


empty array [] to create users without roles.
Table 3.1 User document fields
The role can be specified as

{role: "<role>”,db: “<database>”}

For example-
admin> use test
switched to db test
test> [Link](
{
user: "AAA",
pwd: "AAA123",
roles: [ ]
}
):
{ ok: 1}
test>

Now to test, if the user named Parth is created or not, we issue the show
users command at the MongoDB shell.
test> show users
id: [Link]
user: 'AAA ',
userId: new UUID("59bb3031-f90f-4dle-9749-801469ele645)

user:’ AAA’,
db: 'test',
roles: [],
mechanisms : [ 'SCRAM-SHA-1', SCRAM-SHA-256 ]
test>

The above user is created without any role. But we can assign the role to the
user during the createUser command.

Creating the user with roles

Following is the list of some commonly used roles that can be assigned to their
user account.

Role Description

read Allows the user to read data from any collection within
database.
readAnyDatabase It is similar to read except on the local and config
database.

16
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

readWrite This role provides all the privileges of the read role plus
ability to modify data on all non-system collections.
dbAdmin This role allows the user to read from and write to the
database as well as clean, modify, compact, get
statistics profile and perform validations.
dbAdminAnyDatabase Same as dbAdmin except for all databases.

userAdmin This role allows the user to create and modify user
accounts the database.
userAdminAnyDatabase Same as userAdmin cxcept on the local and config
databases.

Table 3.2 Roles in creating user


For example -
[Link]
user:'sysAdmin",
pwd: "pass123",
roles:['readWrive" "'dbAdmin"]
}
);

Following screenshot represents how to create user with role.

test> [Link](
user:sysAdmin"
pwd: "pass123"
roles: ["readWrite", "dbAdmin”]
}
);
{ ok:: 1}
test>

3. Remove Users

For removing the user, the [Link]() is used.

Syntax

[Link](username)

For example

test> db. dropUser("sysAcin");


{ ok: 1}
test>

17
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

By above command the user named "sysadmin" is removed.


Users.
4. Explain with suitable example how to create database administrator
account in MongoDB?
Access Control

 User exists in context of a single database. MongoDB provides


authentication and authorization at database level.
 For basic authentication purposes, MongoDB stores user credentials
inside a collection called system. users in each database.
 The admin database does not have any users assigned to it.
 The User administrator account provides the ability to create user
accounts in the admin and other databases.
1. Creating a User Administrator Account

 For configuring the access control, the first step is to implement


User Administrator account.
 User Administrators create users and create and assigns roles. A User
Administrators can grant any privilege in the database and can create
new ones.
 In a MongoDB deployment, create the User Administrator as the first
user. But it cannot manage the database.

 Syntax for creating the user administrator account is as follows -


use admin
[Link](
user:"<usernamne>",
Pwd:"<password>",
Roles: ["userAdminAnyDatabase]})

For example
test> use admin
switched to db admin
admin> [Link](
{
user:"sysadmin”,
pwd:"system123”,
roles: [“userAdminAnyDatabase”]})
{ ok: 1 }
admin> show users

Note that the administrator user is now sysadmin with password system123.
we can authenticate the admin database using [Link] coommand with user
name and password options
test> use admin
switched to db admin
18
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

admin> [Link]("sysadmin”, ”system123)


If a wrong password is used then it gives the authentication error
admin> use admin
already on db admin
admin> [Link] ("sysadmin", "pass123");
MongoServerError: Authentication failed.
admin>

2. Creating Database Administrator Account

For creating a Database Administrator account, the createUser method is


used. The assign the roles such as
readWriteAnyDatabase,
dbAdminAnyDatabase,
clusterAdmin.

For Example
test> use admin
Switched to db admin
admin> [Link](
user: "dbAdmin",
pwd: password123"
admin>
roles:
["readWriteAnyDatabase","dbAdminAnyDatabase""clusterAdmin"]
}
);
{ ok: 1 }
admin>
We can use this user in MongoDB shell to administer the database.

5. What are the data types used in MongoDB? Explain in detail.

Following are various types of data types supported by MongoDB.

1. Integer: This data type is used for storing the numerical value.
2. Boolean: This data type is used for implementing the Boolean values
[Link] or false.
3. String: This is the most commonly used data type used for storing the
string values
4. Double: Double is used for storing floating point data.
5. Min/Max keys: This data type is used to compare a value against the
highest BSON element.
6. Arrays: For storing an array or list of multiple values in one key, this
data used.
7. Object: The object is implemented for embedded documents.
8. Symbol: This data type is similar to string data type. This data type is
used specific symbol type.

19
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

9. Null: For storing the null yalues this data type is used.
10. Date: This data type is used to store current date or time. We can also
own date or time object.
11. Binary data: In order to store binary data, we need to use this data
type.
12. Regular expression: This data type is used to store regular expression.

6. Write the MongoDB command to create and drop the


[Link] Databases.

Write the MongoDB command to create and drop the database.


operations.

In this section we will discuss how to create and handle database in


MongoDB using
various commands.

(1) Create Database


For example
Open the command prompt and type the command mongosh for starting the
mongDB shell.
The test> prompt will appear. For creating a database we need to “use” the
command.
Syntax
use Database_name

Example
test> use mystudents
Switched to db mystudents
mystudents>
d to db mystudents
To check the currently selected database, use the command db
mystudents> db
mystudents
mystudents>

(2) Displaying all the databases present in the system

We can see the list of databases present in the MongoDB using the
command show dbs
For example
mystudents> show dbs
Admin 180.06 KiB
config 72.00 KiB
Local 72.00 kiB
mystudents>

20
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

Note that in above listing we can’t see the mystudents database. This is
because we have not inserted any document into it. To get the name of the
database in the listing by means of show command, there should be some
record present in the database.

(3) Drop Database


The dropDatabase() command is used to delete the database. For example -
Mystudents> [Link]()
{ ok: 1,dropped: ‘mystudents’ }
mystudents>

7. Explain with suitable examples, CRUD operations in MongoDB.


Illustrate the following operation with suitable example
(i) Create MongoDB Database
(ii) Create Collection
(iii) Insert documents into a MongoDB database.
(iv) Find and select data from a mongoDB collection.
(v) Uddate a document.(Nov/Dec-2023)

Explain in detail about Query object to fetch the data from MongoDB with relavent
code snippets. (7) (Nov/Dec-2024)
Illustrating about sorting and Result set and finding distinct values from a MongoDB
collection. (6) (Nov/Dec-2024)
Explain CRUD operations over the collections and documents stored in the MongoDB with
suitable example.(April/May-2025)

Managing Collections
After creating some sample database, we must create some collection
inside that [Link] can perform various operations such as insert, delete
and update on this collection. These operations are called CRUD operations.
CRUD stands for Create, Read. Update and Delete operation.

1. Create Collection

Syntax
We can create collection explicitly using createCollection command.
[Link] Collection(name, options)
where
name is the name of collection
options is an optional field. This field is used to specify some parameters
such as Size, maximum number of documents and so on.

21
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
Following is a list of such options.

Field Type Description


Capped Boolean Capped collection is a fixed size collection. It
automaticallyoverwrites the oldest entries when
it reaches to maximum [Link] it is set to true,
enabled a capped collection. When you specify
this value is true, you need to specify the size
parameter.
autolndexID Boolean This field is required to create index id
automatically. Its detault value is false.
size Number This value indicates the maximum size in bytes
for a clapped collection.
Max Number It specifies the maximum number of
documents allowed in capped collection.
Table 3.3 Options for create collection
For example - Following command shows how to create collection in a
database using explicit command

test> use myStudents


Switched to db mystudents
myStudents> [Link]("Student_details”)
{ ok: 1 }
Mystudents>

2) Display Collection

To check the created collection use the command "show collections" at the
commarnd prompt
myStudents> show collections
Student_details
myStudents>

3) Drop Collection

The drop collection command is actually used to remove the collection


completely from the database. The drop command removes a collection
completely from database.

Syntax

[Link] [Link]()

For Example

my Students> db.Student_details.drop()
true
my Students>

We can verify the deletion of the collection by using "show collections" in the
22
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
database.

myStudents> show collections


myStudents>

4) Insert documents within the collection

The document is inserted within the collection. The document is


analogous to rows in database
Syntax
[Link] [Link]( {key, value }

23
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

For example
myStudents> show collections
nyStudents> [Link] Collection("stedent details)
{ ok: 1}

myStudents> db.Student_details.insert(nameAAA" age":2})


acknowledged : true,

myStudents>
insertedIds:{ '0': 0bjectId("643e4b63436497399alala66")}
}
myStudents>

We can verify this insertion by issuing following command


myStudents> db. [Link]()
[{ _id: Object Id ("643e4b63436497399al a2 a66"), name: AAA, age: 22 }]
myStudents>

5) Inserting Multiple Documents


It is possible to insert multiple documents at a time using a single
command. Following program shows how to insert multiple documents in the
existing collection.
my Students> var all_students. =
[
{
“name”: “BBB”
“age":20
},
{
“name" : "DDD”
“age":21
},
];
acknowledged :true,
ent [Link]()
myStudents> [Link] detaits . Insert(allstudents);
insertedIds: { ‘0’ : ObjectId ("643e518d436197399ala2a67”)
‘1': “ObiectId"643e518d436497399aia2a68”)
}
}
myStudents>

To verify the existence of these documents in the collection you can use find
command as
follows -
myStudents> db.Student_details. find()
{-id: ObjectId ("643e4b63436497399ala2a66"), name: ‘AAA’ ,age: 22 }
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘BBB’, age: 21,}
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘DDD’, age: 20,}
24
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

}
myStudents>

6) Delete Documents
For deleting the document, the remove command is used. This is the
simplest command
Syntax
db.collection_name.remove(delete_criteria)

For example
First of all we can find out the documents presents in the collection using
find() command
myStudents> db.Student_details. find()
[
{-id: ObjectId ("643e4b63436497399ala2a66"), name: ‘AAA’ ,age: 22 }
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘BBB’, age: 21,}
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘DDD’, age: 20,}
]
myStudents>
Now to delete a record with name “DDD” we can issue the command as
follows-
myStudents> [Link] [Link]( {“name”: “DDD” });
{ acknowledged: true, deletecount: 0}
myStudents>
Now using find() command we can verify if the desired data is deleted
or not.
myStudents> db.Student_details. find()
{-id: ObjectId ("643e4b63436497399ala2a66"), name: ‘AAA’ ,age: 22 }
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘BBB’, age: 21,}
}

7. Delete all documents

For deleting all the documents from the collection,we can [Link]()
For example
myStudents> [Link] [Link]( { });
{ acknowledged: true, deletecount:2}
myStudents>
We can verify it using db.Student_details.find() command,we can verify that
records are deleted or not.
myStudents> db.Student_details. find()
myStudents>

8. Update Documents

For updating the document, we have to provide some criteria based on


which the document can be updated.

db.collection_name.update(criteria, update_data)

25
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

For example - Suppose the collection "Student_details” contain following


documents
myStudents> db.Student_details.find()
[
{-id: ObjectId ("643e4b63436497399ala2a66"), name: ‘AAA’ ,age: 22 }
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘BBB’, age: 21,}
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘DDD’, age: 20,}
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘CCC’, age: 23,}

]
myStudents>

And we want to change the name CCC" to WWW", then the command
can be issued as
myStudents>db.Student_detaits.update({“name:”CCC”},{set:{“name”:”WWW”}})
DeprecationlWarning: Collection. update () is deprecated. Use updateOne,
updateMany, or bulkwrite.
{
acknowledged : true,
InsertedId: null,
matchedCount: 1,
modifiedCount:1,
upsertedCount:0
}

It can be verified using [Link] [Link]() command


my Students> db.Student_details .find().
[
{-id: ObjectId ("643e4b63436497399ala2a66"), name: ‘AAA’ ,age: 22 }
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘BBB’, age: 21,}
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘DDD’, age: 20,}
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘WWW’, age:
23,}
]
myStudents>

Thus the document gets updated.

By default the update command updates a single document. But we can


update multiple document as well. For that purpose we have to add

db. Student details. update({ "age"21}, ($set:{"age":23}},{multi:true})

9. Sorting

We can use the sort() method for arranging the documents in


ascending or descending order based on particular field of document.
Syntax

26
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

For displaying the documents in ascending order we should pass value 1


db collection name. find().sort ({field name:1})
If we pass -1 then the document will be displayed in the descending order of
the field
For example
Suppose the collection contains following documents.
myStudents> db.Student_details. find()
[
{-id: ObjectId ("643e4b63436497399ala2a66"), name: ‘AAA’ ,age: 22 }
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘BBB’, age: 21,}
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘DDD’, age: 20,}
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘CCC’, age: 23,}
]
myStudents>

For sorting the documents in descending order sort command is used.


myStudents> db.Student_details. find()
[
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘CCC’, age: 23},
{-id: ObjectId ("643e4b63436497399ala2a66"), name: ‘AAA’ ,age: 22 },
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘BBB’, age: 21},
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘DDD’, age: 20},
]
myStudents>

If we want to display data in ascending order, we issue following command


myStudent> db.Student_ [Link]().sort{“age”:1})
For Example:
myStudents> db.Student_details. find()
[
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘DDD’, age: 20},
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘BBB’, age: 21},
{-id: ObjectId ("643e4b63436497399ala2a66"), name: ‘AAA’ ,age: 22 },
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘CCC’, age: 23},
]
myStudents>

27
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

8. What are the steps to connect [Link] with MongoDB ?

For connecting the [Link] with MongoDB we use MongoClient


Following are the steps used to connect [Link] with MongoDB

Step 1: Install MongobB driver for [Link] by issuing following command on


the command prompt
npm install mongodb

Step 2: In the [Link] application program require the MongoDB module by


adding following line of code

const MongoClient = require(‘mongodb’).MongoClient;

Step 3: Define MongoDB Connection URL

const url = “mongodb//[Link]:27017/myStudents";

Step 4: Create the instance of MongoClient by passing the above URL to it.
It is as follows -

const client = new MongoClient(url);

Step 5: Finally use the connect method to get connected with the database

[Link]()

The complete code is as follows -

[Link]
// get the mongoDB client

const MongoClient = require('mongodb'), MongoClhent;

//Specify the URL of the database to which the connection is to be


done
const url= mongodb://[Link]:27017/myStudents

//Create client instance

const client = new MongoClient(url);

//Connect to the database

function getData()
{
[Link]()
then(() =>[Link] ("Connected to Database Successtully!!!”))
catch(error=> [Link](Failed to Connect’,error)
28
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

}
getData():

Program Explanation: In above code,


1) First of all, we have to import the module 'mongodb' using require. Thus
we are creating MongoDB client.

2) Then specify the URL for MongoDB by means of hostname(localhost)


and port number on which MongoDB is running (27017). This is a path
at which we are going to create a database.

3) Then we are using connect method by passing the above database


object is created by a database name "myStudents”.
Note that before execution of the above code, it is necessary to install the
mongodb package using the following command at the current working directory.
Prompt:>npm install mongodb

29
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

9. Explain the MongoDBClient object and the methods associated with


it.
The MongoDBClient
The MongoDBClient object provides interactions to connect to the database,
Following are some commonly used method of MongoDBClient object
Method purpose

connect( url,options) This method is used to connect to the MongoDB


using the specified url
close(force, callback) This method closes the db and underlying
connections.
db(dbname, options) It creates a new DB instance sharing the current
socket connections.
isConnected(options) It checks if MongoClient is connected.

Table 3.4 Methods in MongoDBClient


[Link] the db object and the methods associated with it.
The db object
The db object is created for connecting to the database in MongoDB,
Following are commonly used methods of db object -

Method Purpose

addUser(username, It adds user to the database


password, callback)
admin() This method returns Admin db instance.
collection(name, options, Fetch a specific collection. The name is a
callback) collection name we wish to access. The
callback function accepts error and names
parameters where names is an array of
collection names.
Collections(options,callbacks) This method fetches all the collections for
current db.
createCollection(name, This method is used to create a new
options,call back) collection on a server with the specified
options.
dropCollection(name, It drops the collection from the database,
options, callback) removing it permanently.
listCollections(filter, options) This method is used to get the list of all the
collection information for the specified db

Table 3.4 Methods in DBObject

30
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

[Link] is CRUD? Explain the CRUD operation in [Link].


Explain various way to perform standard CRUD operations via the
MongoShell with suitable example. (April/May -2024)
In this section we will discuss basic CRUD operations on MongoDB. CRUD
stands for Create, Read, Update and Delete. The CRUD operations are
performed in collaboration with [Link] and MongoDB.
Prerequisite: For performing these operations we need to have MongoDB
installed in our machine. One must also install MongoDB Compass (It is a
graphical tool) to verify the operations performed by [Link] on MongoDB.
Example Code: In this example, we will create a Student database with two
fields – name and city.
[Link] of collection
Step 1: We will create a database studentDB. For that purpose make a
folder in your current
working directory. I have created the folder by a name StudentDBDemo.
Step 2: Open the command prompt go to the path of StudentDBDemo. And
issue the commands
D:\Node JSExamples\StudentDBDemo>npm init
And press enter key to accept the default values. By this [Link] file
gets created. install mongodb
Step 3: Then install the mongodb module using following command
D:\Node JSExamples\StudentDBDemo>npm install
mongodb
Step 4: Now create a [Link] file for creating a database and collection. The
code is as
const MongoClient = require('mongodb'), MongoClient;
Example program:[Link]
[Link]
const MongoClient = require('mongodb'), MongoClient;
const url =”mongodb://[Link].27017”;
const client new MongoClient(url);
//Connect to the dabase
const clatabase = "studontsDB;
async function getData()
{
31
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

let result = awvait [Link]();


let dbo = [Link](database)
[Link](“Student_Info”);
[Link]('Collection Created!!!;
}
getData():
Output is

PS E:\NodeJ SExamples\studentDBDemo> node [Link]

Collection Created!!!

Programn Explanation: n above codc,

2) Insertion of document
1) First of all. we have to import the module mongodb' using require, Thus
we are creating mongodb client
2) Then specify the URL for MongoDB by means of hostname (localhost or
[Link])
and port number on which MongoDB is running (27017). This is a path at
which we are going to create a database.
3) Then we are using connect method by passing the above URL. Inside this
function a database object is created by a database name "studentsDB".
4) Then using the method createCollection for database object we can create
a collection inside the database "studentsDB", Note that here the collection
name is "Student_Info".
5) The message "Collection Created!!!" is displayed on the console using
[Link] method.
Once the collection is created, we can insert some document into it.
Following is an example code which shows how to insert one document into
a collection named Student_info
const MongoClient = require(mongodb).MongoClient;
const url='mongodb://[Link]:27017";
const client = new MongoClient(url):
// Connect to the database
const database = "studentsDB":

32
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

async function getData()

{
let result = await [Link]():
let dbo [Link](database):
var mydata = mame:"Ankita',city:"Pune'}:
[Link]('Student_ Info").insertOne(mydata):
[Link](Data Inserted!||"):
}
getData():

Output is
PS E:\NodeJ SExamples\studentDBDemo> node [Link]
Data Inserted !!!
Program explanation: In above code,
1. First of all, we have to import the module 'mongodb' using require.
Thus we are creating MongoDB client.
2. Then specify the URL for MongoDB by means of hostname(localhost)
and port number on which MongoDB is running(27017). This is a
path at which our database exists.
3. Then we are using connect method by passing the above URL. Inside
this function a database object is created by a database name
studentDB". Thus now we can access to studentDB
4. Then a JSON object is in the form {name:value}. We insert data in the
collection in the form of document. This document is čreated in the
form of JSON, Hence the mydata object is created with some values.
This mydata is inserted into the collection using insertOne method
using following code
[Link] ("Student Info"),insertOne(mydata)
In the same manner we can insert many documents in the collection.
const MongoClient = require('mongodb'), MongoClient;
const url =”mongodb://[Link].27017”;
const client new MongoClient(url);
//Connect to the dabase
const clatabase = "studontsDB;
async function getData()
33
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

{
let result = awvait [Link]();let dbo = [Link](database)
var mydata =[
{ name: “BBB”, city: "Mumbai" },
{ name: “CCC”, city: "Chennai' },
{ name: “DDD”, city: "Delhi' }.
{ name: "EEE”, city: "Ahmedabad'" }
[Link]('Student Info"). insertMany (mydata);
console. log(“Multiple documents Inserted!!!");
getData();

Output is
PS E: \Node JSExamples\studentDBDemO node [Link]
Multiple documents Inserted!!!
Program explanation: In above code we have created array of values in
JSON object as follows
var mydata =[
{ name: "BBB", city: "Mumbai" },
{ name: "CCC", city: "Chennai' },
{ name: "DDD', city: "Delhi' },
{ name: "EEE", city: "Ahmedabad'}
];
Then using the insertMany command we can insert all the above documents
at a time This program execution can be verified in MongoDB compass.
Open MongobB Compass, just connect with mongodb://ocalhost:27017,
select the StudentDB database and then select Student Info collection. The
following screenshot displays multiple documents inserted into it.

34
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

3. Displaying (Read) the data from Collection


We can read all the documents of the collection using find method.
Following is a simple
[Link] code that shows how to read the contents of the database.

const MongoClient = require('mongodb'), MongoClient;


const url =”mongodb://[Link].27017”;
const client new MongoClient(url);
//Connect to the dabase
const clatabase = "studontsDB;
async function getData()
{
let result = awvait. [Link]();
35
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

let dbo = [Link](database)


[Link]("Student_ Info');
let response = await collection, find(). toArray();
console. log(response);
}
getData();

Program explanation: In above code,


4) First of all, we have to import the module mongodb using require. Thus
we are creating MongoDB client.
5) Then specify the URL for MongoDB by means of hostname(localhost) and
port number on which MongoDB is running (27017). This is a path at which
our database exists.
6) Then we are using connect method by passing the above URL. Inside this
function a database object is created by a database name studentDB", Thus
now we can accesss to studentDB.

36
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

4. Update document
Then for reading the contents present in the documents of the collection we
use the find() method.
We use to Array method associated with the fimd() because it returns an
array that contains all documents returned by the cursor.
We can modify the document using updateOne method. Following code
illustrates it -
[Link]
const MongoClient = require('mongodb'), MongoClient;
const url =”mongodb://[Link].27017”;
const client new MongoClient(url);
//Connect to the dabase
const clatabase = "studontsDB;
async function getData()
{
let result = awvait [Link]();
let dbo = [Link](database)
var mydata = { name: "DDD'};
var newdata = {$set: name:"TTT”, city:" Jaypur”}
[Link]("Student Info").updateOne (mydata newdata);
[Link] ("One Document Updated!");
}
getData);
Output
PS E:\NodeJSExamples\studentDBDenO> node update. js
One Document Updated!!!
We can verify the above updation in MongoDB Compass. Just open the
database StudentDB using MongoDB Compass to see the modification.

37
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

5. Delete document
This is the operation in which we are simply deleting the desired document.
Here to delete a single record we have used deleteOne method.
The code as follows-
[Link]
const MongoClient = require('mongodb'), MongoClient;
const url =”mongodb://[Link].27017”;
const client new MongoClient(url);
//Connect to the dabase
const clatabase = "studontsDB;
async function getData()
{
let result = awvait. [Link]();
let dbo = [Link](database)
var mydata = { name: "TTT":};
}
//Delete the document
[Link]('Student Info"). deleteOne (mydata):
[Link]('One Document Deleted");
}
getData():

38
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

OUTPUT
PS E:\NodeJ SExamples \studentDBDemo> node [Link]
One DocUment Deleted!!!
We can verify it using MongoDB Compass. Note that the name TTT" is
missing.

The above deletion operation can be verified by displaying the contents of


the collection

39
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

6. sorting

Data can be arranged in sorted order in the collection. For displaying


the sorted ordered data, we use the method sort. Following code illustrates
how to display the data in ascending order of the filed named city.
const MongoClient = require('mongodb'), MongoClient;
const url =”mongodb://[Link].27017”;
const client new MongoClient(url);
//Connect to the dabase
const clatabase = "studontsDB;
async function getData()
{
let result = awvait. [Link]();
let db = [Link](database)
let collection = [Link]("Student Info"):
var mydata = {city:1}:
let response = await [Link]({}).sort(mydata).toAray();
[Link](response);
}

40
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

getData():

Output

41
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

12. Design a signup form using [Link] and MongoDB. The form should capture
name, email, password and mobile number from the user and captured
information are stored in mongoDB. (Nov/Dec -2023)

To design a signup form using [Link] and MongoDB, you'll need to set up a [Link]
server, create routes to handle the form submission, and use MongoDB to store the
captured information. Here's a step-by-step guide to achieve this:

Step 1: Set Up Your [Link] Project

Initialize your project:

mkdir signup-form
cd signup-form
npm init -y
Install necessary packages:

npm install express mongoose body-parser bcryptjs

Step 2: Create the Server and Routes

Create the server file ([Link])

const express = require('express');


const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const app = express();


const port = 3000;

// Connect to MongoDB
[Link]('mongodb://localhost:27017/signupDB', { useNewUrlParser: true,
useUnifiedTopology: true });

// Create a schema and model for User


const userSchema = new [Link]({
name: String,
email: String,
password: String,
mobile: String
});

const User = [Link]('User', userSchema);

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

42
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

// Serve static files


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

// Routes
[Link]('/', (req, res) => {
[Link]( dirname + '/public/[Link]');
});

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


const { name, email, password, mobile } = [Link];

// Hash the password


const hashedPassword = await [Link](password, 10);

// Create a new user


const newUser = new User({
name,
email,
password: hashedPassword,
mobile
});

// Save the user to the database


[Link]((err) => {
if (err) {
[Link]('Error occurred while saving the user.');
} else {
[Link]('User signed up successfully!');
}
});
});

// Start the server


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

Step 3: Create the HTML Form

Create the public directory and the HTML file (public/[Link])

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Signup Form</title>
</head>
<body>
<h1>Signup Form</h1>
43
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

<form action="/signup" method="post">


<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br><br>

<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required><br><br>

<label for="password">Password:</label><br>
<input type="password" id="password" name="password" required><br><br>

<label for="mobile">Mobile Number:</label><br>


<input type="text" id="mobile" name="mobile" required><br><br>

<input type="submit" value="Signup">


</form>
</body>
</html>

Step 4: Run the Application

1. Start your MongoDB server:

[Link] your browser and navigate to [Link] Fill in the form


and submit it
to test the signup functionality.

44
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

13. Illustrate how to connect a [Link] application to a mongodb database


with suitable code. (April/May -2024)

To connect a [Link] application to a MongoDB database, you will need to use the
mongoose library, which is an Object Data Modeling (ODM) library for MongoDB and
[Link]. Here's a step-by-step guide along with suitable code to illustrate this process:

Step 1: Install Dependencies

First, make sure you have mongoose installed in your project:

npm install mongoose

Step 2: Set Up Mongoose Connection

Create a file, for example, [Link], to handle the connection logic:

const mongoose = require('mongoose');

const connectDB = async () => {


try {
const conn = await
[Link]('mongodb://localhost:27017/yourDatabaseName', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true, // Only necessary if using indexes
useFindAndModify: false // Only necessary if using findAndModify
});

45
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

[Link](`MongoDB Connected: ${[Link]}`);


} catch (err) {
[Link](`Error: ${[Link]}`);
[Link](1); // Exit process with failure
}
};

[Link] = connectDB;

Step 3: Integrate the Connection in Your Application

In your main server file (e.g., [Link]), import and use the connectDB function:

const express = require('express');


const connectDB = require('./database');

const app = express();


const port = 3000;

// Connect to MongoDB
connectDB();

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


[Link]('Hello World!');
});

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

Step 4: Define a Mongoose Schema and Model

Create a file, for example, models/[Link], to define a schema and model for the data
you want to store:

const mongoose = require('mongoose');

const userSchema = new [Link]({


name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,

46
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

required: true
},
mobile: {
type: String,
required: true
}
});

const User = [Link]('User', userSchema);

[Link] = User;

Step 5: Use the Model in Your Application

In your main server file or routes, use the User model to interact with the database. For
example, handling user registration:

const express = require('express');


const bodyParser = require('body-parser');
const bcrypt = require('bcryptjs');
const User = require('./models/User');
const connectDB = require('./database');

const app = express();


const port = 3000;

// Connect to MongoDB
connectDB();

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

// Routes
[Link]('/signup', async (req, res) => {
const { name, email, password, mobile } = [Link];

try {
// Hash the password
const hashedPassword = await [Link](password, 10);

// Create a new user


const newUser = new User({
name,
email,
password: hashedPassword,
mobile
});

// Save the user to the database


await [Link]();

47
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

[Link]('User signed up successfully!');


} catch (err) {
[Link](err);
[Link]('Error occurred while saving the user.');
}
});

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

14. A technical institute in Tamil Nadu offering six different under-graduate


programmes in engineering. The institute admit the students to these
programmes based on the average marks obtained in the HSC. Students
seeking admission can submit only one application form and he/she can give
maximum three programmes choices according to their choice of preferences
in the application form. Develop a web based online application form to
capture the required student details including programme preferences and
store them in a database. On successful submission of application form, the
student will be informed a confirmation message through email and SMS to
registered mobile number.
( Nov/Dec – 2023)

Creating a web-based online application form for the technical institute involves similar
steps as the blood donor registration system. Here’s a step-by-step guide to implement
the online application system:

Step 1: Set Up the Project Environment

 Ensure you have [Link] and MongoDB installed.


 Create a new directory for your project and initialize it:

install necessary dependencies:

Step 2: Create the Front-End Form

Create an [Link] file for the student application form:

48
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Application Form</title>
</head>
<body>
<h1>Student Application Form</h1>
<form id="applicationForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>

<label for="mobile">Mobile Number:</label>


<input type="text" id="mobile" name="mobile" required><br><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>

<label for="address">Address:</label>
<input type="text" id="address" name="address" required><br><br>

<label for="hscMarks">Average HSC Marks:</label>


<input type="number" id="hscMarks" name="hscMarks" required><br><br>

<label for="programme1">Programme Preference 1:</label>


<select id="programme1" name="programme1" required>
<option value="programme1">Programme 1</option>
<option value="programme2">Programme 2</option>
<option value="programme3">Programme 3</option>
<option value="programme4">Programme 4</option>
<option value="programme5">Programme 5</option>
<option value="programme6">Programme 6</option>
</select><br><br>

<label for="programme2">Programme Preference 2:</label>


<select id="programme2" name="programme2" required>
<option value="programme1">Programme 1</option>
<option value="programme2">Programme 2</option>
<option value="programme3">Programme 3</option>
<option value="programme4">Programme 4</option>
<option value="programme5">Programme 5</option>
<option value="programme6">Programme 6</option>
</select><br><br>

<label for="programme3">Programme Preference 3:</label>


<select id="programme3" name="programme3" required>
<option value="programme1">Programme 1</option>
<option value="programme2">Programme 2</option>
<option value="programme3">Programme 3</option>
<option value="programme4">Programme 4</option>
49
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

<option value="programme5">Programme 5</option>


<option value="programme6">Programme 6</option>
</select><br><br>

<button type="submit">Submit</button>
</form>

<script>
[Link]('applicationForm').addEventListener('submit',
function(event) {
[Link]();

const formData = new FormData(this);


const data = {};

[Link]((value, key) => {


data[key] = value;
});

fetch('/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: [Link](data)
})
.then(response => [Link]())
.then(data => {
alert([Link]);
})
.catch(error => {
[Link]('Error:', error);
});
});
</script>
</body>
</html>

Step 3: Set Up the Back-End Server

Create a [Link] file for the Express server:

const express = require('express');


const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const nodemailer = require('nodemailer');
const twilio = require('twilio');

// Initialize Express app


const app = express();

50
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

// Use body-parser middleware


[Link]([Link]());

// Connect to MongoDB
[Link]('mongodb://localhost:27017/studentApplicationDB', {
useNewUrlParser: true, useUnifiedTopology: true });

// Define a schema and model for student applications


const studentSchema = new [Link]({
name: String,
mobile: String,
email: String,
address: String,
hscMarks: Number,
programme1: String,
programme2: String,
programme3: String
});

const Student = [Link]('Student', studentSchema);

// Nodemailer setup for email


const transporter = [Link]({
service: 'gmail',
auth: {
user: 'your-email@[Link]',
pass: 'your-email-password'
}
});

// Twilio setup for SMS


const twilioClient = new twilio('your-twilio-account-sid', 'your-twilio-auth-token');

// Endpoint to handle form submissions


[Link]('/submit', async (req, res) => {
const student = new Student([Link]);
try {
await [Link]();

// Send email confirmation


const mailOptions = {
from: 'your-email@[Link]',
to: [Link],
subject: 'Application Submission Confirmation',
text: `Thank you ${[Link]} for applying. Your application has been
received.`
};

[Link](mailOptions, (error, info) => {


if (error) {
return [Link](error);
51
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

}
[Link]('Email sent: ' + [Link]);
});

// Send SMS confirmation


[Link]({
body: `Thank you ${[Link]} for applying. Your application has been
received.`,
from: '+1234567890', // Your Twilio number
to: [Link]
}).then(message => [Link]([Link]));

[Link]({ message: 'Application submitted successfully!' });


} catch (error) {
[Link](400).json({ message: 'Application submission failed', error });
}
});

// Serve the HTML form


[Link]('/', (req, res) => {
[Link]( dirname + '/[Link]');
});

// Start the server


const PORT = [Link] || 3000;
[Link](PORT, () => {
[Link](`Server is running on port ${PORT}`);
});

Step 4: Run the Application

 Start your MongoDB server if it's not already running.

Start your [Link] server

52
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

15. Assume that a well-known private hospital in Tamil Nadu is running a blood
bank for their patients. Any donor who is interest to donate the blood can
register with the hospital for donating blood. The hospital is interested to
introduce the online registration system. Develop a web based donor
registration system to capture information about the donor such as name,
mobile number, email, address, blood group, age, gender and store them in a
database. On successful submission of registration form, the donor will be
informed a confirmation message through email and SMS to registered mobile
number. Nov/Dec -2023)

Developing a web-based donor registration system involves several steps, including creating the front-end
form for data collection, setting up the back-end server to handle form submissions, storing the data in a
database, and integrating email and SMS services to send confirmation messages. Here's a high-level
overview of the process:

1. Set Up the Project Environment:


o Choose a tech stack. For simplicity, let's use HTML/CSS/JavaScript for the front-end,
[Link]/Express for the back-end, MongoDB for the database, and a service like Twilio for SMS
and Node mailer for email notifications.
2. Create the Front-End Form:
53
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

o Design an HTML form to capture the donor's details.


3. Set Up the Back-End Server:
o Create an Express server to handle form submissions and interact with the database.
4. Store Data in the Database:
o Set up MongoDB to store donor information.
5. Send Confirmation Messages:
o Use Twilio's API to send SMS notifications and Nodemailer for email notifications.

Here’s a step-by-step guide to implement this:

Step 1: Set Up the Project Environment

 Ensure you have [Link] and MongoDB installed.


 Create a new directory for your project and initialize it:

Step 2: Create the Front-End Form

Create an [Link] file for the registration form:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blood Donor Registration</title>
</head>
<body>
<h1>Blood Donor Registration Form</h1>
<form id="donorForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>

<label for="mobile">Mobile Number:</label>


<input type="text" id="mobile" name="mobile" required><br><br>

54
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>

<label for="address">Address:</label>
<input type="text" id="address" name="address" required><br><br>

<label for="bloodGroup">Blood Group:</label>


<input type="text" id="bloodGroup" name="bloodGroup" required><br><br>

<label for="age">Age:</label>
<input type="number" id="age" name="age" required><br><br>

<label for="gender">Gender:</label>
<select id="gender" name="gender" required>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select><br><br>

<button type="submit">Register</button>
</form>

<script>
[Link]('donorForm').addEventListener('submit', function(event)
{
[Link]();

const formData = new FormData(this);


const data = {};

[Link]((value, key) => {


data[key] = value;
});

fetch('/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: [Link](data)
})
.then(response => [Link]())
.then(data => {
alert([Link]);
})
.catch(error => {
[Link]('Error:', error);
});
});
</script>
</body>
55
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

</html>

Step 3: Set Up the Back-End Server


Create a [Link] file for the Express server:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const nodemailer = require('nodemailer');
const twilio = require('twilio');

// Initialize Express app


const app = express();

// Use body-parser middleware


[Link]([Link]());

// Connect to MongoDB
[Link]('mongodb://localhost:27017/bloodDonorDB', { useNewUrlParser:
true, useUnifiedTopology: true });

// Define a schema and model for donors


const donorSchema = new [Link]({
name: String,
mobile: String,
email: String,
address: String,
bloodGroup: String,
age: Number,
gender: String
});

const Donor = [Link]('Donor', donorSchema);

// Nodemailer setup for email


const transporter = [Link]({
service: 'gmail',
auth: {
user: 'your-email@[Link]',
pass: 'your-email-password'
}
});

// Twilio setup for SMS


const twilioClient = new twilio('your-twilio-account-sid', 'your-twilio-auth-token');

// Endpoint to handle form submissions


[Link]('/register', async (req, res) => {
const donor = new Donor([Link]);
try {
await [Link]();

56
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

// Send email confirmation


const mailOptions = {
from: 'your-email@[Link]',
to: [Link],
subject: 'Blood Donation Registration Confirmation',
text: `Thank you ${[Link]} for registering as a blood donor!`
};

[Link](mailOptions, (error, info) => {


if (error) {
return [Link](error);
}
[Link]('Email sent: ' + [Link]);
});

// Send SMS confirmation


[Link]({
body: `Thank you ${[Link]} for registering as a blood donor!`,
from: '+1234567890', // Your Twilio number
to: [Link]
}).then(message => [Link]([Link]));

[Link]({ message: 'Registration successful!' });


} catch (error) {
[Link](400).json({ message: 'Registration failed', error });
}
});

// Serve the HTML form


[Link]('/', (req, res) => {
[Link]( dirname + '/[Link]');
});

// Start the server


const PORT = [Link] || 3000;
[Link](PORT, () => {
[Link](`Server is running on port ${PORT}`);
});

57
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

[Link] the below MongoDB collection (Nov/Dec-2024)


Structure of 'restaurants' collection: 1.
"address":
{ "building": "1007", "coord": [-73.856077, 40.848447 1. "street": "Morris Park Ave", "zipcode": "10462" },
"borough": "Bronx". "Cuisine": "Bakery", ). ["date": ("$date": 1393804800000), "grade": "A", "score": 2},
"grades":[ ("date": ["$date": 1378857600000), "grade": "A", "score": 6),
["date": ("$date": 1358985600000), "grade": "A", "score": 10),
["date": ("$date": 1322006400000), "grade": "A", "score": 9).
["date": ["$date": 1299715200000), "grade": "B", "score": 14)
"name": "Morris Park Bake Shop", "restaurant_id": "30075445"
Write MongoDB queries to answer the following questions:
(i)display the fields restaurant id, name, borough and cuisine for all the
documents in the collection restaurant.

(ii) display the first 5 restaurant which is in the borough Bronx.

iii) find the restaurants that achieved a score, more than 80 but less than 100.

(iv) find the restaurants which do not prepare any cuisine of 'American' and
achieved a grade point 'A' not belongs to the borough Brooklyn. The
document must be displayed according to the cuisine in descending order.

(v) find the restaurants that have a grade with a score of 2 and a grade with a
score of 6 and are located in the borough of Manhattan or Brooklyn, and
their cuisine is not American or Chinese.

58
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
(i) Display the fields restaurant_id, name, borough,

[Link](
{},
{
restaurant_id: 1,
name: 1,
borough: 1,
cuisine: 1,
_id: 0
}
(ii) Display the first 5 restaurants in the borough "Bronx"

[Link](
{ borough: "Bronx" }
).limit(
(iii) Find restaurants that achieved a score more than 80 but less than 100
[Link](
{ "[Link]": { $gt: 80, $lt: 100 } }
)

This checks if any element in the grades array has a score in that range.

(iv) Restaurants that:

 Don't serve American cuisine


 Achieved a grade "A"
 Not in Brooklyn
 Sorted by cuisine (descending)

[Link](
{
cuisine: { $ne: "American" },
"[Link]": "A",
borough: { $ne: "Brooklyn" }
}
).sort({ cuisine: -1 })

(v) Restaurants with:

 A grade with score 2 AND


 A grade with score 6
 In Manhattan or Brooklyn
 Cuisine is NOT American or Chinese

[Link](
{
$and: [
59
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
{ "grades": { $elemMatch: { score: 2 } } },
{ "grades": { $elemMatch: { score: 6 } } },
{ borough: { $in: ["Manhattan", "Brooklyn"] } },
{ cuisine: { $nin: ["American", "Chinese"] } }
]
}

60
Prepared by: [Link], AP/IT
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Unit –IV
Implementing express in [Link] – Configuring routes – Using Request
and Response objects – Angular – TypeScript – Angular components –
Expressions – Data binding – build in directives.

Two Marks Questions with Answers

1. What is Express? Enlist the features. ( April/May-2024 )

Express is web application framework used in [Link]. It has rich set of


features that help in building flexible web and mobile applications.

Features of Express

1) Middleware: Middleware is a part of program, that accesses to the


database and respond to client requests.
2) Routing: Express JS provides a routing mechanism so that it is
possible to reach to different web pages using the URLs.
3) Faster server side development: It is very convenient to develop
server side development using Express JS.
4) Debugging: Express Js makes debugging easier by providing the
debugging mechanism.

2. How to installing the Express?


 Express is installed using Node Package Manager(npm). The command issued
for installing the express is,

Prompt:>npm install express

3. How to create a instance of express?

Create an instance of the express class. This instance acts as [Link] application.
Following lines create an instance of express
var express = require(express');
var app = express();

4. Define Request object in express application .

 The request object represents the HTTP request and contains properties for the
request query string, parameters, body and HTTP headers
 For example
 [Link]{'/, function([Link]){}}

Request object

5. Define Response object in express application

The Response object (res) specifies the HTTP response which is sent by an
Express app when it gets an HTTP request.
1
Full stack web Development -Unit -IV Express & Angular V Sem -IT

For example - app get('/', function(req, res){}}



Response object

6. What is TypeScript?

 Typescript is a typed superset of JavaScript. Any valid JavaScript code is


basically a valid code for typescript as well.
 Typescript extends JavaScript by adding data types, classes and other
object-oriented features with type-checking.
 The typescript compiles to plain JavaScript code.
 Typescript is a programming language developed and maintained by
Microsoft.
 Typescript may be used to develop JavaScript applications for both client
side and server side execution.

7. Enlist the features of Typescript.

1. Portability: Typescript is a portable because it can be executed on any


browser or operating system. It can run on any environment
where JavaScript runs.

2. JavaScript: The code written in JavaScript with [Link] extension can be


converted to Typescript by simply changing the extension from
.js to .ts.

3. Static Type checking: This feature allows type checking at compile.

4. Support for Library: For developing the Typescript coding we can use all
JavaScript frameworks, tools and libraries easily.

5. Support for OOP: The TypeScript can make use of various features of
object-oriented programming languages such as classes,
interfaces, inheritance and so on.

8. What is var and let concept in variables used in typescript?

var

The variable can be declared using the keyword var same as JavaScript. To
assign a value to the variable, use the equal sign.
var stutName = "Parth";

let

The let declaration follows the same syntax as var declaration. For example-

let empName" = “Archana”

The var declaration has some problems in solving programs, so ES6 introduced
let keyword to declare a variable in TypeScript and JavaScript. The let keyword
has some restriction in scoping in comparison of the var keyword.

2
Full stack web Development -Unit -IV Express & Angular V Sem -IT

9. How to write a class in TypeScript?

A class contains -

 Properties
 Constructor
 Methods

Syntax of declaring class

class <class_name> {
field;

method;
}

Example

class Person {
person id: number;
person name: string;
getName:string{
return "Parth";
}
}

10. Write a Typescript document for creation of object

An object is an instance of a class. The object is created using keyword new.


For example,

[Link]
class Person {
person id: number;
person name: string;
constructor(id: number, name: string) {
this person id=id;
this person name = name;
}}
Let p1 = new Person(101, "Parth")//object p1 is created
[Link](p1);

11. What is interface? Explain the use of interface in TypeScript with suitable
example.

 Interface is a structure which acts as a contract in our application. That


means, interface defines the syntax that an entity should have.
 The members of interfaces are properties, methods and events.
Syntax
 The typical syntax of interface is
interface interface_name {
3
Full stack web Development -Unit -IV Express & Angular V Sem -IT

property_type: data-type//declare properties, methods or events


...}

12. What is Type Annotations?

The TypeScript is a typed language. We can specify the data type of the variables
and functions. For specifying the type of the variable the syntax is

Variable_name:data type

Where data_type is any standard data type used in JavaScript. For example

var count: number = 100;


var empName = "Ankita":
var isChecked:boolean = true;

13. What is Anonymous function? Give an example of it.

The function without the name is called anonymous function. The type of
functions are dynamically declared at runtime.

For example -

let display = function)) //This is anonymous function


{
[Link]("Welcome");
}

display(); //call to the function

14. Explain arrow function in TypeScript

The fat arrow function is used for anonymous function. They are also called as
lambda functions.
Syntax (larg1,arg2, argN]) => expression {//function body}

By the use of => arrow we need not have to use the keyword function.

For example-

let addtion (amumber, b:number) number =>


{
return a+b;
}
[Link](addtion(10,20));

15. What is Angular?

Angular is a typescript based free and open source web application


framework led by the Angular team at Google and by a community of
individuals and corporations. Angular 10+ is a JavaScript framework which is
used to create Single Page Applications(SPAs).

4
Full stack web Development -Unit -IV Express & Angular V Sem -IT

16. What is the use of ngModule in Angular?

 Angular modules consolidate components, directives and pipes into


cohesive blocks of functionality.
 For defining the module we use the ngModule.
 Every Angular application has at least one NgModule class, the root
module, which is conventionally named AppModule and resides in a file
named [Link].

17. What are the main building blocks in angular architecture?

The main building blocks in angular architecture are-

[Link]
[Link]
[Link]
[Link] Binding
[Link]
[Link]
[Link] and Services.

18. Write about function used in typescript.

Functions are basic building blocks of any JavaScript document. It makes the
code reusable, readable and maintainable
The function can be defined as follows-

function function name(jarg1, arg2,..., argN) {

//body of function
}

The function can be called as follows.

Function_name[[argument]);

19. What is Expressions in Angular? Explain with an example.

Angular evaluates expressions and then can dynamically add the results to a
web page. Expressions are encapsulated blocks of code inside brackets as
follows-

({ expression }}

For example

{{2+3}}//output: 5
{{‘Java’ + ‘Program’ }} //output: Java Program

5
Full stack web Development -Unit -IV Express & Angular V Sem -IT

20. What is Pipe? Demonstrate the code for pipes in Angular.

Pipes are used to transform the data. That means pipes take data as input and are
getting transformed into another format. The pipes are written using pipe operator
which is denoted by │. The pipe can be applied to any view or template and to any
data input.

Built-in Pipes

1. Lowercase
2. Uppercase
3. Currency
4. Date
5. JSON

21. What is data binding in Angular? ( November/December – 2023)

Data binding is a technique where data is in synchronous with components and its
views.
Data binding defines the communication between components and its views. It
requires dynamic HTML and does not require any complex programming.

22. What are the two types of data bindings in Angular?

There are two types of data bindings-

1. Property binding: This type of binding allows to pass the interpolated values
from application data to HTML. The interpolated values are specified in {{ and }}
bracket pair. For instance - the [Link] is interpolating value. <p>
Name: {{ [Link]}}</p>

2. Event binding: Event binding is used to capture events on the user's end on the
app and respond to it in the target environment by updating the application data.

23. What is one way binding and two way binding in angular? (April/May – 2024)

The property binding is one-way binding in which we can set the properties of
the element to the user interface page. In this binding [] is used for data
binding. Following example illustrates it.

View

Model → using Property

Property binding

6
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Two-way binding

Two-way binding is a technique in which we can pass the data from view
to component and from component to view. For example, as we type some text
inside the textbox, the same text will be displayed outside the box.

Model → View at the same time


when event gets triggered
Triggers event

24. Differentiate between React and Angular. (Nov/Dec -2023)

Parameters React React

Type React is a JavaScript library, Angular is a complete framework.


and it is much older than
Angular.

Use of ReactJS can be packaged with Angular is a complete solution in


libraries other programming libraries. itself.

Data React uses one-way data Angular, on the other hand, uses the
binding binding, which means that the two-way data binding method. It
Ul elements can’t be changed helps you to ensure that the model
without updating the state automatically changes when
corresponding model state. any change is made.
Model It is based on Virtual DOM. Based on MVC (Model View
Controller),
Written in JavaScript. Typescript.

Application Use this app if you want to You should use this framework If you
Types develop Native apps, hybrid want to develop a SPA (single-page
apps, or web apps. Application) and mobile apps.
Purpose Develop dynamic web apps Build interactive UI components

25. What is data binding and what is the use of data binding in angular?
( Nov?Dec -2023 )

Data binding in Angular is a mechanism to synchronize data between the


model (the component class) and the view (the HTML template). It allows for a
seamless and automatic synchronization of data, making it easier to build
dynamic and interactive user interfaces. Here's a breakdown of the key uses
6and types of data binding in Angular:

Key Uses of Data Binding in Angular

1. Simplified Data Display:

7
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Automatically reflect the state of the component in the UI, reducing


the need for manual DOM manipulation.

2. Interactive User Interfaces:

Easily create dynamic forms, interactive dashboards, and other UIs


that respond to user input and data changes.

3. Maintain State Consistency:

Ensure that the view and the model are always in sync, reducing
bugs and inconsistencies in the application state.

26. Differentiate between Typescript and Javascript.(Nov/Dec-2024)

[Link] Feature TypeScript JavaScript


Dynamically typed
1 Typing Provides static typing
Comes with IDEs and Limited built-in tooling
2 Tooling
code editors
Standard JavaScript
Similar to JavaScript,
3 Syntax syntax
with additional features
Cannot run TypeScript in
Backward compatible with
4 Compatibility JavaScript files
JavaScript
May require more
Stronger typing can help
5 Debugging debugging and testing
identify errors
Learning Can take time to learn Standard JavaScript
6
curve additional features syntax is familiar

[Link] is the importance of track by in the ng-repeat directive in Angular?(Nov/Dec-2024)

The track by clause in AngularJS’s ng-repeat directive is important for optimizing performance
and preserving the integrity of the DOM when rendering lists.

[Link] do you configure routes in express js ( April/May -2025)

Routing in [Link] involves defining how an application responds to client requests at


different endpoints (URLs). Express, a popular [Link] framework, simplifies the
process of setting up routes and handling HTTP requests.

Basic Routing with Express

To define routes in Express, you use methods of the Express app object that
correspond to HTTP methods like GET, POST, PUT, DELETE, etc. Here is a basic
example:
const express = require('express');

8
Full stack web Development -Unit -IV Express & Angular V Sem -IT
const app = express();

// GET request to the homepage


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

// POST request to the homepage


[Link]('/', (req, res) => {
[Link]('POST request to the homepage');
});

// Start the server


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

[Link] Are Built-in Directives? list two built in directive in angularJS


(April/May-2025)
Angular provides a variety of built-in directives that enhance the functionality of your
applications by adding behavior to elements. These directives can be categorized into
three main types: Components, Attribute Directives, and Structural Directives.

Attribute Directives

Attribute directives change the appearance or behavior of an element, component, or


another directive. Some common attribute directives include:
 NgClass: Adds and removes a set of CSS classes.
 NgStyle: Adds and removes a set of HTML styles.
 NgModel: Adds two-way data binding to an HTML form element.

9
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Part B & C Questions

1. How to implementing Express in [Link] with an example


Write in detail about expressing in Angular is with examples (7) (April/May-2025)

 Express is web application framework used in [Link]. It has rich set of


features that help in building flexible web and mobile applications.

Features of Express

1. Middleware: Middleware is a part of program, that accesses to the


database and respond to client requests.
2. Routing: Express JS provides a routing mechanism so that it is
possible to reach to different web pages using the URLs.
3. Faster server side development: It is very convenient to develop
server Side-development using Express JS.
4. Debugging: Express Js makes debugging easier by providing the
debugging mechanism.

Installing Express
 Express is installed using Node Package Manager(npm). The command issued
for installing the express is,

Prompt:>npm install express

 Following is a simple application program that uses Express JS for displaying


"welcome message" on the web page.

[Link]
var express =require('express);
var app = express();
[Link](‘/’, function(req,res) {
[Link](Welcome User!!!")
});
var server app = listen(8082, function(){
[Link]("Server started!");
});

Output
On the terminal window or on command prompt window issue the command
> node [Link]

server started

open some web browser and issue the URL “localhost:8082”

10
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Program example: In above code,


 We have imported [Link] module using require function. The express
module returns a function and this function returns an object. This object can
be used to configure the Express application. In above code, it is the app
object.
 The app is an instance of express module. To the method of this instance - The
HTTP request, response objects and a callback function can be passed.
 The general syntax is

[Link](path, handler)
here,
method is an HTTP GET, PUT, POST or DELETE
handler is the function executed when the route is matched.

Then using the app. listen to function to make our server application listen to
client requests on port number 8082. We can specify any desired port number.

2. How to create a instance of express?

Create an instance of the express class. This instance acts as [Link] application.
Following lines create an instance of express
var express = require(express');
var app = express();

Configuring express settings

 The express object provides the set, enable and disable mehods to set the
values of application settings.
 Similarly, the express object provides get, enabled and disabled methods to get
set the values of application settings.
 The application settings can be done with the help of following values.

It defines the environment mode such as “development", "testing" and


env
"production". The default is the value of [Link] NODE ENV
Enables or disables the reverse proxy support.
trust proxy
It specifies the number of spaces to use when creating the JSON
response. The
json spaces
default value in development is 2 and 0 in production.

It defines the JSON replacer callback function. Default value is NULL.


json replacer
strict It enables or disables the strict routing.
routing
It specifies the default template engine extension while displaying the
view engine web page.

For specifying the path for template engine it is used. Template engine
views is a package that renders the data or values in HTML pages.

Table 4.1

11
Full stack web Development -Unit -IV Express & Angular V Sem -IT

3. Write about Configuring Routes with an example.


What is [Link] routing? Explain how to setup Express routes with
suitable example. ( Nov/Dec – 2023 )
Explain about configuring routes to implement express in node JS. ( Nov/Dec-2024)

In [Link], routing refers to the mechanism that allows you to define the
behavior of your application in response to HTTP requests. Essentially, it maps
incoming requests to specific handlers (functions) based on the request's URL path
and HTTP method (GET, POST, PUT, DELETE, etc.).

Key Concepts of [Link] Routing

1. Router Objects:
o Router: Express provides a Router class to help organize route handlers into
modular and reusable pieces. You can create instances of routers and mount
them on specific paths.
2. Route Handlers:
o Route: A route in Express is a combination of a URL path and an HTTP
method. For example, GET /users and POST /users are two different routes.
o Handler Functions: These are functions that are executed when a request
matches a route. They handle the request and provide a response.
3. Middleware:
o Middleware: Functions that execute during the request-response cycle. They
can perform tasks such as logging, authentication, or modifying the request
object before passing it to route handlers.

methods to set the Routing is a manner by which an application responds to a


client's request based an particular endpoint. The sample endpoints are,

localhost:8082/aboutus
localhost:8082/contact
localhost:8082/home

There are various types of requests such as GET, POST, PUT or DELETE. While
handling these requests in your express application, the request and response
parameters are passed. These parameters can be used along with the send method.

Following application represents how to performing routing using express

var express= require(‘express’);


var app = express( ):-
app get(/, function(req, res) { [Link]("Welcome User!!!");
});
//routing to 'about us' page
[Link]('/about', function([Link]) { [Link]("This is about us page");
});
//routing to 'contact page
[Link]('/contact', function(req,res) [Link]("This is displays contact
information");
var server = [Link](8082, function(){ [Link]("Server started!");
});

12
Full stack web Development -Unit -IV Express & Angular V Sem -IT

4. Explain the Using Request Objects in express


Illustrate in detail about Request and Response objects in Express JS with
relevant examples. (7) – Nov/Dec-2024
 The request and response objects are the parameters of the callback function
which are used in Express application. We can get the request query, params,
body, headers and cookies.

Request object

 The request object represents the HTTP request and contains properties for the
request query string, parameters, body and HTTP headers

 For example

 [Link]{'/, function([Link]){}}

Request object

The properties and methods of request object are as follows -

Properties/Methods Description

This property is used to hold a reference to the instance of the


[Link]
express application.

It sontains key-value pairs of data submitted in the request


[Link] body. By default, it is undefined and is populated when you
use body-parsing middleware such as body-parser.

13
Full stack web Development -Unit -IV Express & Angular V Sem -IT
[Link]
This property contains cookies sent by the request

14
Full stack web Development -Unit -IV Express & Angular V Sem -IT

[Link] [Link] is remote IP address of the request.

[Link] It is the path part of the request URL.

[Link] [Link] is currently-matched route.

It is used to check content types are acceptable, based on the


[Link](types)
request's Accept HTTP header field. For example
[Link]('html');

[Link](field) This method returns the specified HTTP request header field.

This method returns true if the incoming request's "Content-


[Link](type) Type" HTTP header field matches the MIME type specified by
the type parameter.

Table 4.2 The properties and methods of request object

Example code for demonstrating request object [Link]

var express = require('express');


var app = express();
[Link](/, function(req, res) {
console log("URL: "req originalUrl): [Link]("Protocol: "req protocol)
[Link]("IP",[Link]); [Link]("Path: "req path),
[Link]("Hostname" req hostname),
[Link]("Welcome User!!!")
var server app listen (8082, function(){ [Link]("Server started!");
});

Output

PS E:\ExpressExamples\RequestDemo> node [Link]

Server started!
URL: /
Protocol: http
IP: 111
Path: /
Hostname localhost

Program explanation: In above program, we have called various methods of Request


object such as [Link], [Link], [Link], [Link], and [Link]

15
Full stack web Development -Unit -IV Express & Angular V Sem -IT

5. Explain the response object in express.


Response object: The Response object (res) specifies the HTTP response which
is sent by an Express app when it gets an HTTP request.

For example - app get('/', function(req, res){}}



Response object

Following are some properties and methods of response object.

Properties/Methods
Description

[Link] It holds a reference to the instance of the express


application that is using the middleware.
[Link] It is a Boolean property that indicates if the app sent
HTTP headers for the response.
[Link](field [, value]) This method appends the specified value to the HTTP
response header field.
[Link]([filename]) This method facilitates you to send a file as an
attachment in the HTTP response.

[Link](name, This method is used to set a cookie name to value. The


value [, options]) value cas be a string or object converted to JSON.

[Link]([data] [, This method is used to end the response process. For


encoding]) example [Link]()

This method provides HTTP response header specified by


[Link](field)
field For [Link]("Content-Type")

[Link]([body]) This method is used to send HTTP response.

[Link](field [. value])
This method is used to set the response of HTTP header
field ta value
This method sets an HTTP status for the response. For
[Link](code) example [Link](400) send("Bad Request'); res
status(200). send("Ok");

Example code for demonstrating response object

[Link]

var express require('express');


var app express();
app get('/, function([Link]) {
var new response = '<html> <head> <title> Response Demo </title></head>
<body> <h1>Welcome User</h1></body></html>;
[Link]({
Content-Type: text/html, Content-Length'new [Link]
16
Full stack web Development -Unit -IV Express & Angular V Sem -IT

});
[Link](new response);
[Link]([Link]);
});
var server app listen (8082, function(){ [Link]("Server started!");
[Link]("Sending HTML contents to the browser...");
});

Program explanation: In above program,

We have created an HTML document in a variable new response. This document is


sent to browser using [Link] method. Before sending this document to the browser
we have set the status code as 200 (i.e. OK) and the content-type and content length.
The status of headers sent is also displayed on the console window. For performing
all these tasks, the corresponding methods of Response object are used.

6. Give the definition of TypeScript, Features of TypeScript, advantages and


disadvantages of TypeScript. Develop typescript code to validate email
address and password.(Nov/Dec/2023)

 TypeScript is a typed superset of JavaScript. Any valid JavaScript code is


basically a valid code for typescript as well.
 TypeScript extends JavaScript by adding data types, classes and other object-
oriented features with type-checking.
 The typescript compiles to plain JavaScript code.
 Typescript is a programming language developed and maintained by Microsoft.
 Typescript may be used to develop JavaScript applications for both client side
and server side execution.

Need for TypeScript

 JavaScript is a dynamic scripting language with no type system. JavaScript


provides the primitive types such as number, string, object but it does not
check the datatype of assigned values. Moreover, JavaScript variables are
declared using var keyword which cannot indicate the datatype of the value. So
without a type-system it is not easy to use JavaScript to build complex
applications with large teams working on the same code
 he Type system increases the quality of code and readability. It makes the
maintenance of the code easier.
 Using TypeScript the developer can catch the errors regarding type-system at
the compile time instead of run time. So that it can be fixed easily before it gets
complex.

17
Full stack web Development -Unit -IV Express & Angular V Sem -IT

 Another important aspect of using TypeScript is its support for the use of
object oriented features in the scripting language.

Features of TypeScript

1. Portability: TypeScript is a portable because it can be executed on any


browser or operating system. It can run on any environment where JavaScript
runs.

2. JavaScript: The code written in JavaScript with valid js extension can be


converted to TypeScript by simply changing the extension from .js to .ts.

3. Static Type checking: This feature allows type checking at compile.

4. Support for Library: For developing the TypeScript coding we can use all
JavaScript frameworks, tools and libraries easily.

5. Support for OOP: The TypeScript can make use of various features of object-
oriented programming languages such as classes, interfaces, inheritance and
so on.

6. Client and Server side Development: TypeScript allows the development of


both server-side and client-side programming.

Advantages

 It is an open source language with continuous development.


 It runs on any web browser.
 The TypeScript code can be called from existing JavaScript code. It can also
work with JavaScript frameworks and libraries without any issue.
 TypeScript has a support for the latest JavaScript feature from
ECMAScript2015. The ECMAScript specification is a standardized specification
of a scripting language. This standard is meant to ensure the interoperability of
web pages across different web browsers. The 6" edition, ECMAScript 6 (ES6)
and later renamed to ECMAScript 2015. Some of major enhancements of this
standard include modules, class declarations and so on.

Disadvantages

 Web browsers do not understand the TypeScript code. If we want to run


TypeScript code in the web browser, then we need to compile it. This
compilation process converts it to JavaScript and then we can see the
Typescript code running in the web browser.
 It does not support abstract classes.
 TypeScript takes a time to compile the code.
18
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Develop typescript code to validate email address and password.

A simple TypeScript implementation for validating email addresses and passwords. We’ll
create a class with methods to validate email and password, along with some helper
functions to check their formats.

TypeScript Code

class Validator {
// Regular expression for email validation
private static emailRegex: RegExp = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// Regular expression for password validation


private static passwordRegex: RegExp = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
/**
* Validates an email address.
* @param email - The email address to validate.
* @returns true if the email is valid, otherwise false.
*/
public static validateEmail(email: string): boolean {
return [Link](email);
}
/**
* Validates a password.
* Password must be at least 8 characters long and contain at least one letter and
one number.
* @param password - The password to validate.
* @returns true if the password is valid, otherwise false.
*/
public static validatePassword(password: string): boolean {
return [Link](password);
}}
// Example usage:
const email = "test@[Link]";
const password = "Password123";
[Link](`Is email valid? ${[Link](email)}`); // Output: Is email
valid? true
[Link](`Is password valid? ${[Link](password)}`); // Output:
Is password valid? true

Explanation

1. Email Validation: The regular expression used for validating email addresses
is a basic one that checks if the email contains characters before and after
the @ symbol and has a domain after the .. This regex may not cover all edge
cases but should work for most common email formats.
2. Password Validation: The regular expression for password validation checks
that the password:
o Is at least 8 characters long.
o Contains at least one letter.
o Contains at least one number.
3. Static Methods: The validation methods are static so they can be called
directly on the Validator class without needing to instantiate it.
19
Full stack web Development -Unit -IV Express & Angular V Sem -IT

7. How to Installation the Typescript code


 We first need to install [Link]. we can get it downloaded from
[Link]
 The installation can be done on Linux or windows OS. It has very simple
installation procedure.

 Click Next button to read and accept the License Agreement and the click
install. It will install [Link] quickly on your computer. Finally, click finish to
complete the installation.
 Verify installation

20
Full stack web Development -Unit -IV Express & Angular V Sem -IT

 In order to verify the installation, we have to pen a command prompt and type
the following command-

 If the [Link] successfully installed, then some version number of the [Link]
which you have installed, then some version number of the [Link] which you
have installed in your PC will be displayed.
Step2:
 We have to install the typescript with the help of the node package
mamanger(npm)
 The command which can be issued at the command prompt is as follows-
npm install –g typescript
 The screenshot as follows-

The above command will install Typescript globally so tha twe can use it in any
[Link] check the installed vrsion of typeScript using the following command:
tsc -v

21
Full stack web Development -Unit -IV Express & Angular V Sem -IT

8. How to Write TypeScript Program?

 In this section we will develop our first TypeScript program.

 Normally for executing the web framework programs web developers prefer to
use some IDE. Most commonly used IDE are Visual Studio Code and
Sublime Text2. I have used Visual Studio Code editor for executing the
TypeScript programs. It can be downloaded from the web
site [Link]

 The installation procedure of Visual Code Studio is pretty simple. We have to


simply click the Next button and continue with the default installation
options

 Now let us begin with writing the TypeScript code

Step 1: Create a folder in your local drive. Say I have created a folder named
TypeScript Code at my E:\ drive.

Step 2: Open this folder in Visual Studio Code editor. Create a file with some name
and extension is under this folder. I have created a file named [Link].

[Link]
[Link]("Welcome to my First TypeScript Program!!!!");
Following screenshot shows it-

Step 3: Now execute above code by issuing following command at the command
prompt tac [Link]
Following screenshot illustrates it -

22
Full stack web Development -Unit -IV Express & Angular V Sem -IT

By this step your typescript code is converted to plain javascript code. That means
on compiling the [Link] the [Link] file gets generated.

Step 4:
Now we can get the output of the above program on the web browser. For that
purpose we have create an [Link] file by adding new file under typescript-code
folder and call the [Link] file in it. The code is as follows

[Link]

<html>
<body>
<script sre = '[Link]"></script>
</body>
</html>

Just refer following screenshot

step 5: Open some web browser and enter the path of the file as URL, right click
on browser window. Select Inspect-> Console. The output can be viewed on
Console window. It is as follows-

23
Full stack web Development -Unit -IV Express & Angular V Sem -IT

------------------------------------------------------------------------------------------------------------
9. Give the detail about Variables and Constants in TypeScript

 Variable is the storage location at which the value is stored.


 It is basically a container for value in the code.
 The rules for using variables is as follows -

1. The variable name must be alphabet or numeric.


2. The variable name can not start with a number.
3. The variable name cannot contain spaces and special characters except
underscore or dollar sign.

Variables can be declared using var and let. The contestant can be declared
using const

var

The variable can be declared using the keyword var same as JavaScript. To
assign a value to the variable, use the equal sign.
var stutName = "Parth";

let

The let declaration follows the same syntax as var declaration. For example-

let empName" = “Archana”

The var declaration has some problems in solving programs, so ES6 introduced
let keyword to declare a variable in TypeScript and JavaScript. The let keyword
has some restriction in scoping in comparison of the var keyword.

Difference between var and let

Var declarations are globally scoped or function/locally scoped. The scope is


global when a var variable is declared outside a function. This means that any
24
Full stack web Development -Unit -IV Express & Angular V Sem -IT

variable that is declared with var outside a function block is available for use in
the whole window. For example-

for (var i=0;i<5++){


console log(“i=”,i);
}
[Link]("Outside the loop: i=”, i);

The output is
i=0
i=1
i=2
i=3
i=4

Outside the loop: i = 5

The let keyword is block scoped. The block is defined within { }. It means that
the variable i only exists and can be accessible inside the for loop block.

For example

for (let i=0;i<5++){


console log(“i=”,i);
}
[Link]("Outside the loop: i=”, i);

const

Variables declared with the const maintain constant values. Like let
declarations, const declarations can only be accessed within the block they
were declared. The const cannot be updated or re-declared.

This means that the value of a variable declared with const remains the same
within its scope. It cannot be updated or re-declared. So if we declare a variable
with const, we can neither do this:
const name "Ankita";
greeting Prajkta;
----------------------------------------------------------------------------------------------------------------

10. What is interface? Explain the use of interface in TypeScript with suitable
example.

 Interface is a structure which acts as a contract in our application. That


means, interface defines the syntax that an entity should have.
 The members of interfaces are properties, methods and events.

Syntax
 The typical syntax of interface is
interface interface_name {

property_type: data-type//declare properties, methods or events


...

25
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Rules for using interfaces

i. The interface should be created using the 'interface' keyword followed by the
name of the interface.
ii. While defining the interface, the data-types of the members must be properly
mentioned.
iii. Function interface should only contain the method signature and not
implementation.
iv. While creating the object for the interface function, it should refer to the
implemented function.
v. While defining the function inside the interface variable type and function
return type should be mentioned properly.
vi. While implementing the function which is defined in the interface, the method
signature must be matched properly.

11. What is class? How to use class in TypeScript? Explain it with suitable
example.

In object oriented programming languages like C++ and Java, class is a


fundamental entity which is used to create reusable components.

A class contains-

 Properties
 Constructor
 Methods

Syntax of declaring class

class <class_name> {
field;
method;
}

Example

class Person {

person_id: number;  Properties


person name; string;

getName:string {  Method
return "Arun";
}}

Using constructor

The constructor is a special type of method which is called when creating an


object. In TypeScript, the constructor method is always defined with the name
"constructor".

26
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Example

class Person {
Properties
person_id: number; 
person_name: string;

constructor(id: number, name: string) {


this.person_id=id;  Properties
this.person_name = name;
}
Constructor

getName:string(
Method
return "Parth"; 
}
}
Creating an object
An object is an instance of a class. The object is created using keyword new

For example
[Link]

class Person {
person_id number;
person_name: string;
constructor(id: number, name: string) {
this.person_id=id,
this.Person_name =name;
}}
Let pl-new Person(101, Parth"//object pl is created
[Link](p1);

Output
E:\TypeScriptExamples\ClassDemo>tsc [Link]
E:\TypeScriptExamples\ClassDemo>node [Link] Person (person_id: 101,
person_name: “Arun" )

12. Explain the use of inheritance in TypeScript with suitable example.

Inheritance is a important feature of object oriented programming in which the


child classes are created by inheriting some of the properties of parent class.
The keyword extends is used to inherit the child class from parent class.

Example

class Person { //parent class


pname:string;

constructor(name:string) {
[Link] = name;
class Student extends Person{ // child class

27
Full stack web Development -Unit -IV Express & Angular V Sem -IT

rollno: number;

constructor(name [Link]){
super(name);
[Link]-roll;
}
display void {
console log("Roll Number:", [Link]);
[Link] ("Name: "[Link]);
}
}
var stud =new Student("Parth",101);
console. Warn(stud);

Output

E:\TypeScriptExamples\InheritanceDemo>tsc [Link]

E:\TypeScriptExamples\InheritanceDemo>node [Link]
Student { pname: 'Parth', rollno:101}
E:\TypeScriptExamples\InheritanceDemo>

Program explanation: In above program,

 We have created two classes namely Person and Student. The Person class
contains the property as pname and the Student class contains the property as
rollno.

 The Student class inherits the Person class. Hence the object of Student class
can access the property of parent class(i.e. pname) and property of the self
class (ie, rollno);

 The keyword extends is used to inherit the base class

13. Write the use of modules in TypeScript.

A module is used to set code written in TypeScript. A module can be defined in a


[Link] file which can contain functions, classes, interfaces.

We use the prefix export with all the definitions which we want to include in a
module and want to access from other modules

Demo example

Step 1:

We will create [Link] is a module which contains a class named Addition.


This class is prefixed with keyword export

28
Full stack web Development -Unit -IV Express & Angular V Sem -IT

[Link]

export class Addition (

a: number;
b: number;

constructor (a: number, b: number) {


this.a = a;
this.b = b;
display() {
[Link] (“Addition:” + (this.a + this.b) );
}
}

The above class contains two variables a and b. It also contains one function
display().

Step 2: Now we will create one JavaScript file for importing the class created in
above stер.

Definition import: A module can be used in another module using an import


statement.

Syntax:

import { export name } from "file path without extension"

Following file is used for import file.

[Link]

import {Addition} from './calculator’;

let obj = new Addition(100, 200);

[Link]();

Step 3: Now open the command prompt and issue the commands
tac-module commonjs [Link]
node./.[Link]

E:\TypeScript_Code\ModuleDemo tsc-module commonjs [Link]

Addition: 380

E:\TypeScript_Code\ModuleDemonade ./[Link]
E:\TypeScript_Code\ModuleDemo>
For compiling the modules, we have used following syntax

--module <target> <file path>

The following can be used as target with the above-module command option:
29
Full stack web Development -Unit -IV Express & Angular V Sem -IT

1. None
2. CommonJS
3. AMD
4. UMD
5. System
6. ES6, ES2015 or ESNext

We have used CommonJS option for execution of JavaScript applications.

Importing multiple classes in a single file

Following example illustrates how to import multiple classes in a single JavaScript


file.

Step 1:

Create a TypeScript program and define two classes namely Addition and
Multiplication

[Link]

export class Addition {


a: number;
b:number;

constructor(a: number, b: number) {


this.a = a;
this.b = b;

display() {
[Link]('Addition: + (this.a + this.b));
}
}

export class Multiplication {


a:number;
b:number;

constructor(a: number, b: number) {

this.a = a;
this.b = b;
}
show() {
[Link] ("Multiplication:”+ (this.a * this.b));
}
}

Step 2: Create the [Link] file as follows

[Link]

import (Addition, Multiplication) from './calculator';


30
Full stack web Development -Unit -IV Express & Angular V Sem -IT

let obj1 new Addition(100, 200);


[Link]();
let obj2 new Multiplication(100, 200);
[Link]();

Step 3: Compile the application

Command Prompt

E:\TypeScript_Code\ModuleDemo>tsc --module commonjs [Link]

E:\TypeScript_Code\ModuleDemo>node ./[Link]
Addition: 300
Multiplication: 20000

E:\TypeScript_Code\ModuleDemo>

14. Explain the concept of understanding Functions in TypeScript

Functions are basic building blocks of any JavaScript document. It makes the code
reusable, readable and maintainable

Syntax

The function can be defined as follows-

function function name(jarg1, arg2,..., argN) {

//body of function
}

The function can be called as follows.

Function_name[[argument]);

Demo Example

[Link]
function addition (num1: number, num2: number)
{
var result = num1+num2;
[Link](result);
}
addition(10,20);

Output

E:\TypeScriptExamples\FunctionDemo>tsc [Link]

E:\TypeScriptExamples\FunctionDemo>node [Link] 30

31
Full stack web Development -Unit -IV Express & Angular V Sem -IT

E:\TypeScriptExamples\FunctionDemo>

Anonymous function

 The function without the name is called anonymous function. The type of
functions are dynamically declared at runtime.
For example-
let display function( ) //This is anonymous function
{
[Link]("Welcome"):
}
display(); //call to the function

We can pass the parameters and return type to the anonymous function.
For example -

let addtion = function (a:number, b:number):number


{
return a+b;
}
[Link] (addition (10,20)),

Arrow function

The fat arrow function is used for anonymous function. They are also called as
lambda functions.

Syntax
(arg1,arg2,..., argN]) => expression { //function body}
By the use of => arrow we need not have to use the keyword function
For example-
let addtion = (a:number, b:number):number =>
{
return a+b;
}
[Link](addtion(10,20));

15. What is angular? List and explain its features.


 Angular is a typescript based free and open source web application framework
led by the Angular team at Google and by a community of individuals and
corporations.
 Angular 10+ is a JavaScript framework which is used to create single page
applications(SPAs).
 The single page application is a kind of application which dynamically rewrites
the current page rather than loading entire new pages from a server.
 The SPAs provide the user a very fluid, reactive and fast experience.
 Angular is completely based on components. Due to which the applications
created in Angular give the reactive speed.
 The Angular applications are created with the help of HTML and TypeScript.

32
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Features of angular
1. Support for multiple platforms
Angular is a cross platform language. It allows the developers to create desktop
applications and progressive web applications.

2. High speed web applications


Angular applications are fast and load quickly with new component router.
Angular is specially used as a front end web development for the programming
languages like [Link], Net, PHP, Struts, Spring and other servers for instant
rendering by just using HTML and CSS.

3. Productivity
Angular uses template syntax and command-line tools for adding and
testing the components. This enhances the productivity of Angular.

4. Localization
One of the best features of Angular 10+ is that the latest angular version
Supports for merging of multiple translation documents which could only load
one file in the previous versions.

5. Dynamic development
Angular team releases two versions in a year. This helps the the developer to
have handy and updated functionalities each time along with each hew release.

6. Full stack development


The full stack development is a buzzword that start-up companies use in this
modern of software development. Angular is a complete framework of
JavaScript. It provides testing, animations and accessibility.

How to install Angular CLI?

 The angular CLI is a command-line interface tool that we use to initialize,


develop, scaffold and maintain angular applications directly from a command
prompt or terminal.

 It provides some commands and schematics which help us with faster code
generation. Most of the frameworks and applications normally come with CLI.

 We can install angular with the help of angular CLI.

How to install Angular?

Angular CLI

The Angular CLI is a command-line interface tool that we use to initialize,


dervelop,

Step 1: Install [Link]


Step 2 : Update npm

33
Full stack web Development -Unit -IV Express & Angular V Sem -IT

While installing the node,js, the npn(node package manager) gets installed.
Angular requires NPM v6.11 or later. Hence we have to check the version of
npm by issuing following command on the command prompt window.
Microsoft Windows [Version 10.0.19043.14151

C:\Users>npm -v
6.14.10
C:\Users>
npm install -g npm

If you don't have the latest version of NPM, then update it using the following
command on windows.

npm install –g npm

Step 3: Now install the Angular CLI. For that Pupose create a folder in which we
want to install the Angular. I have created a folder named

Sep 4: We have to check version of installed Angular CLI by issuing the command
ng --Version

34
Full stack web Development -Unit -IV Express & Angular V Sem -IT

16. Write about angular Lifecycle in detail.


Describe in detail about Angular Components, its lifecycle and styles with
example code snippets. (7) (Nov/Dec-2024)

 In Angular, every component has a life-cycle, a number of different stages it


goes through from initializing to destroying. The view of the main component is
rendered in [Link] file using <app-root>.
 The <app-root> is specified using selector.
 In the [Link] file using the annotation @NgModule the component is
specified in the declarations section.

step1: Angular browser displays the [Link] fle on execution of Angular app. We
normally say that “Angular renders your app”

In the [Link] file, there is only one element <app-root></app-root>

step.2:
The <app-root is defined as selector. In sre>app folder. Just open the
[Link]. This file contains the selector as follows

@Component({
selector:’app-root’,
templateUrl:./[Link]’;
styleUrls:[‘.[Link]’]
})

Step3: Inside the [Link] file the specification for AppComponent is


mentioned.

35
Full stack web Development -Unit -IV Express & Angular V Sem -IT
import {AppRoutingModule}’/[Link]
import {[Link]) from’.[Link]’;

36
Full stack web Development -Unit -IV Express & Angular V Sem -IT

import{WelcomeComponent}from’./welcome/welcome.cоmpоnent’;

@NgModule({
declarations: [
AppConiponent.
WelcomeComponent
],
Step 4: This is the flow of execution Angular app. This app can be displayed in the
browser window when we issue the command ng serve -0 on command prompt or
terminal window

Understanding and Using ngModule

 Angular modules consolidate components, directives and pipes into


functionality.
 For defining the module we use the ngmodule.
 Every Angular application has at least one NgModule class, the root module,
Which is conventionally named AppModule and resides in a file named
[Link]
 An NgModule is defined by a class decorated with @NgModule(). The
@NgModulg decorator is a function that takes a single metadata object, whose
properties describe the module.
 Just refer the following screenshot for ngmodule

Following are the metadata options used in NgModule

Providers: It is an array of injectable objects available.


declarations: It is an array of directives. pipes and components that belong to the
current NgModules.
imports: It is an array of Other modules whose exported classes are needed by
component templates declared in this NgModule.
Exports: of declarations that should be visible and usable in the component
templates of other NGModules.
bootstrap: This is the main application view called root component which hosts all
other apps views only. only the root NgModule should set the bootstrap
property.

37
Full stack web Development -Unit -IV Express & Angular V Sem -IT

17. Explain the angular architecture with suitable block diagram.

The main building blocks of angular architecture are-

[Link]
[Link]
[Link]
[Link] Binding
[Link]
[Link]
[Link] and Services.

Fig. Angular architecture

Let us discuss them one by one

1. Modules

 Every Angular App has a root module which is called as AppModule. It provides
bootstrap mechanism that launches the application.
 Organizing your code into distinct functional modules helps in managing the
development of complex applications.
 If we want to use another custom Angular module, then we need to register
that module inside the [Link] file.
 An app typically contains many functional modules.

2. Template

Template is basically used to combine HTML with Angular Markup and modify HTML
element before displaying them.
38
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Template directives provide program logic and binding markup which connects
application data and DOM.
Typically in out Angular App the template looks like this-

<div style="text-align:center">
<h1>
//code for data binding

</h1>
</div>

3. Components
 The component in the application defines a class which basically contains the
application logic and data.
 The application logic is normally written in TypeScript format and view of the
page is in HTML template.
 A component controls a display of screen called a view.
 Every Angular app has at least one component which is known as root
component which connects the component hierarchy with the page Document
Object Model(DOM)

4. Data Binding
There are two types of data bindings-
o Property Binding: This type of binding allows to pass the interpolated values
from application data to HTML. The interpolated values are specified in {{ and }}
bracket pair. For instance - the [Link] is interpolating value.
<p>Name: {{ student name}}</p>

o Event Binding: Event binding is used to capture events on the user's end on
the app and respond to it in the target environment by updating the application
data.

5. Directives
 The directives extend the HTML with the help of new syntax.
 The directives are written using the prefix ng.
 These directives attach certain behaviour to the elements. There are two
commonly used directives ng-model and ng-bind
 ng-model: The ng-model binds the value of the HTML control with the specified
AngularJS expression value.
 ng-bind: This directive replaces the HTML control value with a specified
AngularJS expression value.

6. Metadata

 Metadata means data about data.


 Metadata tells Angular how to process a class. It is used to decorate the class
so that it can configure the expected behavior of a class.

39
Full stack web Development -Unit -IV Express & Angular V Sem -IT

 The metadata for a component class has a template that defines a view.
 The metadata for a service class consists of information Angular needs to make
it available to components through Dependency Injection (DI).

7. Injections and Services

 In Angular, it is a practice for data or logic that it should not be associated with
a specific view. It is created as a service class. Due to this, the data or logic is
shared across components.

 By dependency injection, we mean to allow access to the service by subscribing


it. It acts as a delegate to the service.

 The @Injectable decorator immediately precedes the service class definition.


The decorator provides the metadata that allows our service to be injected into
client components as a dependency.

18. Explain about Angular components Or Give the sample layout of the Angular
application with multiple Components.
Describe in detail about Angular Components, its lifecycle and styles with example
code snippeta. (7) (Nov/Dec-2024)

Components are basic building block element of Angular. The components are
associated with the template and they define different aspects of the user interface.

• Each component consists of -


An HTML template that declares what renders on the page.
A Typescript class that defines behavior.
A CSS selector that defines how the component is used in a template.

Typical organized page in Angular App contains multiple components. It can be


viewed as follows-

Figure - Multiple components on angular App page

We will create a component in a first-app application. Not its time to create a simple
app. There are two ways to create components the component can be created
manually or it can be created using Angular CLI command. Let us now create a
40
Full stack web Development -Unit -IV Express & Angular V Sem -IT
simple component using Angular CLI method.

Demo Example

41
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Step 1: Go to the first-app folder and issue the following command at the command
line. Note that the name of my component is welcome. You can give any name to the
component.

ng generate component welcome

On issuing this command the folder named welcome gets created inside the src->app
folder of project. The project explorer window is as shown below

Note that it creates four files [Link], [Link],


[Link] and [Link]

Step 2: We will keep our [Link] file very simple. Delete everything from
it which comes by default from the Angular framework and simply add following code
to it.

42
Full stack web Development -Unit -IV Express & Angular V Sem -IT

[Link]

<h1>Hello</h1>

Step 3: Now open [Link] file and edit it as follows. The bold-faced
code shows the modification in the [Link] file of component.

import Component, Oninit) from @angular/core


@Component({

selector 'app-welcome,// This selector name will be used in [Link] file


(Refer step 5)

templateUrl: /[Link].
styleUria: [/[Link]]
export class WelcomeComponent implements OnInit {
constructor() {}
ngOnInit(): void (
current User: String = "Anuradha

Step 4: Open [Link] file and edit the code in it as follows -

[Link]

<p>welcome {{currentUser}}</p>

Step 5: Now open [Link] file and edit it with the selector name of the
component.
[Link]
<h1>Hello</h1>
<app-welcome></app-welcome>
Step 6: Now open the command prompt and issue the command na serve -

The application will get compiled and the browser window will get opened up. The
welcome component will be added to it.

43
Full stack web Development -Unit -IV Express & Angular V Sem -IT

19. What is Expressions in Angular? Explain with an example.

Angular evaluates expressions and then can dynamically add the results to a web
page. Expressions are encapsulated blocks of code inside brackets as follows-

({ expression }}

For example

{{2+3}}//output: 5

{{‘Java’ + ‘Program’ }} //output: Java Program

Step 1: Create a folder with suitable folder name using ng new folder-name
Step 2: Open the [Link] file under sre/app folder.

[Link]

<h1> Demo of Expression </h1>


<h4>Addition of 10 and 20 is:</h4>
{{10-20}}
</br>
<h4>Addition of two strings 1 and 2 is: </h4>

{{‘1’+’2’}}

Output

The output can be viewed on the web browser as follows-

44
Full stack web Development -Unit -IV Express & Angular V Sem -IT

20. What is Pipe? Demonstrate the code for pipes in Angular.

Pipes are used to transform the data. That means pipes take data as input and are
getting transformed into another format. The pipes are written using pipe operator
which is denoted by │. The pipe can be applied to any view or template and to any
data input.

Built-in Pipes

1. Lowercase
2. Uppercase
3. Currency
4. Date
5. JSON

Demo Example

Let us understand this with demo example

Step 1: Create a folder using some suitable name. I have created a folder by a
name pipe- demo using the command ng new pipe-demo.

Step 2: Open the [Link] file and create a student array as follows-

[Link]

import { Component } from '@angular/core';


@Component({
selector: 'app-root',
templateUrl: /[Link]',
styleUrls: [/[Link]']
export class AppComponent {
student={
roll:101,
name:' Arun ', city:Pune', fees:10000, DOB:09/01/1980' };

Step 3: Now open the view page i.e. [Link] and edit it as follows by
using built in pipes

[Link]

<h1> Welcome</h1>
<div style="font-weight:bold;">
Name in lower-case: {{[Link] | lowercase }}
</div>
<div style="font-weight:bold;">
City in upper-case: (([Link] | uppercase }}
</div>
<div style="font-weight:bold;">
Date of Birth: (([Link] | date }}
</div>
<div style="font-weight:bold;">
45
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Fees: ((student fees | currency:INR'}}


</div>

Step 4: Open the command-prompt and issue the command ng serve -o. The
output can be displayed on the browser window as follows-

--------------------------------------------------------------------------------------------------------------
21. Explain about Data Binding and its types with an example in Angular.
What is data binding in angular? Explain types of data binding in Angular
each with suitable example.( April/May – 2024)
What is data binding in Angular and what are the types of data binding?
Illustrate with suitable example, how data binding in Angular allows
developers to create interactive web applications. (6+8) (April/May-2025)

Data binding is a technique where data is in synchronous with components and


its views.

Data binding defines the communication between components and its views. It
requires dynamic HTML and does not require any complex programming.

Types of data binding

There are basically two approaches used for data bindings - One way Binding and
two way Binding. The one-way binding is done using interpolation binding,
property binding and event binding. Let us discuss them briefly with the help of
demo examples.

1) Interpolation binding

Using interpolation we can bind the values to the user interface elements. This is
one-way data binding. Because data moves from component to view element or
HTML element. This is one-directional flow of data.

View
Model
Model →
using Interpolation

Interpolation binding

46
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Demo example

47
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Let us understand this type of binding with the help of example-

Step 1: Now create a workspace folder for the Angular application. I have created
a folder binding-demo using ng new command. It is as follows-

ng new binding-demo

The answer to add Angular routing is y and stylesheet format is css.

Step 2: Now change directory to the binding-demo folder. Go to src->app folder


and open the file [Link]. Add two data member roll_no and
name to the class Add Component
[Link]

Import (Component } from '@angular/core';


Component((
selector: app-root,
templateUrl/[Link].
styleUrls: [/[Link]']
export class AppComponent(
public roll nonumber=101
public name:String='Anuradha'

Step 3: Now open [Link] file. Delete the entire default code and add
following code to it.
[Link]

<h1 style="text-align: center;">WELCOME</h1>


<h2 style="text-align: center;">Roll no: ((roll_no)}</h2>
<h2 style="text-align: center">Name: ((name))</h2>

Step 4: Now open the command-prompt window and issue the command ng serve -
o. The browser window will display the output as follows-

BindingDemo
WELCOME
Roll no: 101
Name: Arun
2) Property binding

The property binding is one-way binding in which we can set the properties of the
element to the user interface page. In this binding [] is used for data binding.
Following example illustrates it.

View

Model → using Property

Fig. 4.2 Property binding

Demo example
48
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Take one image file and save it to sre-assets folder. I have with me [Link] file a
image file which I have saved in sre-assets folder.

Step 1: Go to src->app folder and open the file [Link]. Add the image
variable as follows-

[Link]

import (Component } from '@angular/core';

Component({
selector: app-root',
templateUrl: /[Link],
styleUrls: .[[Link]’]
}}
export class AppComponent {
public roll no number-101;
public name String 'Anuradha';
public image="/assets/[Link]"
}

Step 2: Open the [Link] page and set the property value to image.

[Link]

<h1>WELCOME</h1>
<h2>Roll no: ((roll_no))</h2>
<h2>Name: ((name)}</h2>
<img src="image" alt="Logo" style="height:0px;width:150px">

Step 3: Open the command prompt window and issue the command ng serve -o.
The output will be as follows-

3) Event binding

The event binding is the flow of data from view to component. In this case, the event
is triggered on the view or HTML page. The view page sends data to the component.

Model View

Triggers event On triggering event

Fig. 4.3 Event binding

In the following application, on clicking the button on the view page (i.e.
[Link] page), the data is send to the component

Demo example

Step 1: Open the [Link] page and add following code to it

49
Full stack web Development -Unit -IV Express & Angular V Sem -IT

[Link]
<h1>WELCOME</h1>
<h2>Roll_no: ((roll_no}}</h2>
<h2>Name: {{name}}</h2>
<button (click)='display()">Enroll</button>

Step 2: open the [Link] page and add following code to it.

[Link]

import { Component } from '@angular/core';


@Component({ selector: app-root",
templateUrl: /[Link]",
styleUrls: [/[Link]]
})
export class AppComponent {
public roll no number 101;
public name String - 'Amuradha';
display()

{
alert("You are now Enrolled!!!");
}
}

Script explanation:

By above two steps we have created Enroll button on the HTML page and on clicking
the button, "You are Enrolled" message will be displayed.

Step3: Open the command prompt and issue the command ng serve –o. The output
will be

4) Two way binding

Two way binding is a technique in which we can pass the data from view to
component and from component to view. For example as we type some text inside the
textbox, the same text will be be displayed outside the box.

Model → View at the same time


when event gets triggered
Triggers event

Two-way binding

50
Full stack web Development -Unit -IV Express & Angular V Sem -IT

Step 1: Open [Link] and edit the code as follows.

import { Component } from '@angular/core';


@Component({ selector: app-root",
templateUrl: /[Link]",
styleUrls: [/[Link]]
})
export class AppComponent {
public roll no number 101;
public name String - 'Amuradha';
public comment String="”;
}
Step 2: Open [Link] file and edit the code as follows-
[Link]

<h1>WELCOME</h1>
<h2>Roll_no: {{roll_no}}</h2>
<h2>Name: {{name}}</h2>
Enter your Comments: <input (ngModel)]="canumenttype="text">
<hr>
<p>You have entered</p>
<h4>{{comment}}</h4>
Script Explanation: In above script we have used input textbox, using ngModel
directive we are binding the contents of textbox with the variable comment. And
below this text box inside the paragraph element<p> we are interpolating (using (1)
the comment variable to display the contents of the textbox simultaneously as we
type it. This illustrates the two-way binding process.

Step 3: Open the [Link] and import FormsModule to it. In the folowing code,
bold faced code indicates the modifications.
[Link]
import { NgModule } from ‘@angular/core’;
import { BrowserModule} from '@angular/platform-browser;
import { FormsModule} from '@angular/forms;
import { AppRoutingModule} from './[Link]';
import { AppComponent } from './[Link]';
@NgModule({
declarations:[
AppComponent
]’
imports: [ BrowserModule, AppRouting Module, FormsModule],
providers: [],
bootstrap: (AppComponent) })
})
export class AppModule {}

Step 4: Open the command prompt window and issue the command ng serve. The
browser will display the output. Just type some text in the textbox. Note that as you
type in the textbox, the same text will appear on the same HTML.

51
Full stack web Development -Unit -IV Express & Angular V Sem -IT

22. Explain about Built-in Directives in angular

Directives is a technique in Angular that adds additional behaviour to the


elements in the Angular applications.

There are three different types of directives -

1. Components 2. Structural directives 3. Attribute directives

1. Structural Directives

 The most commonly used directives are structural directives. These are
directives that change the DOM layout. Note that DOM stands for Document
Object Modeling.
 With the help of structural directive the elements can be added or removed
from DOM.
 The structural directive's name always starts with an asterisk(*) prefix.
 There are three most popularly used structural directives -

 NgIf
 NgFor
 NgSwitch

1.1 ngif Directive

 It is used to create or remove a part of the DOM tree depending on a condition.

Syntax

<div "nglf="condition">Content to display when condition is true.</div>

Demo Example

Step 1: Create a workspace using following command ng new directive-demo


Step 2: Edit [Link] as follows - [Link]

<button (click)="show = Ishow'>


{{show? Click to Hide': 'Click to show}}
</button>
<br>
<h1>
<div "nglf="show">Welcome useril</div>
</h1>
Step 3: Edit the [Link] as follows

[Link]

import { Component } from '@angular/core';


@Component({

selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']

52
Full stack web Development -Unit -IV Express & Angular V Sem -IT

})
Step 4: Execute the above code using ng serve -o

1.2 ngfor Directive

This is a type of structural directive that shows the template for each item in
the collection or list. The ngFor is prefixed by *.

The syntax is <li "ngFor="let item of items;">...</li>

Demo Example

Following example illustrates how to use *ngFor directive for displaying the list
of students.

Step 1: Go to the folder location in which the application for ngFor is to be


created. Open [Link] file and edit is as follows -

[Link]

@Component(
import { Component } from '@angular/core'; selector: 'app-root', templateUrl:
'/[Link]", styleUris: ['/[Link]"]
export class AppComponent(
students = |
(roll_no:2,name: 'Archana'),
{roll_no:4,name: Chinmaya'),
(roll_no:6, name: 'Soumya').
{roll_no:8,name: Swati')

Step 2: Now open the html file and edit the code as follows -

[Link]

<h1> List of Students</h1>


<table border='5'>
<th>Roll No</th>
<th>Name</th>

53
Full stack web Development -Unit -IV Express & Angular V Sem -IT

<tr *ngFor "let student of students;">


<td>{{student.roll_no}}</td>
<td>{{[Link]}}</td>
</tr>
</table>

Step 3: Run the above application at the command prompt by issuing the command
ng serve -o. The web browser will get opened up and the output will be
displayed as
follows-

1.3. ngSwitch Directive

 The [ngSwitch] directive on a container specifies an expression to match


against.
 The expressions for matching are provided by ngSwitchCase directives on
views within the container. The ngSwitchCase is preceded by asterisk or*.
 Every view that matches is displayed.
 If there are no matches, a view with the ngSwitchDefault directive is rendered.

Demo example

Let us see the example that explains the use of ngSwitch directive.

Step 1: Go to the folder location in which the application for ngSwitch is to be


created.
Step 2: Open [Link] file and edit is as follows-

[Link]

import (Component) from '@angular/core';


@Component({
selector: app-root, templateUrl: '/[Link]", styleUris:
['/[Link]
})
export class AppComponent {
counter=3;
}

Step 3: Now open the html file and edit the code as follows –

54
Full stack web Development -Unit -IV Express & Angular V Sem -IT

[Link]

<h3> ngSwitch Demo</h3>


<div [ngSwitch]="counter">
<div *ngSwitchCase="1"> 1 is selected</div>
<div *ngSwitchCase="2"> 2 is selected</div>
<div *ngSwitchCase="3"> 3 is selected</div>
<div *ngSwitchCase="4"> 4 is selected</div>
<div "ngSwitchDefault Default value </div> </div>

Step 4: Run the above application at the command prompt by issuing the
command ng serve -o. The web browser will get opened up and the output will be
displayed as follows -

Output is

ngSwitch Demo

3 is selected

2. Attribute directive

Many ngModules such as the FormsModule define their own attribute directives. The
most common attribute directives are as follows:

Directive Description

ngModel The ngModel directive binds the value changes in the attached form
element with changes in the data model. Thus we can use ngModel to
create two-way data bindings for reading and writing input-control
values.
ngForm The ng Form directive creates a top-level FormGroup instance and
binds it to a <form> element to track aggregated form value and
validation status. As soon as we import Forms Module, this directive
becomes active by default on all <form> tags There is no need to add
a special selector.
ngStyle This directive updates the style of an HTML element.

55
Full stack web Development -Unit -IV Express & Angular V Sem -IT

23. What is routing in [Link]? Illustrate configuring of dynamic routing in


angular application with suitable code example (April/May -2024)

In [Link], routing refers to the mechanism that allows you to define the behavior
of your application in response to HTTP requests. Essentially, it maps incoming
requests to specific handlers (functions) based on the request's URL path and HTTP
method (GET, POST, PUT, DELETE, etc.).

Configuring of dynamic routing

In an Angular application, dynamic routing allows you to create routes that can
handle varying parameters or conditions. This is useful for scenarios like displaying
details for a specific item or user based on an ID or other parameters.

Dynamic Routing: Define routes with parameters in the routing module (app-
[Link]).

Access Parameters: Use ActivatedRoute to access route parameters in components.

Router Links: Use [routerLink] to navigate between routes with parameters.

Steps to Configure Dynamic Routing in Angular

1. Set Up Angular Project: First, ensure you have Angular CLI installed and
create a new Angular project if you haven’t done so:

2. Generate Components: Generate components for the routes you want to


define:

3. Configure Routing: Update the routing module to define routes with parameters.

Example Code

1. Update [Link]

Routing Module:

56
Full stack web Development -Unit -IV Express & Angular V Sem -IT

The [Link] file sets up routes. The route with path:


'user/:id' includes a dynamic segment :id that can be accessed in the
UserDetailComponent.

In src/app/[Link], configure the routes with parameters:

2. Define Components

Home Component ([Link])

o HomeComponent: Contains links that navigate to UserDetailComponent


with different IDs. The routerLink directive creates links that include
route parameters.

57
Full stack web Development -Unit -IV Express & Angular V Sem -IT

User Detail Component ([Link])

o UserDetailComponent: Uses ActivatedRoute to access the route


parameters. The [Link]('id') method retrieves the
dynamic segment from the URL.

3. Update [Link]

o The <router-outlet> directive in [Link] is where Angular


injects the component that matches the current r

Update the [Link] to include the router outlet:

58
Full stack web Development -Unit -IV Express & Angular V Sem -IT

[Link] and construct request and response object in express js(April/May-2025)


In [Link], the request and response objects are core components used to handle HTTP requests
and send responses. Here's a comparison and an example of how to construct and use them:
Comparison of Request and Response Objects
Feature Request Object (req) Response Object (res)
Purpose Represents the incoming HTTP request. Represents the outgoing HTTP response.
Access Data Contains data like query parameters, body, Used to send data back to the client.
headers, etc.
Methods Provides methods Provides methods
like [Link], [Link], [Link], etc. like [Link](), [Link](), [Link](),
etc.
Properties Includes [Link], [Link], [Link], Includes [Link], [Link],
etc. etc.
Customization Used to extract and process client-sent data. Used to format and send responses to the
client.
Constructing and Using Request and Response Objects

const express = require('express');


const app = express();

// Middleware to parse JSON body


[Link]([Link]());

// Example route
[Link]('/example', (req, res) => {
// Accessing the request object
const name = [Link]; // Extracting data from the request body
const queryParam = [Link]; // Extracting query parameter
const headerValue = [Link]['custom-header']; // Accessing a custom header

// Constructing a response
if (!name) {
[Link](400).json({ error: 'Name is required' }); // Sending a JSON response with
status code
} else {
[Link](200).send(`Hello, ${name}! Your ID is ${queryParam}.`); // Sending a plain
text response
}
});

// Start the server


[Link](3000, () => {
[Link]('Server is running on port 3000');
});
Key Methods and Properties
Request (req)

 [Link]: Access route parameters (e.g., /user/:id).


 [Link]: Access query string parameters (e.g., ?id=123).
 [Link]: Access the request body (requires middleware like [Link]()).
 [Link]: Access HTTP headers.
Response (res)

 [Link](code): Set the HTTP status code.

59
Full stack web Development -Unit -IV Express & Angular V Sem -IT
 [Link](data): Send a plain text or HTML response.
 [Link](data): Send a JSON response.
 [Link](url): Redirect the client to another URL.

This example demonstrates how to handle incoming data and construct appropriate responses in
[Link]. It's a flexible and powerful way to build web applications!

60
Full Stack Web Development UNIT – V React III Yr/ V sem

UNIT-V MERN STACK –


Basic React applications – React Components – React State – Express
REST APIs – Modularization and Webpack – Routing with React Router
– Server-side rendering

Two Marks Questions with Answers

1 What is MERN stack? ( Nov/Dec -2023)

MERN stack is a collection of four technologies that are used to develop full
stack web applications. MERN stack comprises of four technologies namely,

M stands for MongoDB which is used for preparing database.


E stands for Express mainly used for developing [Link] web framework.
R stands for React mainly used for developing client side JavaScript
framework.
N stands for Nodejs which is an open source, cross-platform, JavaScript
run-time environment that executes JavaScript code outside of a browser.

2. What is ReactJS?

ReactJS is an open source, component-based front end JavaScript library


maintained by Facebook

This library is responsible only for the view layer of the application. That
means this JavaScript is for building user interfaces.

3 .What are functional components in ReactJS?

Functional components are simple JavaScript functions. The functional


components return the JSX(JavaScript XML)code to render the DOM tree.

Following code fragment shows the functional component

function Welcome(props) { return <h1>Welcome ([Link])</h1>; }


Alternatively, the functional component can be created using arrow
function as follows-
const Welcome (props) => { return <h1>Welcome ([Link])</h1>;

4. How to define class components in ReactJs?

To define the class component, we have to first create a class and extend
React Component class.

Class components are ES6 classes that return JSX. Below, is a class
component which is similar to Welcome function(as given in Functional
component):

class Welcome extends React Component{


render() {
61
Full Stack Web Development UNIT – V React III Yr/ V sem

return <h1>Welcome, (this props name)</h1>;


}
}

5. What is the use of setState() function in ReactJS?

The setState() is used to change the value of the state object. State can be
updated in response to event handlers, server responses, or prop changes.

This is done using the setState() method. The setState() method enqueues
all of the updates made to the component state and instructs React to re-
render the component and its children with the updated state.

6. What is modularization?

Modularization is a technique which helps in code organization by splitting


the code into smaller parts. The modular architecture involves breaking
down a program into subprograms called modules.

7. What is Webpack? What is webpack in React and why use it?(April/May-2025)

Webpack in react is a JavaScript module bundler that is commonly


used with React to bundle and manage dependencies. The webpack takes
all the necessary JavaScript files, CSS files combine them into a single
bundle that can be loaded by the browser.

8. What is Babel?

Babel is a JavaScript compiler that converts modern JavaScript code


into the version which is compatible with all the browsers. Babel transpiles
modern JavaScript for use in React Components. The transpiler is a tool
used to convert source code into another source code of same level.

The main reason we need babel in modularization is that it gives us the


privilege to make use of the latest things JavaScript has to offer without
worrying about whether it will work in the browser or not.

9. What is React Router

ReactJS router is a single page application.

The single page application is a web application that interacts with the
user by dynamically rewriting the current page, rather than loading entire
new pages from the server.
When a user types a specific URL into the browser and if this URL path
matches any 'route' inside the router file, the user will be redirected to that
particular route.

62
Full Stack Web Development UNIT – V React III Yr/ V sem

10. List and explain the three packages that are used in ReactJS routing
(Nov/Dec -2023)

1. react-router: It is the heart of react-router and provides core


functionalities for routing in web applications and all the packages for
react-router- dom and react-router-native
2. react-router-native: It is used for routing in mobile applications
3. react-router-dom: It is used to implement dynamic routing in web
applications.

11. What is Server side Rendering (SSR)?

Server Side Rendering (SSR) is a technique in which the HTML


contents of React application are displayed on the server side before
sending it to client. With SSR the initial page load is faster and it improves
the search engine optimization.

In server side rendering technique, the HTML page is created at the server
side with all the necessary contents of the site and then it is sent back to
the user.
The user will get fully rendered HTML page that contains all the necessary
information without having to wait for JavaScript or CSS file to load.

12. What are the benefits of reactJS? ( April/May – 2024)

1. Faster debugging and rendering


2. Easy to learn and use
3. Reusability of code components.
4. Readily available JavaScript libraries
5. Works for both iOS and android apps

13. What are the drawbacks of the MERN stack? ( April/May – 2024)
1. Complexity for Beginners. ...
2. Configuration Overhead. ...
3. Scalability Challenges with MongoDB. ...
4. SEO Issues with React. ...
5. Large Bundle Sizes. ...
6. Security Concerns. ...
7. Learning Curve for [Link] and [Link].

[Link] the render function, instead of returning one <div>, try returning two <div>
elemente placed one after the other. What happens? And Why?(Nov/Dec-2024)

function MyComponent() {
return (
<div>First Div</div>
<div>Second Div</div> // ❌This will cause an error
);
}
63
Full Stack Web Development UNIT – V React III Yr/ V sem
React throws a syntax error similar to:

SyntaxError: Adjacent JSX elements must be wrapped in an enclosing tag.

Why Does This Happen?


In JavaScript, especially when using JSX, a function must return a single element. React components render to
a tree with a single root node. Multiple sibling elements (like two <div>s side by side) must be wrapped in
a single parent so React knows how to manage and reconcile the component tree properly.

[Link] between React route parameter and query parameter.(Nov/Dec-2024)

React route parameters and query parameters are both used to pass data through URLs, but they serve different
purposes and are accessed differently in React Router.

Feature Route Parameter Query Parameter


Syntax in URL /book/:id → /book/123 /search?query=react&page=2
Location In path In query string
Defined in
Yes No
route?
Use case Identifying resources Filtering, searching, pagination
Accessed using useParams() useSearchParams()
Optional? No (must match route) Yes
Affects routing? Yes No (same component, just different data)

[Link] are state and props different in React?(April/May-2025)

Feature props state


Definition Data passed to a component Data managed within a component
Mutability Immutable (read-only) Mutable (can change)
Scope Controlled by parent Controlled by component itself
Use case Configure/initialize component Manage interactive/dynamic behavior
Trigger re-render? Yes (when parent re-renders with new props) Yes (when state changes)

64
Full Stack Web Development UNIT – V React III Yr/ V sem

Part B & C Questions


1. Explain the concept of MERN Stack with suitable block diagram

 MERN stack is a collection of four technologies that are used to


develop full stack web applications.
 MERN stack comprises of four technologies namely,
o M stands for MongoDB which is used for preparing database.
o E stands for Express mainly used for developing Node,js web
framework.
o R stands for React mainly used for developing client side JavaScript
framework.
o N stands for [Link] which is an open source, cross-platform,
JavaScript run-time environment that executes JavaScript code
outside of a browser.
 MongoDB, [Link], and [Link] help you build the backend of an
application, while React powers the frontend. By learning MERN stack
will help you to become a full stack developer.

Components of MERN Stack

[Link]

 MongoDB is a NoSQL database where each record is a document


comprising of key-value pairs that are similar to JSON JavaScript Object
Notation) objects.
 MongoDB enables users to create databases, schemas and tables.
 It offers the Mongo shell that provides a JS interface for deleting, querying
and updating the records.

2. Express

 Express is a NodeJS framework that simplifies writing the backend code.


[Link] has powerful models for URL routing (matching an incoming
URL with a server function), and handling HTTP requests and responses.
 For keeping the code precise, ExpressJS offers a range of middleware.

65
Full Stack Web Development UNIT – V React III Yr/ V sem

MERN stack

3. React

 React is one of the most popular open-source front-end JavaScript libraries


used for building Web applications, It is used to build User Interfaces (U)
for single page web application.
 It allows developers to create large web applications that can easily change
the data of the page even without reloading the page.

4. [Link]

 It is open source JavaScript Runtime environment.


 It is Fast - Built on Google Chrome's JavaScript Engine and has a fast code
execution.
 It allows users to run code on the server.
 It comes with the node package manager or npm, enabling users to select
from a wide selection of node modules or packages.

With suitable block diagram explain the concept of MERN stack.

2. Basic React Applications

Let us start the introduction of ReactJS with a real-world example, Suppose


that on a Facebook one. you click the "like on some photograph and then
by the time you scroll down the same n00. the like count gets incremented
by some number, even without reloading your Facebook. This magic
change happens because of our ReactJS!!!

ReactJS is an open source, component-based front end JavaScript library


maintained by Facebook.

This library is responsible only for the view layer of the application. That means
this JavaScript is for building user interfaces.

Features of ReactJS

66
Full Stack Web Development UNIT – V React III Yr/ V sem

Virtual DOM

DOM stands for Document Object Model. It also provides a way to update the
content, structure and style of the document. Virtual DOM is a
representation of original DOM. When user updates something on the web
application, DOM gets updated. Updating the DOM is very slow, most of
the JavaScript frameworks update the whole DOM which makes it slower.
But actually there is no need to update the whole DOM. instead, these
frameworks should update only the part of DOM that is required to update.
This is what the virtual DOM does. This is why ReactJS's DOM
manipulation is much faster than other frameworks. Due to this property,
whenever any change is made in the web application, then those changes
are reflected on the web page within no time.

Components

This feature allows the web developer to create custom elements which can be
reused in HTML.

JSX
JSX is an extension of JavaScript syntax. JSX can be seen as a combination
of javascript and XML. The syntax of JSX is very simple that makes
writing components very easy.
One way data binding
The React/S is designed in such a way that it follows, unidirectional or one
way data binding. That means, data is allowed to flow in one direction at
a time. This helps in achieving greater control over the application. This
makes helps in increasing the efficiency of an application.

67
Full Stack Web Development UNIT – V React III Yr/ V sem

2. Write about Installation of ReactJS

Open the command prompt window and issue the command


npm
C:\Users\DELL>npm install -g create-react-app
(table)
The installation process will get started. Following scrcenshot shows it.

Check if the reactJS is installed or not by checking its version

That all., if it shows some version number then the reactjs is installed.

Creating first program


We will create out simple ReactJS application in which we will simply display
a "Welcome User" message.
Step1: Go to the directory in which the first application is to be created. At
the command prompt issue the command
D:\reactDemo>create-react-app firstapp

68
Full Stack Web Development UNIT – V React III Yr/ V sem

Note that the firstapp is the name of the first program written in reactJS.

Step 2: Now locate the [Link] file which is present inside the src folder. Edit
it as follows -
[Link]
import React from ’react’;
import ReactDOM from react-dom;
[Link](
<h1> Welcome, user!!!</h1>,
[Link]('root')
);

Step 3: Now open the terminal window or command-prompt window and


issue the command
npm start
By this command the web browser gets opened and the output will be
displayed.

----------------------------------------------------------------------------------------------------------

69
Full Stack Web Development UNIT – V React III Yr/ V sem

3. Explain the functional component in React

Components are basic building blocks of any ReactJS application. There


are two types of Components that are created in ReactJS –
1. Functional Components
2. Class Component
1. Functional components
Functional components are simple JavaScript functions. The functional
components return the JSX(JavaScript XML)code to render the DOM
tree. Following code fragment shows the functional component
function Welcome(props){
return <h1>Welcome {[Link]}</h1>;
}
Alternatively the functional component can be created using arrow
function as follows –
const Welcome= (props) =>{
retum <h1>Welcome ([Link]} </h1>;
}
Note that the function name always start with capital letter.
Demo Example
Step 1: Open the command prompt and issue the following command
D:\reactDemo>> create-react-app funcomponent
By this command we are creating a workspace by the name funcomponent
in which we will be creating our function component.
Step 2: Locate [Link] file in the src folder of your application and edit it as
follows -
[Link]
Step 3: Open the terminal window or command-prompt. Switch to
funcomponent folder and
issue the command npm start. The web browser will get opened up
automatically
and the output will be displayed as follows -

localhost:3000

Student Information....

70
Full Stack Web Development UNIT – V React III Yr/ V sem

Roll_no:111

Name:Chitra

React App

phone:1234567890

2. Class component
To define the class component we have to first create a class and extend
[Link] class.
Class components are ES6 classes that return JSX Below. is a class
component which is similar to Welcome function(as given in Functional
component) :
class Welcome extends [Link]{
render(){
return <h1>Welcome, {this [Link]) </h1>
}
}
Note that the class component must have the render) method for returning
JSX.
Demo Example
Step 1: Open the conmmand pronmpt and issue the following command
D:\reactDemo> create-react-app classcomponent
By this command we are creating a workspace by the name classcomponent
in which we will be creating our function component.
Step 2: Locate [Link] file in the src folder of your application and edit it as
follows -
[Link]
Step 3 : Open the terminal window or command-prompt. Switch to
funcomponent folder and issue the command npm start. The web
browser will get opened up automatically and the output will be
displayed as follows –

71
Full Stack Web Development UNIT – V React III Yr/ V sem

4. Explain about Inter Components Communication in detail.


What is the state and props in React?(April/May-2024)
What is React Router and what are the purpose of React Router in a React applications? Illustrate how
states are managed in React and how state information are shared between the components. (5+8)
(April/May-2025)

React is a component-based U library, When the UI is split into small,


focused [Link] can do one job and do it well. But in order to
build up a system into something that Can accomplish an interesting task,
multiple components are necded. These components often need to work in
coordination together and, thus, must be able to communicate with each
other. Data must be exchanged among the components.
In this section we will discuss the communication from parent class to
child class.
Step 1 : Go to the directory in which the first application is to be created.
At the command
prompt issue the command create-react-app <folder-name>
Step 2: Now open the coresponding folder and edit the [Link] file as
follows
[Link]

import React from 'react';


import ReactDOM from react-dom;
}
class Student extends [Link]{
constructor(props){
super(props);
render(){
return <div>
<p>
<h2>Student Information. .... </h2>
<p>
<label>Roll no:<b>{[Link],</b></label>
</p>
</p>
<label>Name:<b>{[Link])</b></lalbel>
<p>
</p>
<label>phone:<b>{[Link]}</b></Mabel>
<p>
<label>Total Marks:<b>{[Link]}</b></label>
</p>
<Marks English={[Link], English} Maths={[Link]}
Science={[Link]} ></Marks>
</div>
}
}

72
Full Stack Web Development UNIT – V React III Yr/ V sem

73
Full Stack Web Development UNIT – V React III Yr/ V sem

class VMarks extends [Link](

Constructor(props)f
super(props);
}
render(){
return<div
h3>Marks of Each Subject are...</h3>
<p>
label> English:<b>{this,props. English} </b> </\abel>
</p>
<p>
lalbel>Maths:Kb>{[Link]} </b></abel>
</p>
<p>
<label>Science:<b> [Link]}</b></label>
</p>
</div>
}
}
cOnst elementStudent Roll"111 Name"Chitra Phone = "1234567890" Marks -
"95
English="40" Maths="35 Science-"20>/Student>
[Link](element,[Link](root))
Step 3 : Open the terminal window and issue the command npm start. The
web browser will
get opened up automatically and the output will be displayed as follows -
Student Information...

React App
C localhost:3000

Roll no:111
Name:Chitra
phone:1234567890
Total Marks:95
Marks of Each Subject are...
English:40
Maths:35
Science:20

The props
The props stand for properties. These are the arguments that are passed
to the react components,
Props are passed to components via HTML attributes,

74
Full Stack Web Development UNIT – V React III Yr/ V sem

For example consider following HTML seript

const element = <Student course="computer science" />;

The component receives the argument as props object. The code is

function Student(props) {

retum <h2> I have opted for{ [Link]}</h2>

The props are basically used to pass data from one component to another
React State
Basic concept
The React State is a built in object which contains data or information
about the component.
The component's changing state can be represented by this state object.
The change in state can happen as a response to user actions or events.
Every time the state of an object changes, React re-renders the
component to the browser. The state object is initialized in the
constructor.
• The state object can store multiple properties.
The setState() function
• The setState() is used to change the value of the state object.
• State can be updated in response to event handlers, server responses, or
prop changes.
This is done using the setState() method. The setState) method enqueues all
of the updates made to the component state and instructs React to re-
render the component and its chíldren with the updated state.
Demo example
Step 1: Create a folder with some suitable name, I have created a folder
named statedemo by the following command

E:> create-react-app statedemo

Step 2: Locate the src folder and edit the [Link] file as follows –
[Link]

import React from 'react':


import ReactDOM from 'react-dom:
import /[Link]':
class Color extends [Link]
constructor(props) {

75
Full Stack Web Development UNIT – V React III Yr/ V sem

super(props);
[Link] = (colomame: "Blue'};
changeColor()
[Link]({colorname: "Golden"}):
}
render(){
return(
<div>
<h1>My Favorite Color is {[Link]) </h1>
<button onClick={(0=> [Link](0}>Clhck to change color</button >
</div>
}
}
Const element = <Color></Color>
[Link](element,[Link]('root')):

Step 3: Open command prompt and type the command npm start. The
output will be displayed on the web browser

React App
localhost:3000
My Favorite Color is Blue
Click to change color

Click the button and we get


React App
localhost:3000
My Favorite Color is Golden
Click to change color
Program explanation: In above application,
1. We have edited [Link] file. The class named Color is a child class of React
Component.
2. In this class, we have written a constructor. This constructor assigns initial
[Link] with variable colorname as blue.
3. In the render) function of React we have displayed a message using hl tag.
Below this message the button component is created.
4. On the button click event the state must get changed. For this purpose, the
event handling function changeColor is written.
5. In changeColor() function, the state is changed by using [Link](). The
parameter passed to this function is state variable colorname with some
updated value. Basically, React provides its own method setState(). The
setState) method takes a single parameter and expects an object which
should contain the set of values to be updated. Once the update is done
the method implicitly calls the render() method to repaint the page.

76
Full Stack Web Development UNIT – V React III Yr/ V sem

6. Thus when the button is clicked the color value changes


from blue to Golden.
Difference between props and State
Prop State

Props are immutable. That means State holds data and it can be
once we set the propS can not be changed over the time.
changed. i.e. States are mutable.

Props can be accessed by child State can not be accessed by


component. child component

Props allow to pass the data from State holds the information
one component to another. about the components.

Props can be used in both State can only be used in class


functional as well as class components.
components.

The parent component sets props for Event handlers generally update
the children components state.

5. What is API?

API stands for Application Programming Interface.


APIs are a set of functions and procedures that allow for the creation of
applications that access data and features of other applications, services, or
operating systems.
In other words, if you want to interact with a computer or system to retrieve
information or perform a function, an API helps you communicate what you
want to that system so understand and fulfil the request.
It is basically a software intermediary that allows two applications to talk to
each other. For example - When we use Facebook, send a message or check
the weather on our mobile phone we use API.
For example - If we want to buy a movie ticket, we go to the online ticket
booking site enter movie name, use credit card information, get the ticket,
print it. The software that interacts with us to perform all these task is
nothing but the A, Following screenshots some well-known examples of API.

77
Full Stack Web Development UNIT – V React III Yr/ V sem

6. What is REST API? (April/May-2024)

REST stands for Representational State Transfer. It is a set of rules that


developers follow while creating their API.
Each URL made by the client is a request and data sent back to the client
is treated as response.
The request consists of,

1. End Point 2. Method 3. Headers 4. Data

(1) Endpoint
The endpoint (or route) is the URL you request. For example -
[Link]
(2) Methods
There are various types of methods. But the most commonly used one
are as follows -
1) GET 2) POST 3) DELETE 4) PUT 5) PATCH
These methods are basically used for performing CRUD operations. Here
C- stands for Create,R- stands for Read, U- stands for Update and
D-stands for Delete.

METHOD PURPOSE

For getting the data from the server, this request is used.
GET The server looks for the data the client has requested and
sends it back to the client.
This method is used when new resource is to be created
on the server, when client uses this method and provides
the data, then the server creates a new entry the database
POST
and acknowledges the client whether the creation is
successful or not.

These are the two methods that are used when the client
wants to update some resource. When PUT method is
PUT
used, then that means client wants to update entire
and
resource. And when PATCH method is used, then that
PATCH
means client simply
wants to update small part of the resource.
DELETE This request is used to delete a resource from the server.

78
Full Stack Web Development UNIT – V React III Yr/ V sem

There are some software tools such as Postman, that help the client to select
the appropriate method and issue the URL. Following screenshot is of a
software tool Postman, using which we can select appropriate method.
[Link] (In this URL the /employee acts as a
endpoint)

GET (A client can select any desired method)


POST
PUT and
PATCH
DELETE
GET
POST
PUT
COPY
HEAD
OPTIONS
LINK
UNLINK
PURGE
LOCK

3) Headers
Header are used to provide authentication and other useful information
to client and server, The HTTP headers are property-value pairs
separated by Colons(:).
For example -
"Content-Type: application/json"
(4) Data
The DATA contains information which the client wants to send to the
server. While sending the DATA to the server the methods such as
POST, PUT, PATCH or DELETE are used.
It is preferred to send the data in JSON format. The format is,

{
Property l:value 1,
Property2:value2
}

79
Full Stack Web Development UNIT – V React III Yr/ V sem

Concept of Node JS API


The NodejS seript is popularly used to create REST API. We will write the
server script in
[Link]. The database is created using MongoDB. The client interface is
handled with the help of
Postman.

7. Write and explain a simple application using REST HTTP method APls
in [Link]
What is REST API and how to create a REST API with [Link] and
Express? (April/May-2024)

Prerequisite: For creating the [Link] Rest API we need following software
to be installed in Our machine
1) Postman: This is an API client. This client software allows us to enter
the request in JSON format and select the commands such as GET,
POST, UPDATE, DELETE and so on.
2) MongoDB: This is a database package. We need MongoDB compass to
be installed along with the mongoDB server application. The MongoDB
compass is a graphical tool for handling database operations.
3) NodeJS: This is a course used for creating an API in js file.
Step1: Make a new folder in your current working directory for creating
Rest APL. Here I am creating a folder named RestApiDemo
Step2: Now open the command prompt window and create [Link]
file using npm init command. Following screenshot illustrates the
same.
At the command prompt simply type the command

npm init

Then hit the enter button. You can add the values of your choice or simply
go on pressing enter key and accept the default value.

80
Full Stack Web Development UNIT – V React III Yr/ V sem

Step 3 : Now install some more packages that are required for creating this
Rest API
Installation of express module
Issue the following command
prompt:\>npm install express

Installation of mongoDB module


Issue the following command
prompt:/ >npm install mongodb

Installation of mongoose module


Issue the following command
prompt:/>npm install mongoose
Command Prompt

81
Full Stack Web Development UNIT – V React III Yr/ V sem

Installation of nodemon
Issue the following command at the command prompt
Prompt:>npm install –g nodemon –save-dev.

The sample [Link] file will show you all these dependencies of the
modules you have installed just now.

[Link]
{
“name": "restapidemo",
"version": "1.0.0",
"description": "This is my Rest API Demo Project",
"main": "[Link],
"scripts": {
"start": "nodemon [Link]"
},
"author": "[Link]",
"license": "ISC",
"dependencies " : {
"express": "A4, 17.1",
"mongodb" ; "^3.6.4",
"mongoose": "A5.12.0"
}
}

Note that I have added following line in [Link] file so that as soon as I
save any changes file, the output gets reflected immediately. I need not
have to run the [Link] file every time.
“start” : “nodemon [Link]”
Step 4 :Now create your main server in a file named [Link].

82
Full Stack Web Development UNIT – V React III Yr/ V sem

[Link]

const express = requíre(express');


const mongoose réquire('mongoose);
url = mongodb://ocalhost/EmployeeDB;
const app express();
[Link](url, {useNewUrlParser:true})
Const con = mnongoose,connection //getting the connection object

require('express):
[Link]([Link]))
[Link]( Open () => {7/on opening the connection, connecting with database
console. log(Connected to Database)
})
[Link]([Link]())
Const employeeRouter = require(‘./routes/employees’) /initial endpoint
[Link](employees,employeeRouter)
[Link](8082. () =>{
console. log("Server Started!!!")
})

Step 5: Create a folder named routes. Inside the routes folder create a file
named [Link]. This file will handle the GET and POST requests of
REST API. Using POST request we can create the API by inserting the
data into the database. The GET request will retrieve and display the
data from
Step 6: Now create another folder named models. Inside models folder create
a file named [Link]. This file will describe the Schema. The fields of
the document are described in this file along with data type and some
other description is mentioned in this file. Note that the schema is
specified in JSON format.
[Link]

const mongoose = require(mongoose')


Const employeeSchema = new [Link]({
name: {
type: String,
required: true
}
designation: {
type: String,
required: true
}
})
[Link] = [Link](‘Employee’,employeeSchema)

83
Full Stack Web Development UNIT – V React III Yr/ V sem

Step 7: For better understanding, the folder structure of this project can be
viewed in the following explorer window.

Step 8 :For getting the output, Open the command prompt window and issue
the following
Command.

D:/NodeJSExamples\RestApiDemo >nodemon run start

You should get the “Server started” and “Connected to Database” messages

Now, Open the Postman and click on Create Request. Select the POST
command issue the URL as
[Link]
And then click on Send button

84
Full Stack Web Development UNIT – V React III Yr/ V sem

Once we hit the send button we get the results by generating the unique_id
for the data which we have inserted.

In this, manner we can insert more data by selecting the Post command.
This data is send [Link] server and then getting stored in the MongoDB
[Link] order to retrieve data being stored, we can use GET method
on Postman client andcomplete data in the form of JSON structure.
We can verify the data by opening the database created in MongoDB.

8. Write a web application of your choice to demonstrate the


webpack modularization concept
Explain about modularization in React using Webpack
tool.(Nov/Dec-2024)

 Modularization is a technique which helps in code organization by splitting


the code into smaller parts. The modular architecture involves breaking
down a program into sub-programs called modules.
 Each module is associated with certain functionality. The module helps to
understand the entire code.
 React is one of the most popular front-end technology that uses the
component structure for modularizing. React uses something called
component structure, where eacn component has its own file. To access
the code in the files. we use import and export.
 Webpack in react is a JavaScript module bundler that is commonly used
with React to bundle and manage dependencies.
 The webpack takes all the necessary JavaScript files, CSS files combine
them into a single bundle that can be loaded by the browser.
 For using the webpack in React we use [Link] fille. Following
are the sections of [Link] file
o Entry: The entry refers to the entry point of React application. All the React
components branch out from appjs and [Link] is found inside [Link]. The
entry attribute is defined as follows-

[Link]={
entry:/app/[Link]
}

o Output: After completing all the processes, the React webpack creates a
bundle file. Using output we can specify the name and location of final
output file. For example-

[Link]={
entry:./app/indexjs,
output:{
path: [Link] dirname, "/dist”), the bundle output path 85
filename: "[Link]", /the name of the bundle
}
Full Stack Web Development UNIT – V React III Yr/ V sem

Loader: Loader is like compiler, it checks for different types of files and match
them with their appropriate loaders for handling them. For example -
[Link]
module: {
Loaders:|{
test: /\. ( js|jsx)$/,
exclude:/(node_modules)/,
loader: babel-Loader’.
}]
}
}

There are certain rules used in the module and those are
est t checks for particular file type(such as js,.css,.jsx and so on)
use t specifies a list of loaders used by any specific file type.
xclude t helps the developer to decide which files should not be
processed.
nclude t helps the developer to decide which files should be processed

For example -

{
test:[Link]/,
use:['style-loader css-loader’]
}
Plugins: An effective plugin interlace is included with Webpack. The majority
of webpack’s functionality makes use of this plugin interface. As a result,
Webpack is more flexible.
MODE: The mode in React helps developers to use different set ups when they
are in development and production mode.
devServer: It is used to quickly build the applications. For example -
[Link] = {

devServer:{.
inline: true,
contentBase:/dist!
port: 3000
},
};

86
Full Stack Web Development UNIT – V React III Yr/ V sem

Use of Babel
 Babel is a JavaScript compiler that converts modern JavaScript code into
the version which is compatible with all the browsers. Babel transpiles
modern JavaScript for use in React Components.
 The transpiler is a tool used to convert source code into another source
code of same level.
 The main reason we need babel in modularization is that it gives us the
privilege to make use of the latest things JavaScript has to offer without
worrying about whether it will work in the
browser or not.
Demo Example
Step 1: Create a folder with some suitable name. I have created a folder
named webpack example. Create an [Link] file inside it.
Now initialize npm using npm init -y command

npm init -y

Step 2: Install react and babel packages


Install react

npm i react react-dom

Installing babel

npm i -D @babel/core @babel/preset-eeny @babel/preset-react babel-loader


CSs-loader html webpack-plugin sass sass-loader style-loader rurl-loader
Webpack Webpack-cli Webpack-dev-server

Step 3: webpack webpack-cli webpack-dev-server Create [Link]


inside your folder(In my case it is webpack_ example). Edit the code as
follows
[Link]

Const path = require('path');


[Link] = {
entry:/app/[Link]',
output: {
path: [Link]( dimame, "/dist'), // the bundle output path
filename: "[Link]", // the namne of the bundle
}.
module:{
rules:[
test:/\.js$/,
exclude:/(node modules)/,
use:{
loader:’babel-loader',

87
Full Stack Web Development UNIT – V React III Yr/ V sem

options:
presets:['@babel/preset-env', "@babel/preset-react"]
}
}
},
{
test:/\.css/,
use:['style-loader’, ‘css-loader’]
}
Step 4 : Create two folders namely app and dist. Inside the app folder create
an [Link] [Link] entry point must be [Link]. The output will be in
[Link] which will be created by the webpack in the dist folder.

app
JS anotherModule,js
JS index,js
# [Link]
Step 5 : Install jquery using npm. Following Screenshot illustrates this –

PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL


PS E:\webpack example> npm install jquery—Save
added 1 package, and audited 2 packages in 906ms
found e vulnerabilities
PS E:\webpack example>

Step 6 : The source files in app folder are as follows –


[Link]

import name from [Link];


import /[Link]
import $ from jquery
import React from ‘react’
import ReactDOM from ‘react-dom’

class App extends [Link]


render(){
return (
<h1>Welcome {name}</h1>
)
}
}
[Link](<App/,[Link]('root’))
[Link]

Const name = ‘Parth’

88
Full Stack Web Development UNIT – V React III Yr/ V sem

export default name;


[Link]
body{
background: khaki;
}
H1{
Color:red;
}
[Link]

<DOCTYPE html>
<html>
<head>
<title >Modularization and WebPack Demo </title
</head>
<body>
<div id="root'></div>
<script src="dist/[Link]"> </script>
</body>
</html>

Step 7 : Run and build the application using the command npm run start-

PS E:\webpack example npm run start


> webpack exampledi@1.0.0 start
> webpack-w--mode development

Step 8: Open the [Link] file in suitable web browser-

Welcome Parth

Program explanation: In above code.


1) WE Have created two js files namely [Link] and [Link] and one
.css file ned [Link]. These are bundled together using webpack
module and displayed the output on the browser.
2) In [Link] file we simply render the "Welcome" message with the name which
is obtained from [Link] file. For displaying the welcome
message, the style is applied to hl and body tags and these styles are The
[Link], [Link] and [Link] files are packed together using
Webpack and result is displayed on the browser.

89
Full Stack Web Development UNIT – V React III Yr/ V sem

9. Explain with suitable application for demonstrating routing with


React JS
 Routing is a technique by which the user is directed to different pages
based on their action.
 ReactJS router is a single page application. The single page application is
a web application that interacts with the user by dynamically rewriting the
current page, rather than loading entire new pages from the server. When
a user types a specific URL into the browser and if this URL path matches
any 'route' inside the router file, the user will be redirected to that
particular route.
 Most of the popular sites such as Youtube, facebook and Instagram make
use of ReactJs for rendering multiple views via routing technique.
 There are two important packages that are used while using ReactJs
routing.
1. react-router : It provides core routing components and functions for the
React Router application.
2. React-router-dom: This package enables the user to implement dynamic
routing in a web app.
 React Router is the core package for the router. React Router DOM
contains DOM binding and gives you access to React Router by default.
 The React Router API is based on following elements :
o <Router>: The router that keeps the UI in sync with the URL.
o <Link>: Renders a navigation link.
o <Route>: Renders a UI component depending on the URL.
o <BrowserRouter>: It is used for handling the dynamic URL.
Demo example

Step 1: Create a folder for developing routing application using following


command

D:\reactDemo> create-react-app routerdemo

Step 2 : Install the package for router using the command

D:\reactDemo\routerdemo >npm install react-router-dom

90
Full Stack Web Development UNIT – V React III Yr/ V sem

Step 3 : Inside the sre folder create a .js file. I named it as [Link](note that
here the w is small letter)
[Link]

import React from react;


function Welcome(){
return(
</div>
<h1> Welcome User!!! <h1>
< /div>
);
}
Export default Welcome
Step 4 : Again create one more js file inside the src folder. I have named it as
[Link](Again note that c is in small letter here.)
[Link]
import React from react;
function Contact(){
return
<div>
<p> <b>Phone: </b>1234567890 </p>
<p><b>Email:</b>[Link]@[Link]</p>
</div>
);
}
Export default contact

Step 5: Locate [Link] from src folder. Specify the routes for the above created
two files-
[Link] and [Link] files.
[Link]
import React from 'react;
import ReactDOM from react-dom';
import (BrowserRouter, Link, Switch, Route, Routes) from 'react-router- dom';
import Welcome firom /welcome';
import Contact from /contact';
function App){
retum(
<div>
<h1> Router Demo </h1>
<u1>
<li><Link to="/welcomepg”>Welcome Page</Link></li>
<li><Link to="contactpg’”>Contact Page</Link></li>
</ul>Routes>
<Route path="/welcomepg" element ={<Welcome />}/>
<Route path="/contactpg” element={<Contact />} />
</Routes>
</div>
)

91
Full Stack Web Development UNIT – V React III Yr/ V sem

}
<BrowserRouter>
<App></App>
</BrowserRouter>,
[Link]('root"
));

10. What is server side rendering? Explain.


Write a step-by-step procedure to enable server-side rendering for a React app. (7)
(Nov/Dec-2024)
11. Server-side Rendering

Server Side Rendering(SSR) is a technique in which the HTML Contents of


React With SSR the initial page load is faster and it improves the search
engine optimization.
In server side rendering technique, the HTML page is created at the server
side with all the necessary contents of the site and then it is sent back to
the user.
The user will get fully render HTML page that contains all the necessary
information without having to wait for and JavaScript or CSS file to load.
That means the user who visits the web site will be able to see everything
much faster than if they were looking at the blank screen application are
displayed on the server side before sending it to client, while waiting for
JavaScript files to load.
Server-side rendering is used in many popular JavaScript frameworks,
including Angular and React. There are also other frameworks like Preact,
which aims to lightweight alternative to React.
In general, websites that use server-side rendering include social media
sites such Facebook and Twitter, as well as e-commerce websites like
Walmart and Amazon.
For example - Suppose we have a React application that displays the list
of some articles. When user requests the page, the server retrieves the
92
Full Stack Web Development UNIT – V React III Yr/ V sem
information from backend API and uses React's rendering engine to
generate HTML content on the server-side.

93
Full Stack Web Development UNIT – V React III Yr/ V sem

After creating the HTML file, it is sent to the client along with necessary
JavaScript files. User can immediately display this HTML page on the web
browser. After the initial page load, the application behaves like a typical
React application and any additional user interaction is handled by the
client-side JavaScript code. This means that the user experience is still
interactive and dynamic.
• The process of utilizing the HTML rendered on the server for a component
is called hydration. The [Link]() function does not perform
hydration but replaces the entire HTML tree by rendering the component
from the scratch. For hydration, We need to use [Link]()
function.

//import App components


import { App } irom /components/app:
// compile App component in #app HTML element
[Link]( <App/>[Link]('app));

This function works exactly the same as the render function but it utilizes the
server-side rendered HTML instead of rendering the component. However,
it expects the server- side rendered HTML and HTML rendered by the App
component to be exactly the same. If there is a mismatch, it can lead to
unexpected results.
2. The advantages and disadvantages of server side rendering.

Advantages of server-side rendering


1) Easy Indexing by search Engines : As contents are rendered at the server
side before sending it to the user, the search engines can casily index and
crawl it.,
2) Fast load time: The server side rendering improves the page loading
improves the overall user experience.
3) Indexing with the use of Social media : Client-side rendering is not
supported by Facebook's Open Graph Protocol or Twitter Cards,. for
example. If social media sharing is an important part of marketing
strategy, server-side rendering may be a better option.
Disadvantages of server-side rendering
1) Increased burden on Server: Due to server side rendering, it becomes costly
and resource intensive, the server has to bear the full burden of rendering
contents for users.
2) lower page rendering: The Server side rendering is ideal for statíc HTML site
generation, but for complex applications it may result in slower page
rendering.
3.

94
Full Stack Web Development UNIT – V React III Yr/ V sem

Difference between Server-Side Rendering(SSR) and Client-Side Rendering


(CSR):
In server side rendering, the HTML contents are generated on the server on the
other hand in client side rendering, the HTML contents are generated on the
client side along with JavaScript.
SSR requires additional server-side configuration while CSR requires less
server-side configuration.
SSR is useful for improving the initial page load time and search engine
optimization. On the other hand, CSR is suitable for applications with dynamic
user interfaces that require frequent updates without refreshing the page.
The SSR sends the pre-rendered HTML page to the client. While CSR sends the
minimal HTML page to the client.

12. What in state and props in React with suitable code example, illustrate
how to build dynamic forms in React? April/May -2024)

In React, state and props are two core concepts that help manage data and
UI components.

State

 State is a built-in object that stores property values that belong to a


component. When the state object changes, the component re-
renders.
 State is managed within the component (local state).

Props

 Props (short for properties) are read-only attributes passed from


parent to child components. Props allow data to be passed down the
component tree.
 Props are immutable, meaning they cannot be changed by the child
component receiving them.

Dynamic Forms in React

Dynamic forms can be built by maintaining form data in the state and
rendering form elements based on this state. Here’s a step-by-step example:

1. Create a form component:


2. Manage form data in state:
3. Handle form submission:

import React, { useState } from 'react';


// DynamicForm Component

95
Full Stack Web Development UNIT – V React III Yr/ V sem

const DynamicForm = () => {


// Initial state for form fields
const [formFields, setFormFields] = useState([
{ name: 'username', type: 'text', value: '' },
{ name: 'email', type: 'email', value: '' },
{ name: 'password', type: 'password', value: '' },
]);

// Handle input change


const handleChange = (index, event) => {
const newFormFields = [...formFields];
newFormFields[index].value = [Link];
setFormFields(newFormFields);
};

// Handle form submission


const handleSubmit = (event) => {
[Link]();
const formData = [Link]((data, field) => {
data[[Link]] = [Link];
return data;
}, {});
[Link]('Form Data Submitted:', formData);
};

return (
<form onSubmit={handleSubmit}>
{[Link]((field, index) => (
<div key={index}>
<label>{[Link]}</label>
<input
type={[Link]}
name={[Link]}
value={[Link]}
onChange={(event) => handleChange(index, event)}
/>
</div>
))}
<button type="submit">Submit</button>
</form>
);
};

// App Component
const App = () => {
return (
<div>
<h1>Dynamic Form in React</h1>
<DynamicForm />
</div>

96
Full Stack Web Development UNIT – V React III Yr/ V sem

);
};

export default App;

Explanation

1. State Management:
o useState is used to initialize and manage the form fields.
o The state form Fields is an array of objects where each object
represents a form field with properties name, type, and value.
2. Handling Input Changes:
o handleChange function updates the state when an input field
value changes. It receives the index of the field being changed
and the event object.
3. Form Submission:
o handleSubmit function prevents the default form submission
behavior, gathers the form data from the state, and logs it to the
console.
4. Rendering the Form:
o The form is dynamically generated by mapping over the form
Fields state and rendering an input field for each object in the
array.

This approach allows for flexible and dynamic form handling in React,
making it easy to add, remove, or modify form fields by simply updating the
state.

97
Full Stack Web Development UNIT – V React III Yr/ V sem

13. Explain the different phases of ReactJS component lifecycle. illustrate


how to change the the state of the component on click (Nov/Dec -
2023)
Discuss in detail about React Components and React States with examples
and code snippets.(Nov/Dec-2024)

React components go through several phases in their lifecycle, which can be


categorized into three main stages:
1. Mounting: When the component is being inserted into the DOM.
2. Updating: When the component is being re-rendered due to changes
in state or props.
3. Unmounting: When the component is being removed from the DOM.

1. Mounting
This phase covers the creation of the component and its insertion into the
DOM. The following lifecycle methods are invoked in this phase:
 constructor(props):
o Called before the component is mounted.
o Used to initialize state and bind methods.
 static getDerivedStateFromProps(props, state):
o Called right before rendering.
o Used to update the state based on props.
 render():
o The only required method in a class component.
o Returns the JSX that defines the component's UI.
 componentDidMount():
o Called immediately after the component is mounted.
o Used for initializing things like network requests, setting up
subscriptions, or manipulating the DOM.
2. Updating
This phase occurs when the component's state or props change, causing it
to re-render. The following lifecycle methods are invoked in this phase:
 static getDerivedStateFromProps(props, state):
o Called right before rendering, both on the initial mount and on
subsequent updates.
 shouldComponentUpdate(nextProps, nextState):
o Determines whether the component should re-render or not.
o Returns true by default.
 render():
o Called to re-render the component.
 getSnapshotBeforeUpdate(prevProps, prevState):
o Called right before the most recently rendered output is
committed to the DOM.
o Allows capturing some information (e.g., scroll position) before it
potentially changes.
 componentDidUpdate(prevProps, prevState, snapshot):
o Called immediately after updating.
o Used for operations that need to happen after the DOM has
been updated, like network requests based on updated data.

98
Full Stack Web Development UNIT – V React III Yr/ V sem

3. Unmounting
This phase covers the removal of the component from the DOM. The
following lifecycle method is invoked in this phase:
 componentWillUnmount():
o Called immediately before the component is destroyed.
o Used for cleanup tasks like invalidating timers, canceling
network requests, or cleaning up subscriptions.

Illustrate how to change the the state of the component on click

Changing the state of a React component in response to a click event


is a common task. Here's an example that illustrates how to update
the state when a button is clicked.
 Example Code
import React, { Component } from 'react';

class ClickCounter extends Component {


constructor(props) {
super(props);
// Initialize state
[Link] = {
count: 0,
};
}

// Method to handle button click


handleButtonClick = () => {
// Update state
[Link]((prevState) => ({
count: [Link] + 1,
}));
};

render() {
return (
<div>
<h1>Click Counter</h1>
<p>Count: {[Link]}</p>
<button onClick={[Link]}>Increment</button>
</div>
);
}
}

export default ClickCounter;


Explanation
1. State Initialization:
o The constructor method is used to initialize the state. Here,
[Link] = { count: 0 } sets the initial count to 0.

99
Full Stack Web Development UNIT – V React III Yr/ V sem

2. Event Handler:
o The handleButtonClick method is defined to handle the button
click event. This method uses [Link] to update the
component's state.
o [Link] is used with a callback function that receives the
previous state (prevState). This ensures that the state update is
based on the latest state.
3. Rendering:
o The render method returns JSX that defines the component's
UI.
o The <button> element has an onClick event handler that is set
to [Link]. When the button is clicked, the
handleButtonClick method is invoked, updating the state.
4. State Update and Re-rendering:
o When the button is clicked, the state is updated by
incrementing the count.
o After the state update, the component re-renders, and the new
count value is displayed.

14. Develop Rest API to perform CRUD operations for customer entity
with suitable attributes of your choice ( Nov/Dec -2023)

To develop a REST API to perform CRUD operations for a customer


entity, we'll use [Link], Express, and MongoDB with Mongoose. Here
are the steps:

1. Setup Project and Install Dependencies


2. Connect to MongoDB
3. Define Mongoose Schema and Model
4. Create REST API Routes for CRUD Operations
5. Implement CRUD Operations

Step 1: Setup Project and Install Dependencies

Create a new [Link] project and install the necessary dependencies:

mkdir customer-crud-api
cd customer-crud-api
npm init -y
npm install express mongoose body-parser

Step 2: Connect to MongoDB

Create a file named [Link] to handle the MongoDB connection:

// [Link]

const mongoose = require('mongoose');

const connectDB = async () => {

100
Full Stack Web Development UNIT – V React III Yr/ V sem

try {
await [Link]('mongodb://localhost:27017/customerDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
});
[Link]('MongoDB connected...');
} catch (err) {
[Link]([Link]);
[Link](1);
}
};

[Link] = connectDB;

Step 3: Define Mongoose Schema and Model

Create a file named models/[Link] to define the customer schema


and model:

// models/[Link]
const mongoose = require('mongoose');

const customerSchema = new [Link]({


name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
phone: {
type: String,
required: true,
},
address: {
type: String,
required: true,
},
});

const Customer = [Link]('Customer', customerSchema);

[Link] = Customer;

Step 4: Create REST API Routes for CRUD Operations

101
Full Stack Web Development UNIT – V React III Yr/ V sem

Create a file named routes/[Link] to define the routes for CRUD


operations:

// routes/[Link]
const express = require('express');
const router = [Link]();
const Customer = require('../models/Customer');

// Create a new customer


[Link]('/', async (req, res) => {
try {
const newCustomer = new Customer([Link]);
await [Link]();
[Link](201).json(newCustomer);
} catch (err) {
[Link](400).json({ error: [Link] });
}
});

// Get all customers


[Link]('/', async (req, res) => {
try {
const customers = await [Link]();
[Link](200).json(customers);
} catch (err) {
[Link](500).json({ error: [Link] });
}
});

// Get a customer by ID
[Link]('/:id', async (req, res) => {
try {
const customer = await [Link]([Link]);
if (!customer) {
return [Link](404).json({ error: 'Customer not found' });
}
[Link](200).json(customer);
} catch (err) {
[Link](500).json({ error: [Link] });
}
});

// Update a customer by ID
[Link]('/:id', async (req, res) => {
try {
const customer = await [Link]([Link],
[Link], { new: true, runValidators: true });
if (!customer) {
return [Link](404).json({ error: 'Customer not found' });
}

102
Full Stack Web Development UNIT – V React III Yr/ V sem

[Link](200).json(customer);
} catch (err) {
[Link](400).json({ error: [Link] });
}
});

// Delete a customer by ID
[Link]('/:id', async (req, res) => {
try {
const customer = await [Link]([Link]);
if (!customer) {
return [Link](404).json({ error: 'Customer not found' });
}
[Link](200).json({ message: 'Customer deleted successfully' });
} catch (err) {
[Link](500).json({ error: [Link] });
}
});

[Link] = router;

Step 5: Implement CRUD Operations in Main Server File

Create a file named [Link] to set up the server and use the routes:

javascript
Copy code
// [Link]
const express = require('express');
const bodyParser = require('body-parser');
const connectDB = require('./database');
const customerRoutes = require('./routes/customer');

const app = express();


const port = 3000;

// Connect to MongoDB
connectDB();

// Middleware
[Link]([Link]());

// Use Routes
[Link]('/api/customers', customerRoutes);

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


[Link]('Welcome to the Customer CRUD API');
});

[Link](port, () => {

103
Full Stack Web Development UNIT – V React III Yr/ V sem

[Link](`Server is running on [Link]


});

This setup provides a complete REST API to perform CRUD operations


for a customer entity using [Link] and MongoDB.

15. Discuss React Class Component Lifecycle in the context of online


shopping application with appropriate code snippets.(April/May-2025)

class ProductDetails extends Component {


constructor(props) {
super(props);
[Link] = {
product: null,
isLoading: true
};
[Link]("Constructor: Initialized state");
}

componentDidMount() {
// Simulate API call to fetch product details
[Link]("componentDidMount: Fetching product data");
fetch(`/api/products/${[Link]}`)
.then(res => [Link]())
.then(data => {
[Link]({ product: data, isLoading: false });
})
.catch(err => [Link](err));
}

shouldComponentUpdate(nextProps, nextState) {
// Prevent unnecessary updates
return [Link] !== [Link] || [Link] !==
[Link];
}

componentDidUpdate(prevProps, prevState) {
// Respond to prop changes, e.g. user selects a different product
if ([Link] !== [Link]) {
[Link]("componentDidUpdate: Product ID changed, re-fetching data");
[Link]({ isLoading: true });
fetch(`/api/products/${[Link]}`)
.then(res => [Link]())
.then(data => {
[Link]({ product: data, isLoading: false });
});
}
}

componentWillUnmount() {
[Link]("componentWillUnmount: Cleaning up before component is removed");
// Example: Cancel any outstanding requests, remove event listeners, etc.
}

render() {
const { product, isLoading } = [Link];

if (isLoading) return <p>Loading...</p>;


if (!product) return <p>No product found</p>;

104
Full Stack Web Development UNIT – V React III Yr/ V sem
return (
<div>
<h2>{[Link]}</h2>
<p>{[Link]}</p>
<strong>Price: ₹{[Link]}</strong>
{/* Add to Cart button, reviews, etc. */}
</div>
);
}
}

export default ProductDetails;

[Link] a React JS based web application for an online book store. Write code to perform the
following functionalities.(April/May-2025)

(i)Registration and user Login


(ii) User Profile Page
(iii) Books catalog
(iv) Shopping Cart
(v) Order Conformation.

Here's a basic React JS-based online bookstore application broken down into the requested core
functionalities. This includes:

1. Registration and Login


2. User Profile Page
3. Books Catalog
4. Shopping Cart
5. Order Confirmation

[Link]

import React from 'react';


import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { AuthProvider } from './context/AuthContext';
import { CartProvider } from './context/CartContext';
import Navbar from './components/Navbar';
import Register from './pages/Register';
import Login from './pages/Login';
import Profile from './pages/Profile';
import Catalog from './pages/Catalog';
import Cart from './pages/Cart';
import OrderConfirmation from './pages/OrderConfirmation';

function App() {
return (
<AuthProvider>
<CartProvider>
<Router>
<Navbar />
<Routes>
<Route path="/" element={<Catalog />} />
<Route path="/register" element={<Register />} />
<Route path="/login" element={<Login />} />

105
Full Stack Web Development UNIT – V React III Yr/ V sem
<Route path="/profile" element={<Profile />} />
<Route path="/cart" element={<Cart />} />
<Route path="/order-confirmation" element={<OrderConfirmation />} />
</Routes>
</Router>
</CartProvider>
</AuthProvider>
);
}

export default App;


pages/[Link]

import React, { useContext, useState } from 'react';


import { AuthContext } from '../context/AuthContext';
import { useNavigate } from 'react-router-dom';

export default function Login() {


const { login } = useContext(AuthContext);
const [form, setForm] = useState({ email: '', password: '' });
const navigate = useNavigate();

const handleSubmit = e => {


[Link]();
if (login([Link], [Link])) {
navigate('/');
} else {
alert("Login failed");
}
};

return (
<form onSubmit={handleSubmit}>
<h2>Login</h2>
<input placeholder="Email" onChange={e => setForm({ ...form, email: [Link] })} />
<input type="password" placeholder="Password" onChange={e => setForm({ ...form, password:
[Link] })} />
<button type="submit">Login</button>
</form>
);
}
pages/[Link]

import React, { useContext } from 'react';


import { AuthContext } from '../context/AuthContext';

export default function Profile() {


const { user } = useContext(AuthContext);

return user ? (
<div>
<h2>Profile</h2>
<p><strong>Name:</strong> {[Link]}</p>
<p><strong>Email:</strong> {[Link]}</p>
</div>
) : <p>Please login to view your profile.</p>;
}
pages/[Link]

import React, { useContext } from 'react';


import { CartContext } from '../context/CartContext';
106
Full Stack Web Development UNIT – V React III Yr/ V sem
import { v4 as uuidv4 } from 'uuid';

const books = [
{ id: uuidv4(), title: 'React for Beginners', price: 19.99 },
{ id: uuidv4(), title: 'Mastering JavaScript', price: 24.99 },
{ id: uuidv4(), title: '[Link] Essentials', price: 21.99 }
];

export default function Catalog() {


const { addToCart } = useContext(CartContext);

return (
<div>
<h2>Book Catalog</h2>
{[Link](book => (
<div key={[Link]}>
<h3>{[Link]}</h3>
<p>${[Link](2)}</p>
<button onClick={() => addToCart(book)}>Add to Cart</button>
</div>
))}
</div>
);
}
pages/[Link]

import React, { useContext } from 'react';


import { CartContext } from '../context/CartContext';
import { useNavigate } from 'react-router-dom';

export default function Cart() {


const { cart, removeFromCart, clearCart } = useContext(CartContext);
const navigate = useNavigate();

const total = [Link]((sum, item) => sum + [Link], 0).toFixed(2);

const confirmOrder = () => {


clearCart();
navigate('/order-confirmation');
};

return (
<div>
<h2>Shopping Cart</h2>
{[Link](item => (
<div key={[Link]}>
<p>{[Link]} - ${[Link]}</p>
<button onClick={() => removeFromCart([Link])}>Remove</button>
</div>
))}
<h3>Total: ${total}</h3>
<button onClick={confirmOrder}>Confirm Order</button>
</div>
);
}
pages/[Link]

import React from 'react';

export default function OrderConfirmation() {


const { user, logout } = useContext(AuthContext);

107
Full Stack Web Development UNIT – V React III Yr/ V sem

return (
<nav>
<Link to="/">Catalog</Link> |
{user ? (
<>
<Link to="/profile">Profile</Link> |
<Link to="/cart">Cart</Link> |
<button onClick={logout}>Logout</button>
</>
):(
<>
<Link to="/login">Login</Link> |
<Link to="/register">Register</Link>
</>
)}
</nav>
);
}

108

You might also like