IT3501-Full Stack Web Development Notes
IT3501-Full Stack Web Development Notes
STUDY MATERIAL
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
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
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
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.
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.
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
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:-
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.
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.
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
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.
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
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.
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.
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.
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.
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.
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
3.2 IIS
[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.
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.
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:
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
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.
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
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
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,
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. 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.
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
Emerging Technologies
Summary
Staying informed about these technologies and trends can help full stack developers
build more efficient, scalable, and modern applications.
File: server/[Link]
3. Frontend Development
3.1. Create React Components
File: client/src/[Link]
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:
Output
[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.
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:
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.
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)
A Frontend framework/library
A Backend framework
A Database system
Sometimes a runtime environment, server, or middleware
MongoDB – Database
[Link] – Backend framework
React – Frontend library
[Link] – Runtime environment for JavaScript on the server
1. Frontend (React)
Role:
Role:
Role:
4. Database (MongoDB)
Role:
[Link] and contrast between MEAN stack and MERN Stack (6) Nov/Dec-2024)
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:
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.
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
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.
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.
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
Client-Side ([Link])
Key Components:
jsx
// Sample React booking form snippet
Routes:
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'
});
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)
Directory Structure
project/
├── client/ # React frontend
└── server/ # Express backend
🚀 Backend ([Link] + Express + MongoDB)
server/[Link]
[Link]("mongodb://localhost:27017/athleticEvents");
// 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);
});
function App() {
const [registrations, setRegistrations] = useState([]);
const [form, setForm] = useState({ name: "", age: "", contact: "", event: "" });
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>
);
}
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]
are joined using the ampersand (&) Sign. The parameter can be a number,
string, encrypted value or any other form of data on the database.
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
2. Threaded Models
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.
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.
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.
-------------------------------------------------------------------------------------------------------------------
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.
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-
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]
[Link]
[Link]("Welcome to first [Link] Application program");
run the above program in command prompt with the command node [Link]
-------------------------------------------------------------------------------------------------------------
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.
NPM gets installed along with the installation of [Link]. To verity the presence
of npm package on your machine install following command –
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
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
<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 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"
}
}
for installing any [Link] module we have to use the install [Link] example-
node
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
packages
Once you execute the above commands, the [Link] gets created.
(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
• 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.
[Link].
}
Step 2: Now, open the command prompt and issue the command.
Output is
(3) OS
The os module provides information about the operating system of your computer.
and create a [Link] file as follows,
[Link]
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
The console object is a global object which is used to print different levels of
messages to stdout and stderr.
[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]
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!!");
----------------------------------------------------------------------------------------------------
• 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.
emit(event, [arg1], [arg2], Raise the specified events with the supplied arguments.
[...)
// Raising FirstEvent
Output
D:\NodeJSExamples>node [Link]
When event occurs, My Function is
called
Data passed is: datal data2
Example Code
var events = require('events');
Var eventEmitter = new [Link] ();
//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
.
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");
[Link]("Task3");
[Link]
Output
setTimeout(function_name,delay_in_milliseconds,parameter1,parameter2, ...);
Example [Link]
};
Output
2) setlmmediate()
This function schedules the immediate execution of the callback function
after I/O event.
The syntax is
setImmediate () => {
//function body
})
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]("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
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.
------------------------------------------------------------------------------------------------------------
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?
var fs = require("fs'):
[Link]('Serving User1")
[Link] ([Link]());
});
[Link]("Serving User2");
[Link]("Serving User3");
[Link]("Good Bye!!!");
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,
2. Writing to Buffer
The syntax for writing to the buffer is
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
Example Code
Following is a simple node js program that shows how to write data to the
buffer.
[Link]
[Link]("Good Morning");
Output
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.
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.
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]
var ws = [Link]('[Link]');
[Link](str,'utf8');
[Link]();
Output
Read operation
For reading from the stream we use createReadStream. Then using the data
event the data can be read in chunks.
var fs = require(“fs”);
var str = "";
var rs = [Link]('[Link]');
[Link](“utf8");
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.
Step 4: Use the pipe() function for passing the data from readable stream to
writable stream.
var fs = require("fs");
var rs = [Link]('[Link]');
[Link] ("utf8");
var ws = [Link]('[Link]');
[Link]('utf8');
[Link](ws);
[Link]
Hello friends,
[Link]
Hello friends,
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.
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.
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
var fs = require("fs");
[Link]('[Link]', 'w',function(err,file){
if(err)
[Link](err)
[Link] ('File created!!!');
});
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!!!');
});
Output:
D:\NodeJSExamples>node [Link]
File Writing Done!!!
D:\Node3SExamples>type [Link]
This line is replacing the previous contents
D: \NodeJSExamples>
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
Deleting a file
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
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.
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
Property Purpose
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.
url The url string is sent to the server. This string can be parsed
using [Link]()
close It is used while closing the communication.
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>
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
Key-Value Pairs:
o username=JohnDoe
o password=12345
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.
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.
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.
4. What is mongoDB?
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
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
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.
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:
3
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
4
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
Cost-effective
Full technical support and documentation
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 }
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
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
Method
Purpose
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.
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
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>
9
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.
Understanding Collections
Understanding Documents
11
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
{
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.
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,
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
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.
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.
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.
test> [Link](
user:sysAdmin"
pwd: "pass123"
roles: ["readWrite", "dbAdmin”]
}
);
{ ok:: 1}
test>
3. Remove Users
Syntax
[Link](username)
For example
17
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
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
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.
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.
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>
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.
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.
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
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.
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>
insertedIds:{ '0': 0bjectId("643e4b63436497399alala66")}
}
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,}
}
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
db.collection_name.update(criteria, update_data)
25
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
]
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
}
9. Sorting
26
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
27
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
Step 4: Create the instance of MongoClient by passing the above URL to it.
It is as follows -
Step 5: Finally use the connect method to get connected with the database
[Link]()
[Link]
// get the mongoDB client
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():
29
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
Method Purpose
30
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
Collection Created!!!
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
{
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
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.
39
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
6. sorting
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:
mkdir signup-form
cd signup-form
npm init -y
Install necessary packages:
// Connect to MongoDB
[Link]('mongodb://localhost:27017/signupDB', { useNewUrlParser: true,
useUnifiedTopology: true });
// Middleware
[Link]([Link]({ extended: true }));
42
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
// Routes
[Link]('/', (req, res) => {
[Link]( dirname + '/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
<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>
44
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
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:
45
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
[Link] = connectDB;
In your main server file (e.g., [Link]), import and use the connectDB function:
// Connect to MongoDB
connectDB();
[Link](port, () => {
[Link](`Server is running on [Link]
});
Create a file, for example, models/[Link], to define a schema and model for the data
you want to store:
46
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
required: true
},
mobile: {
type: String,
required: true
}
});
[Link] = User;
In your main server file or routes, use the User model to interact with the database. For
example, handling user registration:
// 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);
47
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
[Link](port, () => {
[Link](`Server is running on [Link]
});
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:
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="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>
<button type="submit">Submit</button>
</form>
<script>
[Link]('applicationForm').addEventListener('submit',
function(event) {
[Link]();
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>
50
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
// Connect to MongoDB
[Link]('mongodb://localhost:27017/studentApplicationDB', {
useNewUrlParser: true, useUnifiedTopology: true });
}
[Link]('Email sent: ' + [Link]);
});
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:
<!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>
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="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]();
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>
// Connect to MongoDB
[Link]('mongodb://localhost:27017/bloodDonorDB', { useNewUrlParser:
true, useUnifiedTopology: true });
56
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
57
Prepared by: [Link], AP/IT
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
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.
[Link](
{
cuisine: { $ne: "American" },
"[Link]": "A",
borough: { $ne: "Brooklyn" }
}
).sort({ cuisine: -1 })
[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.
Features 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();
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 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
6. What is TypeScript?
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.
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-
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
A class contains -
Properties
Constructor
Methods
class <class_name> {
field;
method;
}
Example
class Person {
person id: number;
person name: string;
getName:string{
return "Parth";
}
}
[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.
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
The function without the name is called anonymous function. The type of
functions are dynamically declared at runtime.
For example -
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-
4
Full stack web Development -Unit -IV Express & Angular V Sem -IT
[Link]
[Link]
[Link]
[Link] Binding
[Link]
[Link]
[Link] and Services.
Functions are basic building blocks of any JavaScript document. It makes the
code reusable, readable and maintainable
The function can be defined as follows-
//body of function
}
Function_name[[argument]);
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
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
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.
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
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.
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 )
7
Full stack web Development -Unit -IV Express & Angular V Sem -IT
Ensure that the view and the model are always in sync, reducing
bugs and inconsistencies in the application state.
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.
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();
Attribute Directives
9
Full stack web Development -Unit -IV Express & Angular V Sem -IT
Features of Express
Installing Express
Express is installed using Node Package Manager(npm). The command issued
for installing the express is,
[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
10
Full stack web Development -Unit -IV Express & Angular V Sem -IT
[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.
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();
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.
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
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.).
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.
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.
12
Full stack web Development -Unit -IV Express & Angular V Sem -IT
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
Properties/Methods Description
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](field) This method returns the specified HTTP request header field.
Output
Server started!
URL: /
Protocol: http
IP: 111
Path: /
Hostname localhost
15
Full stack web Development -Unit -IV Express & Angular V Sem -IT
Properties/Methods
Description
[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");
[Link]
});
[Link](new response);
[Link]([Link]);
});
var server app listen (8082, function(){ [Link]("Server started!");
[Link]("Sending HTML contents to the browser...");
});
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
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.
Advantages
Disadvantages
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@]+$/;
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
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
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]
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>
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
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-
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.
variable that is declared with var outside a function block is available for use in
the whole window. For example-
The output is
i=0
i=1
i=2
i=3
i=4
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
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.
Syntax
The typical syntax of interface is
interface interface_name {
25
Full stack web Development -Unit -IV Express & Angular V Sem -IT
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.
A class contains-
Properties
Constructor
Methods
class <class_name> {
field;
method;
}
Example
class Person {
getName:string { Method
return "Arun";
}}
Using constructor
26
Full stack web Development -Unit -IV Express & Angular V Sem -IT
Example
class Person {
Properties
person_id: number;
person_name: string;
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" )
Example
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>
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);
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:
28
Full stack web Development -Unit -IV Express & Angular V Sem -IT
[Link]
a: number;
b: number;
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ер.
Syntax:
[Link]
[Link]();
Step 3: Now open the command prompt and issue the commands
tac-module commonjs [Link]
node./.[Link]
Addition: 380
E:\TypeScript_Code\ModuleDemonade ./[Link]
E:\TypeScript_Code\ModuleDemo>
For compiling the modules, we have used following syntax
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
Step 1:
Create a TypeScript program and define two classes namely Addition and
Multiplication
[Link]
display() {
[Link]('Addition: + (this.a + this.b));
}
}
this.a = a;
this.b = b;
}
show() {
[Link] ("Multiplication:”+ (this.a * this.b));
}
}
[Link]
Command Prompt
E:\TypeScript_Code\ModuleDemo>node ./[Link]
Addition: 300
Multiplication: 20000
E:\TypeScript_Code\ModuleDemo>
Functions are basic building blocks of any JavaScript document. It makes the code
reusable, readable and maintainable
Syntax
//body of function
}
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 -
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));
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.
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.
It provides some commands and schematics which help us with faster code
generation. Most of the frameworks and applications normally come with CLI.
Angular CLI
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.
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
step1: Angular browser displays the [Link] fle on execution of Angular app. We
normally say that “Angular renders your app”
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]’]
})
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
37
Full stack web Development -Unit -IV Express & Angular V Sem -IT
[Link]
[Link]
[Link]
[Link] Binding
[Link]
[Link]
[Link] and Services.
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
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).
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.
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.
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.
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
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.
templateUrl: /[Link].
styleUria: [/[Link]]
export class WelcomeComponent implements OnInit {
constructor() {}
ngOnInit(): void (
current User: String = "Anuradha
[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
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
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]
{{‘1’+’2’}}
Output
44
Full stack web Development -Unit -IV Express & Angular V Sem -IT
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
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]
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
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 defines the communication between components and its views. It
requires dynamic HTML and does not require any complex programming.
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
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
Step 3: Now open [Link] file. Delete the entire default code and add
following code to it.
[Link]
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
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]
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
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
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]
{
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
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.
Two-way binding
50
Full stack web Development -Unit -IV Express & Angular V Sem -IT
<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
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
Syntax
Demo Example
[Link]
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
This is a type of structural directive that shows the template for each item in
the collection or list. The ngFor is prefixed by *.
Demo Example
Following example illustrates how to use *ngFor directive for displaying the list
of students.
[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]
53
Full stack web Development -Unit -IV Express & Angular V Sem -IT
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-
Demo example
Let us see the example that explains the use of ngSwitch directive.
[Link]
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]
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
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.).
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]).
1. Set Up Angular Project: First, ensure you have Angular CLI installed and
create a new Angular project if you haven’t done so:
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
2. Define Components
57
Full stack web Development -Unit -IV Express & Angular V Sem -IT
3. Update [Link]
58
Full stack web Development -Unit -IV Express & Angular V Sem -IT
// 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
}
});
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
MERN stack is a collection of four technologies that are used to develop full
stack web applications. MERN stack comprises of four technologies namely,
2. What is ReactJS?
This library is responsible only for the view layer of the application. That
means this JavaScript is for building user interfaces.
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):
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?
8. What is Babel?
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)
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.
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:
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.
64
Full Stack Web Development UNIT – V React III Yr/ V sem
[Link]
2. Express
65
Full Stack Web Development UNIT – V React III Yr/ V sem
MERN stack
3. React
4. [Link]
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
That all., if it shows some version number then the reactjs is installed.
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')
);
----------------------------------------------------------------------------------------------------------
69
Full Stack Web Development UNIT – V React III Yr/ V sem
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
72
Full Stack Web Development UNIT – V React III Yr/ V sem
73
Full Stack Web Development UNIT – V React III Yr/ V sem
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
function Student(props) {
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
Step 2: Locate the src folder and edit the [Link] file as follows –
[Link]
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
76
Full Stack Web Development UNIT – V React III Yr/ V sem
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 allow to pass the data from State holds the information
one component to another. about the components.
The parent component sets props for Event handlers generally update
the children components state.
5. What is API?
77
Full Stack Web Development UNIT – V React III Yr/ V sem
(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)
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
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
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]
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]
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.
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.
[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
Installing babel
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 –
88
Full Stack Web Development UNIT – V React III Yr/ V sem
<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-
Welcome Parth
89
Full Stack Web Development UNIT – V React III Yr/ V sem
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]
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"
));
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.
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.
94
Full Stack Web Development UNIT – V React III Yr/ V sem
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
Props
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:
95
Full Stack Web Development UNIT – V React III Yr/ V sem
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
);
};
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
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.
render() {
return (
<div>
<h1>Click Counter</h1>
<p>Count: {[Link]}</p>
<button onClick={[Link]}>Increment</button>
</div>
);
}
}
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)
mkdir customer-crud-api
cd customer-crud-api
npm init -y
npm install express mongoose body-parser
// [Link]
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;
// models/[Link]
const mongoose = require('mongoose');
[Link] = Customer;
101
Full Stack Web Development UNIT – V React III Yr/ V sem
// routes/[Link]
const express = require('express');
const router = [Link]();
const Customer = require('../models/Customer');
// 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;
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');
// Connect to MongoDB
connectDB();
// Middleware
[Link]([Link]());
// Use Routes
[Link]('/api/customers', customerRoutes);
[Link](port, () => {
103
Full Stack Web Development UNIT – V React III Yr/ V sem
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];
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>
);
}
}
[Link] a React JS based web application for an online book store. Write code to perform the
following functionalities.(April/May-2025)
Here's a basic React JS-based online bookstore application broken down into the requested core
functionalities. This includes:
[Link]
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>
);
}
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]
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]
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 }
];
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]
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]
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