0% found this document useful (0 votes)
85 views152 pages

Labmanual of NodeJs

The document outlines the vision, mission, and educational objectives of the CMR Institute of Technology's Computer Science and Cyber Security departments, emphasizing the development of skilled professionals for the IT sector. It details the program outcomes and specific skills students will acquire, including proficiency in various programming frameworks and technologies. Additionally, it includes course outcomes, a list of experiments, and micro-projects for practical application of learned skills in web development and security.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views152 pages

Labmanual of NodeJs

The document outlines the vision, mission, and educational objectives of the CMR Institute of Technology's Computer Science and Cyber Security departments, emphasizing the development of skilled professionals for the IT sector. It details the program outcomes and specific skills students will acquire, including proficiency in various programming frameworks and technologies. Additionally, it includes course outcomes, a list of experiments, and micro-projects for practical application of learned skills in web development and security.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

II-B.Tech.

II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

CMR INSTITUTE OF TECHNOLOGY

Vision: To create world class technocrats for societal needs.


Mission: Achieve global quality technical education by assessing learning environment through
 Innovative Research & Development
 Eco-system for better Industry institute interaction
 Capacity building among stakeholders

Quality Policy: Strive for global professional excellence in pursuit of key-stakeholders.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Vision: Develop competent software professionals, researchers and entrepreneurs to serve global society.
Mission: The department of Computer Science and Engineering is committed to
 create technocrats with proficiency in design and code for software development
 adapt contemporary technologies by lifelong learning and face challenges in IT and ITES sectors
 quench the thirst of knowledge in higher education, employment, R&D and entrepreneurship

I. Programme Educational Objectives (PEOs): Engineering Graduates will

1. Pursue successful professional career in IT and IT-enabled sectors.


2. Pursue lifelong learning skills to solve complex problems through multidisciplinary-research.
3. Exhibits professionalism, ethics and inter-personal skills to develop leadership qualities.

II. Programme Outcomes (POs): Engineering Graduates will be able to

1. Apply mathematics, science, engineering fundamentals to solve complex engineering problems.


2. Identify, formulate and analyze complex engineering problems to reach substantiated conclusions.
3. Design and develop a component/system/process to solve complex societal engineering problems.
4. Design and conduct experiments to analyze, interpret and synthesize data for valid conclusions.
5. Create, select and apply modern tools, skills, resources to solve complex engineering problems.
6. Apply contextual engineering knowledge to solve societal issues.
7. Adapt modern engineering practices with environmental safety and sustainable development.
8. Apply professional code of ethics, responsibilities and norms in engineering practices.
9. Compete as an individual and/or as a leader in collaborative cross-cultural teams.
10. Communicate effectively through technical reports, designs, documentations and presentations.
11. Endorse cognitive management skills to prepare project report using modern tools and finance.
12. Engage in independent and life-long learning in the broad context of technological changes.

III. Programme Specific Outcomes (PSOs): Engineering Graduates will be able to

1.Design and develop Computer-Based-Systems using Algorithms, Networks, Security, Gaming, Full Stack,
DevOps, IoT, Cloud, Data Science and AI&ML.
2. Apply cutting-edge technologies to solve real world problems

CMR INSTITUTE OF TECHNOLOGY

CMR Institute of Technology Page No:1


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Vision: To create world class technocrats for societal needs.


Mission: Achieve global quality technical education by assessing learning environment through
 Innovative Research & Development
 Eco-system for better Industry institute interaction
 Capacity building among stakeholders

Quality Policy: Strive for global professional excellence in pursuit of key-stakeholders.

DEPARTMENT OF CYBER SECURITY

Vision: Develop competent software professionals, researchers and entrepreneurs to serve global society.
Mission: The department of CYBER SECURITY is committed to
 create technocrats with proficiency in design and code for software development
 adapt contemporary technologies by lifelong learning and face challenges in IT and ITES sectors
 quench the thirst of knowledge in higher education, employment, R&D and entrepreneurship

I. Programme Educational Objectives (PEOs): Engineering Graduates will

1. Pursue successful professional career in IT and IT-enabled sectors.


2. Pursue lifelong learning skills to solve complex problems through multidisciplinary-research.
3. Exhibits professionalism, ethics and inter-personal skills to develop leadership qualities.

II. Programme Outcomes (POs): Engineering Graduates will be able to

1. Apply mathematics, science, engineering fundamentals to solve complex engineering problems.


2. Identify, formulate and analyze complex engineering problems to reach substantiated conclusions.
3. Design and develop a component/system/process to solve complex societal engineering problems.
4. Design and conduct experiments to analyze, interpret and synthesize data for valid conclusions.
5. Create, select and apply modern tools, skills, resources to solve complex engineering problems.
6. Apply contextual engineering knowledge to solve societal issues.
7. Adapt modern engineering practices with environmental safety and sustainable development.
8. Apply professional code of ethics, responsibilities and norms in engineering practices.
9. Compete as an individual and/or as a leader in collaborative cross-cultural teams.
10. Communicate effectively through technical reports, designs, documentations and presentations.
11. Endorse cognitive management skills to prepare project report using modern tools and finance.
12. Engage in independent and life-long learning in the broad context of technological changes.

III. Programme Specific Outcomes (PSOs): Engineering Graduates will be able to

1.Design and develop Computer-Based-Systems using Algorithms, Networks, Security, Gaming, Full Stack,
DevOps, IoT, Cloud, Data Science and AI&ML.
2. Apply techniques of cyber security to solve real world problems

CMR Institute of Technology Page No:2


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Course B.Tech.-IV-Sem. L T P C
Course Code 24CSPC46 - - 2 1

Course Outcomes (COs) & CO-PO Mapping (3-Strong; 2-Medium; 1-Weak Correlation)
COs Upon completion of course the students will be able to PO4 PO5 PO9 PO12 PSO2
CO1 build website with HTML5, CSS, Bootstrap and JavaScript 3 3 3 3 3
CO2 demonstrate JavaScript using NodeJS and MongoDB 3 3 3 3 3
CO3 develop single page application using Angular 3 3 3 3 3
CO4 develop single page application using React JS 3 3 3 3 3
CO5 design web application using Django 3 3 3 3 3

List of Experiments
Week Title/Experiment
1 Demonstrate version control in Git and Github using simple html code.
2 Design a simple webpage using bootstrap template.
3 Write a java script code to validate user registration and login form.
4 Write a jquery code to show website slider.
5 Create a simple Node.js server with routes login, register, profile and logout.
6 Write middleware to validate users and generate JWT and redirect to profile.
7 Write MongoDB model for the user and query to fetch user, validate and register.
8 Design a Single Page Application with different menu items using Angular.
9 Fetch user details from server using REST API and show in profile menu using Angular.
10 Design Single Page Application with different menu items using react.
11 Install Django and setup a virtual environment. Design Web Application with different
menu items using Django.
12 Fetch user details from server using REST API and show in profile menu using Django.
References
1. Full Stack Development Lab Manual, Dept. of CSE, CMRIT, Hyd.
Micro-Projects: Student should submit a report on one of the following/any other micro-
project(s) approved by the lab faculty before commencement of lab internal examination.
1. Build Real Estate Application using MERN Stack.
2. Build Real World LMS eLearning Marketplace using NextJs React Node MongoDB.
3. Build Job Portal Application Using MERN Stack with Redux.
4. Build Your Portfolio Website with Angular JS.
5. Build an Online Coding Platform Project using AngularJS.
6. Build Image Sharing & Social Network App with Angular and Firebase.
7. Build Car Zone - A Used Car Selling Business Website Using Django.
8. Building an Advanced Banking Application with Django.
9. Build E-commerce REST API with Django.
10. Build a Subscription Platform with PayPal's API Using Django.

CMR Institute of Technology Page No:3


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

1.Demonstrate version control in Git and Github using simple html code.

Step1 : Introduction about Git and Github

Explain about what is version control system and its use.


What is git and github

Git-is the version control system ,it is of type distributed


GitHub- it is the remote repository in distributed version control system

Explain about the terms working directory,local repository,remote repository,push,pull,checkout

Explain git architecture ,in that what is working directory,staging area,remote repository

Step2 : installation of git in local system and creation of account in github

Explain about above steps and complete the procedure

Step3 : create a folder and make it as your local working directory

To start local repoitory

Use git init

Example : i created a following directory in my system

D:\ram\fsd\exp1

Now i want to make the above folder exp1 as my local repository

In cmd by going to your respected directory type git init - it will initiate a empty git repository which acts as a local
Repository

It will create .git hidden file in the above loaction

CMR Institute of Technology Page No:4


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

The following contents are present in ,git folder

Now open the local working directory in visual studio code /any code editor and create an html file with your desired name

Now check your local repository whether it is tracked or not


Use git status command

CMR Institute of Technology Page No:5


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Here we need to explain about life cycle of file in git


In git the file will be in one of the following state
1. Untracked - file which is present in working directory ,which is unaware by the git this type of file is called
untracked

2. Staged - files which are added to staging area

To add files to staging area use the following command


git add filename - general syntax
git add index.html

3. Commited state - Any file which is commited is said to be in commited state


To commit a file first you need to give authorized credentials to tell repository by whom the changes are
made
For that use the following sysntax
git config --global user.email “your mail id”
git config --global user.name “your mail id”

Note: Here global keyword is helpful if you want all the repositories in your system is executing by
only one

You will get following errors if you not config the credentials

CMR Institute of Technology Page No:6


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

1.
To config credentials

Now we have given credentials


Commit a file use the following syntax:
git commit -m “commit message”
If we did not give commit message it will pop up a file and asks to type the commit message

There enter the message

If you have made changes to the file and want to save them before exiting Vim, you
can use the command :wq This command saves the changes and exits Vim. Here are
the steps to follow:
1 Press the Esc key to switch to command mode.
2 Type :wq and press enter
It will come out of the file and shows following msg

CMR Institute of Technology Page No:7


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Now again check git status

If everything is ok you will see above message

If you want to know log of git then use


git log command

4. Modified state : if you made any changes to the file which is tracked by git is
inmodified state
Now change the code:
To see this now iam making changes to my index.html and adding the following line

Now using git status check the modified file

CMR Institute of Technology Page No:8


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

For modified files we can directly commit using the following command

git commit -a -m “this commit adds h2 tag to code”

Till now we worked only on local repository

Now we need to push code to remote repository


For this we need to have a repository in github
Create an account in github
Now create a repsitory in github

Initially it will be empty


Now we need to establish connection from our local repository to remote repository

This code you will see in the repository you created

CMR Institute of Technology Page No:9


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Now to push code to repository use the following syntax

After typing git push origin master it will ask you authentication msg execute as it
asks

Now check github repository

CMR Institute of Technology Page No:10


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Viva Questions:

1.What is git?

Ans: Git is a modern and widely used distributed version control system in the world. It is developed to
manage projects with high speed and efficiency. The version control system allows us to monitor and work
together with our team members at the same workspace.

2.What is the difference between Git and GitHub ?

Ans: Git is a free, open-source version control tool that developers install locally on their personal
computers, while GitHub is a pay-for-use online service built to run Git in the cloud.

3.What are the benefits of version control system?

Ans:

 Enhances the project development speed by providing efficient collaboration,


 Leverages the productivity, expedites product delivery, and skills of the employees through better
communication and assistance,
 Reduce possibilities of errors and conflicts meanwhile project development through traceability to
every small change,
 Employees or contributors of the project can contribute from anywhere irrespective of the different
geographical locations through this VCS,
 For each different contributor to the project, a different working copy is maintained and not
merged to the main file unless the working copy is validated. The most popular example is Git,
Helix core, Microsoft TFS,

4.What is a repository in Git ?

Ans: A Git repository is a central storage location for managing and tracking changes in files and
directories. It is a crucial component of the Git version control system, which enables collaborative
development and allows multiple developers to work on a project simultaneously.

5.What is difference between git pull and git fetch?

Ans: The key difference between git fetch and pull is that git pull copies changes from a remote repository
directly into your working directory, while git fetch does not. The git fetch command only copies changes
into your local Git repo. The git pull command does both.

CMR Institute of Technology Page No:11


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

2.Design a simple webpage using bootstrap template

Index.html:

<html>
<head>
<title>YOGO Web Template - Easy Tutorials</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,600&display=swap"
rel="stylesheet">
</head>
<body>
<section class="header">
<div class="container">
<nav class="navbar navbar-expand-lg navbar-light">
<a class="navbar-brand" href="#"><img src="images/YOGO.png"></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-
target="#navbarNav" aria-controls="navbarNav" aria-expanded="false">

CMR Institute of Technology Page No:12


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

<i class="fa fa-bars"></i>


</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto text-right">
<li class="nav-item">
<a class="nav-link active-home" href="#">HOME</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">SERVICES</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">PRICING</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">ABOUT US</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">CONTACT US</a>
</li>
</ul>
</div>
</nav>

<div class="row banner">


<div class="col-md-6">
<h1>Let's Start The Magic</h1>
<p>YOGO helps people to learn new things without spending<br>too much money
on unnecessary things.</p>
<a href="https://www.youtube.com/c/EasyTutorialsVideo?sub_confirmation=1"
class="express-btn">JOIN FREE</a>
<a href="https://www.youtube.com/c/EasyTutorialsVideo?
sub_confirmation=1">EXPLORE MORE</a>
</div>
<div class="col-md-6 text-center">
<img src="images/home-pic.png" class="img-fluid">
</div>
</div>

</div>
</section>

<section class="service">
<div class="container">
<h2 class="title">We provide a wide range<br> of services</h2>
<p class="subtitle">Let's start odering with YOGO app to save a huge money
today</p>
<div class="row">
<div class="col-md-4">
<div class="service-box">
<img src="images/Icon-1.png">

CMR Institute of Technology Page No:13


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

<h6>Express Delivery</h6>
<p>Lorem ipsum, or lipsum as sometimes known, is dummy text
used in</p>
<i class="fa fa-arrow-right"></i>
</div>
</div>
<div class="col-md-4">
<div class="service-box active-service">
<img src="images/Icon-2.png">
<h6>Offer Arround You</h6>
<p>Lorem ipsum, or lipsum as sometimes known, is dummy text
used in</p>
<i class="fa fa-arrow-right"></i>
</div>
</div>
<div class="col-md-4">
<div class="service-box">
<img src="images/Icon-3.png">
<h6>Pocket Friendly</h6>
<p>Lorem ipsum, or lipsum as sometimes known, is dummy text
used in</p>
<i class="fa fa-arrow-right"></i>
</div>
</div>
</div>
</div>
</section>

<section class="feature">
<div class="container">
<div class="row">
<div class="col-md-6 text-center">
<img src="images/feature.png">
</div>
<div class="col-md-6">
<h2>We always love to hear from <br> our customers</h2>
<p>Lorem ipsum, or lipsum as sometimes <br>known, is dummy text
used in</p>
<a href="https://www.youtube.com/c/EasyTutorialsVideo?
sub_confirmation=1">WATCH NOW</a>
</div>
</div>
</div>
</section>

<section class="explore">
<div class="container">
<div class="row">

<div class="col-md-6">
<h2>How does YOGO make <br>life better</h2>
<p>Lorem ipsum, or lipsum as sometimes <br>known, is dummy text
used in</p>

CMR Institute of Technology Page No:14


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

<a href="https://www.youtube.com/c/EasyTutorialsVideo?
sub_confirmation=1">EXPLORE NOW</a>
</div>
<div class="col-md-6">
<img src="images/explore.png" class="img-fluid">
</div>
</div>
</div>
</section>

<section class="review">
<div class="container">
<div class="bd-example">
<div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleCaptions" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleCaptions" data-slide-to="1"></li>
<li data-target="#carouselExampleCaptions" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<img src="images/testimonial-1.png">
<div class="carousel-caption">
<h6>Jennifer Lopez</h6>
<small>CEO & FOUNDER @ Microsoft</small>
<p>Lorem ipsum, or lipsum as sometimes <br>known, is dummy text used in lorem
ipsum, or lipsum as sometimes <br>known, is dummy text used in</p>
</div>
</div>
<div class="carousel-item">
<img src="images/testimonial-2.jpg">
<div class="carousel-caption">
<h6>George Symonds</h6>
<small>SENIOR MANAGER @ Google</small>
<p>Lorem ipsum, or lipsum as sometimes <br>known, is dummy text used in lorem
ipsum, or lipsum as sometimes <br>known, is dummy text used in</p>
</div>
</div>
<div class="carousel-item">
<img src="images/testimonial-3.jpg">
<div class="carousel-caption">
<h6>Ying Yue</h6>
<small>FASHION DESIGNER @ Myntra</small>
<p>Lorem ipsum, or lipsum as sometimes <br>known, is dummy text used in lorem
ipsum, or lipsum as sometimes <br>known, is dummy text used in</p>
</div>
</div>
</div>
</div>
</div>
</div>
</section>

CMR Institute of Technology Page No:15


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

<section class="footer text-center">


<div class="container">
<h2>Subscribe To Our Newsletter</h2>
<form>
<input type="email" placeholder="Enter Your Email.." required>
<button type="submit">SUBSCRIBE</button>
<small>Copyright @ 2019, Designed by Easy Tutorials.</small>
</form>
</div>
</section>
</body>
</html>

Style.css:

*{
margin: 0;
padding: 0;
font-family: 'Montserrat', sans-serif;
}
.header{
background: #6900d1;
}
.navbar{
padding-top: 20px !important;
}
.nav-item{
margin-left: 40px;
margin-bottom: 10px;
}
.nav-link{
color: #fff !important;
font-size: 12px !important;
padding: 0 0 5px 0 !important;
display: unset !important;
}
.navbar-brand img{
width: 125px;
}
.fa-bars{
color: #fff;
font-size: 40px !important;
}
.navbar-toggler{
border: 0 !important;

CMR Institute of Technology Page No:16


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

outline: none !important;


padding: initial !important;
}
.active-home{
border-bottom: 2px solid #fff;
}
.nav-link:hover{
border-bottom: 2px solid #fff;
}
.banner{
margin-top: 8%;
color: #fff;
}
.banner h1{
margin: 80px 0 50px;
font-weight: 600;
font-size: 50px;
}
.banner img{
max-height: 500px;
}
.banner a{
padding: 12px;
width: 150px;
display: inline-block;
background: #6900d1;
text-decoration: none !important;
color: #fff;
border: 2px solid #fff;
border-radius: 5px;
text-align: center;
margin-top: 30px;
font-size: 14px;
}
.banner a:hover{
color: #fff;
}
.express-btn{
background: #fff !important;
color: #000 !important;
margin-right: 5px;
}

/*-----------service----------*/

.service{
margin: 75px 0;
}
.title{
text-align: center;
font-weight: bold;
margin-bottom: 30px;
}

CMR Institute of Technology Page No:17


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

.subtitle{
text-align: center;
margin-bottom: 70px;
font-size: 15px;
}
.service-box{
padding: 0 35px;
cursor: pointer;
margin-bottom: 10px;
transition: .4s;
}
.service-box img{
width: 60px;
margin-top: 65px;
margin-bottom: 45px;
}
.service-box h6{
margin-bottom: 40px;
font-weight: bold;
}
.service-box p{
font-size: 14px;
color: #808080;
}
.fa-arrow-right{
font-size: 22px !important;
margin-top: 30px;
margin-bottom: 35px;
cursor: pointer;
}
.service-box:hover,.active-service{
background: #6900d1;
border-radius: 5px;
color: #fff !important;
box-shadow: 0 15px 15px 2px rgba(213,213,213,0.5);
}
.service-box:hover p{
color: #fff !important;
}
.active-service p{
color: #fff;
}

/*-------feature-----*/

.feature,.explore{
margin: 200px 0;
}
.feature img{
max-width: 77%;
cursor: pointer;
}
.feature h2{

CMR Institute of Technology Page No:18


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

margin-top: 100px;
font-weight: bold;
line-height: 50px;
}
.feature p,.explore p{
margin-top: 25px;
margin-bottom: 50px;
color: #808080;
font-size: 14px;
line-height: 18px;
}
.feature a,.explore a{
width: 170px;
padding: 15px 10px;
display: block;
background: #6900d1;
text-decoration: none !important;
color: #fff !important;
border-radius: 5px;
text-align: center;
font-weight: bold;
font-size: 14px;
box-shadow: 0 9px 9px 1px rgba(204,204,204,0.5);
}
.explore h2{
margin-top: 50px;
font-weight: bold;
line-height: 50px;
}
.explore a{
margin-bottom: 50px;
}

/*--------review--------*/

.review{
margin: 100px 0;
}
.carousel-item img{
width: 150px;
border-radius: 50%;
}
.carousel-item{
text-align: center;
height: 430px;
}
.carousel-caption{
z-index: -1 !important;
box-shadow: 0 0 15px 1px rgba(166,163,223,0.5);
border-radius: 5px;
margin-bottom: 50px;
}
.carousel-caption h6{

CMR Institute of Technology Page No:19


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

margin-top: 55px;
font-weight: bold;
color: #000 !important;
}
.carousel-caption small{
margin-top: 10px;
margin-bottom: 50px;
display: block;
color: #000 !important;
}
.carousel-caption p{
text-align: center;
padding: 0 50px;
font-size: 15px;
color: #808080 !important;
}
.carousel-indicators li{
background-color: #6900d1 !important;
}

@media only screen and (max-width: 800px){


.carousel-item
{
height: 520px;
}
.carousel-caption{
margin: 0 10px 50px 10px;
left: 0 !important;
right: 0 !important;
}
}

/*----------footer-------*/

.footer{
background: #6900d1;
padding-top: 5px;
}
.footer h2{
color: #fff;
font-weight: 600;
margin: 70px 0;
}
.footer input{
width: 60%;
background: transparent;
outline: none;
border: 0;
border-bottom: 1px solid #fff;
padding: 10px;
color: #fff;
margin-bottom: 30px;

CMR Institute of Technology Page No:20


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

text-align: center;
}
::placeholder{
color: #efefef;
font-size: 13px;
}
.footer button{
padding: 6px;
width: 180px;
margin: auto;
display: block;
color: #fff;
border: 1px solid #fff;
font-size: 20px;
background: transparent;
}
.footer small{
font-size: 14px;
padding: 70px;
padding-bottom: 20px;
color: #fff;
display: block;
}

Output:

CMR Institute of Technology Page No:21


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Viva Questions:

1. What is bootstrap grid system ?

Ans: Bootstrap's grid system allows up to 12 columns across the page.

If you do not want to use all 12 column individually, you can group the columns together to create wider columns:

Bootstrap's grid system is responsive, and the columns will re-arrange depending on the screen size: On a big screen it
might look better with the content organized in three columns, but on a small screen it would be better if the content
items were stacked on top of each other.

2.Could you explain how to use the dropdown plug-in in bootstrap ?

 Ans: Wrap the child elements inside a .dropdown class.


 We can use either a button or an anchor tag for toggling. For toggling we need to use the .dropdown-
toggle class and add data-bs-toggle=”dropdown” element to the parent class.
 For making the dropdown menu items use the .dropdown-menu class. Use .dropdown-item class with
each item names.

3.Name some CSS style components ?

Ans: CSS selectors are used to "find" (or select) the HTML elements you want to style.

We can divide CSS selectors into five categories:

 Simple selectors (select elements based on name, id, class)


 Combinator selectors (select elements based on a specific relationship between them)
 Pseudo-class selectors (select elements based on a certain state)
 Pseudo-elements selectors (select and style a part of an element)
 Attribute selectors (select elements based on an attribute or attribute value)

4.What is image map in HTML5 ?

Ans:
An image map is an image with clickable areas. The required name attribute of the <map> element is
associated with the <img>'s usemap attribute and creates a relationship between the image and the map. The <map>
element contains a number of <area> elements, that defines the clickable areas in the image map.

5. What is <Div> tag ?

The <div> tag defines a division or a section in an HTML document. The <div> tag is used as a container
for HTML elements - which is then styled with CSS or manipulated with JavaScript. The <div> tag is easily styled by
using the class or id attribute.

6.What is SVG stands for ?

CMR Institute of Technology Page No:22


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

SVG stands for Scalable Vector Graphics. SVG defines vector-based graphics in XML format. SVG graphics are
scalable, and do not lose any quality if they are zoomed or resized. SVG is supported by all major browsers.

3.Write a java script code to validate user registration and login form.
app.js:
const form = document.querySelector('#create-account-form');
const usernameInput = document.querySelector('#username');
const emailInput = document.querySelector('#email');
const passwordInput = document.querySelector('#password');
const confirmPasswordInput = document.querySelector('#confirm-password');

form.addEventListener('submit', (event)=>{

validateForm();
console.log(isFormValid());
if(isFormValid()==true){
form.submit();
}else {
event.preventDefault();
}

});

function isFormValid(){
const inputContainers = form.querySelectorAll('.input-group');
let result = true;
inputContainers.forEach((container)=>{
if(container.classList.contains('error')){
result = false;
}
});
return result;
}

function validateForm() {
//USERNAME
if(usernameInput.value.trim()==''){
setError(usernameInput, 'Name can not be empty');
}else if(usernameInput.value.trim().length <5 || usernameInput.value.trim().length
> 15){
setError(usernameInput, 'Name must be min 5 and max 15 charecters');
}else {
setSuccess(usernameInput);
}
//EMAIL
if(emailInput.value.trim()==''){
setError(emailInput, 'Provide email address');
}else if(isEmailValid(emailInput.value)){
setSuccess(emailInput);
}else{

CMR Institute of Technology Page No:23


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

setError(emailInput, 'Provide valid email address');


}

//PASSWORD
if(passwordInput.value.trim()==''){
setError(passwordInput, 'Password can not be empty');
}else if(passwordInput.value.trim().length <6 || passwordInput.value.trim().length
>20){
setError(passwordInput, 'Password min 6 max 20 charecters');
}else {
setSuccess(passwordInput);
}
//CONFIRM PASSWORD
if(confirmPasswordInput.value.trim()==''){
setError(confirmPasswordInput, 'Password can not be empty');
}else if(confirmPasswordInput.value !== passwordInput.value){
setError(confirmPasswordInput, 'Password does not match');
}else {
setSuccess(confirmPasswordInput);
}
}

function setError(element, errorMessage) {


const parent = element.parentElement;
if(parent.classList.contains('success')){
parent.classList.remove('success');
}
parent.classList.add('error');
const paragraph = parent.querySelector('p');
paragraph.textContent = errorMessage;
}

function setSuccess(element){
const parent = element.parentElement;
if(parent.classList.contains('error')){
parent.classList.remove('error');
}
parent.classList.add('success');
}

function isEmailValid(email){
const reg =/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()
[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

return reg.test(email);
}

Index.html:
<!DOCTYPE html>
<html lang="en">
<head>,

CMR Institute of Technology Page No:24


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FORM VALIDATION</title>
<link rel="stylesheet" href="style.css">
<script src="https://kit.fontawesome.com/2bbac3a66c.js" crossorigin="anonymous"
></script>
</head>
<body>
<form id="create-account-form" action="result.html" method="GET">

<div class="title">
<h2>Create Account</h2>
</div>
<!-- USERNAME -->
<div class="input-group">
<label for="username">Name</label>
<input type="text" id="username" placeholder="Name" name="username">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<p>Error Message</p>
</div>
<!-- EMAIL -->
<div class="input-group">
<label for="email">Email</label>
<input type="email" id="email" placeholder="Email" name="email">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<p>Error Message</p>
</div>
<!-- PASSWORD -->
<div class="input-group">
<label for="password">Password</label>
<input type="password" id="password" placeholder="Password"
name="password">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<p>Error Message</p>
</div>
<!-- CONFIRM PASSWORD -->
<div class="input-group">
<label for="confirm-password">Confirm Password</label>
<input type="password" id="confirm-password" placeholder="Password"
name="confirmpassword">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<p>Error Message</p>
</div>

<button type="submit" class="btn">Submit</button>


</form>

CMR Institute of Technology Page No:25


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

<!-- JAVASCRIPT -->


<script src="app.js"></script>
</body>
</html>

<!--

<i class="fas fa-check-circle"></i>


<i class="fas fa-exclamation-circle"></i>

-->
result.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Result</title>
</head>
<body>
<p id="paragraph"></p>
<a href="index.html">go to index page</a>

<script src="result.js"></script>
</body>
</html>

result.js:
const paragraph = document.querySelector('#paragraph');

const params = new URLSearchParams(window.location.search);

params.forEach((value, key)=>{
paragraph.append(`${key} = ${value}`);
paragraph.append(document.createElement('br'));
});

style.css: * {
padding:0;
margin:0;
box-sizing: border-box;
}

body {
display:flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: chocolate;

CMR Institute of Technology Page No:26


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

#create-account-form {
width:400px;
padding:20px;
text-transform: uppercase;
background-color: #fff;
}

.title {
margin-bottom: 20px;
}

.input-group {
margin:20px 0;
position:relative;
}

.input-group label {
display:inline-block;
margin-bottom: 5px;
}

.input-group input {
display:block;
width:100%;
padding:10px;
}

.error input {
border:3px red solid;
}

.success input {
border:3px green solid;
}

.input-group i {
position:absolute;
right:10px;
top:35px;
visibility: hidden;
}

.success i.fa-check-circle{
visibility: visible;
color:green;
}

.error i.fa-exclamation-circle {
visibility: visible;
color:red;

CMR Institute of Technology Page No:27


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

.input-group p {
font-size: 15px;
color:red;
visibility: hidden;
}

.error p {
visibility: visible;
}

.btn {
width:100%;
padding:10px;
font-size: 20px;
background-color: chocolate;
color:#fff;
text-transform: uppercase;
border:none;
}

Output:

CMR Institute of Technology Page No:28


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

VIVA QUESTIONS:

1.List some of the advantages of JavaScript.?


Ans: Some of the advantages of JavaScript are:

o Server interaction is less


o Feedback to the visitors is immediate
o Interactivity is high
o Interfaces are richer

2. List some of the disadvantages of JavaScript.


Ans: Some of the disadvantages of JavaScript are:

o No support for multithreading


o No support for multiprocessing
o Reading and writing of files is not allowed
o No support for networking applications

CMR Institute of Technology Page No:29


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

3. Define a named function in JavaScript.

The function which has named at the time of definition is called a named function. For example

1. function msg()
2. {
3. document.writeln("Named Function");
4. }
5. msg();
4. Define anonymous function ?

It is a function that has no name. These functions are declared dynamically at runtime using the function operator
instead of the function declaration. The function operator is more flexible than a function declaration. It can be easily
used in the place of an expression

5. What is the difference between JavaScript and JScript?

Netscape provided the JavaScript language. Microsoft changed the name and called it JScript to avoid the trademark
issue. In other words, you can say JScript is the same as JavaScript, but Microsoft provides it.

4.Write a jquery code to show website slider.

CMR Institute of Technology Page No:30


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Image Slider</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<style type="text/css">
body {
background-color: black;
}

.slider {
margin-top: 10%;
}

.slider img {
display: none;
}

.slider img.active {
display: block;
border: 2px solid white;
}

CMR Institute of Technology Page No:31


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

</style>
</head>
<body>
<center>
<div class="slider">
<img src="images/1.jpg">
<img src="images/2.jpg">
<img src="images/3.jpg">
<img src="images/4.jpg" class="active">
<img src="images/5.jpg">
</div>

<br><br>
<input type="button" class="btn btn-primary" onclick="changeSlide('previous')"
value="Previous">
<input type="button" class="btn btn-success" onclick="slideshow(this)"
value="Start Slideshow">
<input type="button" class="btn btn-primary" onclick="changeSlide('next')"
value="Next">
</center>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"
integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
crossorigin="anonymous"></script>
<script type="text/javascript">
var stopSlideshow = false;

function slideshow(caller) {
var status = $(caller).attr('value');

if (status.indexOf('Start') > -1) {


stopSlideshow = false;
$(caller).attr('value', 'Stop Slideshow');
$(caller).addClass('btn-danger').removeClass('btn-success');
} else {
stopSlideshow = true;
$(caller).attr('value', 'Start Slideshow');
$(caller).addClass('btn-success').removeClass('btn-danger');
}

var interval = setInterval(function () {


if (!stopSlideshow)
changeSlide('next');
else
clearInterval(interval);
}, 2000);
}

function changeSlide(direction) {
var currentImg = $('.active');
var nextImg = currentImg.next();
var previousImg = currentImg.prev();

CMR Institute of Technology Page No:32


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

if (direction == 'next') {
if (nextImg.length)
nextImg.addClass('active');
else
$('.slider img').first().addClass('active');
} else {
if (previousImg.length)
previousImg.addClass('active');
else
$('.slider img').last().addClass('active');
}

currentImg.removeClass('active');
}
</script>
</body>
</html>

Output:

CMR Institute of Technology Page No:33


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Viva Questions:

1. What are the jquery methods used to provide effects ?

Ans:
jQuery offers a variety of methods to create visual effects, including showing, hiding, sliding, fading, and custom
animations. These methods are part of jQuery's effects module and can be easily integrated into web projects to
enhance user interface interactions Here's a brief overview of some of the most commonly used
jQuery methods for effects

1..show() and .hide()


2..toggle()
3..fadeIn() and .fadeOut()
4..fadeToggle()
5..fadeTo()
6..slideDown(), .slideUp(), and .slideToggle()

2. Why do we use jQuery ?

Ans:
jQuery, introduced in 2006, quickly became a staple in web development due to its simplicity, ease of use, and cross-
browser compatibility. While modern web development has seen the rise of various frameworks and libraries, jQuery
still holds relevance
for several reasons:

CMR Institute of Technology Page No:34


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

1.Simplifies JavaScript
2.Cross-browser Compatibility
3.Rich Feature Set
4.Large Community and Plugin Ecosystem
5.Ease of Learning
6.Integration with Other Libraries and Frameworks
7.Performance Optimization

3. What are the basic selectors in jQuery ?

Ans: jQuery selectors allow you to select and manipulate HTML elements. They are based on
the CSS selectors, so if you're familiar with CSS, you'll find jQuery selectors quite intuitive.
Here are some of the basic selectors in jQuery:

1.Element Selector
2.ID Selector
3.Class Selector
4.Universal Selector
5.Multiple Selector
6.Attribute Selector
7.Descendant Selector
8.Child Selector
9.Next Adjacent Selector
10.Next Siblings Selector

4. what is the use of jQuery load method ?

Ans: The jQuery .load() method is a powerful and convenient way to load data from a server
and place the returned HTML into the matched element(s) without needing to manually
perform AJAX calls and DOM manipulation. It simplifies the process of fetching and displaying
content asynchronously, making it particularly useful for updating parts of a webpage with
new content without reloading the entire page.

5. Is it possible that jQuery HTML work for both HTML and XML document ?

Ans:

Yes, jQuery's .html() method primarily works with HTML documents, designed to get or set the HTML content of an
element. However, it can also manipulate elements within XML documents loaded in the browser, with some caveats
and limitations.

In HTML Documents
The .html() method is straightforward and powerful when used with HTML documents. It can retrieve the HTML
content of the first element in the set of matched elements or set the HTML content of every matched element. For
example:

To get the HTML content: var content = $('#element').html();

CMR Institute of Technology Page No:35


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

To set the HTML content: $('#element').html('<p>New content</p>');


This method is widely used for dynamically manipulating the DOM by inserting,
replacing, or removing elements and content.

5. Create a simple Node.js server with routes login, register, profile and logout.

Server.js:
// Importing express module
const express = require('express');
const app = express();

app.use(express.json());

Server.js:

// Import express for creating API's endpoints


const express = require("express");
const path = require('path');
const fs = require("fs");
const users = require("./database.json");
var database;

CMR Institute of Technology Page No:36


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

var token="wrong key";

// Read database.json file


fs.readFile("database.json", function(err, data) {

// Check for errors


if (err) throw err;

// Converting to JSON
database = JSON.parse(data);
});

// Import jwt for API's endpoints authentication


const jwt = require("jsonwebtoken");

// Creates an Express application, initiate


// express top level function
const app = express();

// A port for serving API's


const port = 3000;

// Allow json data


app.use(express.json());

app.get('/',
CMR Institute of Technology Page No:37
II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

(req, res) => {


res.sendFile(__dirname + '/login.html');
});

// Login route
app.post("/auth", (req, res) => {
// Get the name to the json body data

const name = req.body.name;


console.log(name);

// Get the password to the json body data


const password = req.body.password;
console.log(password)
// Make two variable for further use
let isPresent = false;
let isPresentIndex = null;

// iterate a loop to the data items and


// check what data are matched.
for (let i = 0; i < database.length; i++) {

// If data name are matched so check


// the password are correct or not
if (database[i].name === name
&& database[i].password === password) {

CMR Institute of Technology Page No:38


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

// If both are correct so make


// isPresent variable true
isPresent = true;

// And store the data index


isPresentIndex = i;

// Break the loop after matching


successfully
break;
}
}

// If isPresent is true, then create a


// token and pass to the response
if (isPresent) {

// The jwt.sign method are used


// to create token
const token =
jwt.sign(database[isPresentIndex], "secret");

// Pass the data or token in response


res.json({
login: true,

CMR Institute of Technology Page No:39


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

token: token,
data: database[isPresentIndex],
});
} else {

// If isPresent is false return the error


res.json({
login: false,
token: token,
error: "please check name and
password.",
});
}
});

// Verify route
app.post("/verifyToken", (req, res) => {

// Get token value to the json body


const token = req.body.token;

// If the token is present


if (token) {

// Verify the token using jwt.verify method


const decode = jwt.verify(token, "secret");

CMR Institute of Technology Page No:40


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

// Return response with decode data


res.json({
login: true,
data: decode,
});
} else {

// Return response with error


res.json({
login: false,
data: "error",
});
}
});

app.post('/login',(req, res) => {


res.redirect("/login")
});

// Listen the server


app.listen(port, () => {
console.log(`Server is running :
http://localhost:${port}/`);
});

CMR Institute of Technology Page No:41


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Database.json:

[{"name":"jyotsna","work":"Assistant
Professor","password":"abc"},
{"name":"Sarvesh","work":"Assistant
Professor","password":"ambala"},
{"name":"ram","work":"Assistant
Professor","password":"priya"}
]

Login.html:

<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<style>
h2{
display: none;
}
</style>
<script src="https://code.jquery.com/jquery-
3.6.0.min.js"></script>
<script>
const form=$("#loginForm");
$(document).ready(function() {

CMR Institute of Technology Page No:42


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

$("#loginForm").submit((event)=>{
event.preventDefault();
var name = $("#username").val();
var password=$("#pwd").val();
//generateToken by making a service call to /auth
with post
$.ajax({
url:"/auth",
type:"POST",
contentType:"application/json",
dataType:"json",
data: JSON.stringify({
name: name,
password: password
}),
success: function(data) {
var tokenData=data;
if(tokenData.login==true){
if(verifyLogin(tokenData.token))
{
$("#verified").show();
$("#not-verified").hide();
alert("JWT Token:
"+tokenData.token);
}
}

CMR Institute of Technology Page No:43


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

else{
$("#verified").hide();
$("#not-verified").show();
alert("Authentication Failed");
}
},
error: function(data ){
console.log("Something went wrong");
}
});
});
});

function verifyLogin(token)
{
let result=true;
//verifyToken by making a service call to
/verifyToken with get
$.ajax({
url:"/verifyToken",
type:"POST",
contentType:"application/json",
dataType:"json",
data: JSON.stringify({
token: token,
}),

CMR Institute of Technology Page No:44


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

success: function(data) {
if(data.login==true)
{
result=true;
}
else
{
result=false;
}
},
error: function(data ){
console.log("Wrong Token, Not
Authenticated.");
}
});
return result;
}
</script>
<body>
<h2>Sign In</h2>
<form id="loginForm">
<label for="username">Username:</label><br>
<input type="text" id="username"
name="username"><br>
<label for="pwd">Password:</label><br>
<input type="password" id="pwd"

CMR Institute of Technology Page No:45


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

name="pwd"><br><br>
<input type="submit" value="Submit">
</form>
<h2 id="verified">You are a verified user </h2>
<h2 id="not-verified">You are not a verified user
</h2>
</body>
</html>
Output:

CMR Institute of Technology Page No:46


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Note:
Step 1) Download Postman. Go to https://www.postman.com/downloads/ and choose your
desired platform among Mac, Windows or Linux. ...
Step 2) Click on Run. ...
Step 3) Postman Installation Start. ...
Step 4) Signup for Postman Account. ...
Step 5) Click on Save My Preferences. ...
Step 6) Congratulation!

CMR Institute of Technology Page No:47


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Viva Questions:
1. Why use jwt authentication ?

Ans: JWT, or JSON Web Token, is a compact, URL-safe means of representing claims to be transferred between
two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web
Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to
be digitally signed or integrity-protected with a Message Authentication Code (MAC) and/or encrypted. JWT
authentication has become popular for several reasons, particularly in web and mobile applications.

2. why do we need the JSON Web Token (JWT) in the modern web?

Ans:In the landscape of modern web development, JSON Web Tokens (JWT) fulfill critical needs for secure,
flexible, and scalable user authentication and information exchange.

Their significance is magnified by the evolution of web applications towards more complex architectures,
including microservices and single-page applications (SPAs), as well as the increasing emphasis on mobile and
API-first development. Here's why

JWTs are particularly valuable in the modern web:


1.Decentralized Authentication and Authorization
2. Stateless Sessions for Scalability
3. Cross-Platform and Cross-Domain Communication
4. Microservices Architecture
5. Single Sign-On (SSO)
6. Enhanced Security Features
7. Simplicity and Speed
8. Compliance and Best Practices

3. How it works for angular JS authentication ?

Ans: AngularJS, a client-side JavaScript framework by Google, has been widely used for building dynamic
single-page applications (SPAs). When it comes to implementing authentication in AngularJS applications, JSON
Web Tokens (JWT) provide a robust and flexible method to secure the application while maintaining a user-
friendly experience.

4. Give the necessary steps for JSON web tokens?


Ans: Implementing JSON Web Tokens (JWT) for authentication and authorization in a web application involves
several key steps, from user authentication to token validation. Below is a generalized process that outlines the
necessary steps to effectively use JWTs:
1. User Authentication
2. Token Generation

CMR Institute of Technology Page No:48


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

3. Token Transmission
4. Token Usage
5. Token Validation
6. Access Control
7. Token Expiry and Renewal

5.What do you mean by typescript ?

Ans: TypeScript is an open-source programming language developed and maintained by Microsoft. It is a superset of
JavaScript, meaning that any valid JavaScript code is also valid TypeScript code. TypeScript extends JavaScript by
adding static types to the language.
1.Static Type-Checking
2.Type Inference
3.Advanced Types
4.IDE Support
5.Compatibility with JavaScript
6.Compilation to JavaScript

6. Write middleware to validate JWT and redirect to profile.

CMR Institute of Technology Page No:49


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Database. Json:

[{"name":"jyotsna","work":"Assistant
Professor","password":"abc"},
{"name":"Sarvesh","work":"Assistant
Professor","password":"ambala"},
{"name":"ram","work":"Assistant
Professor","password":"priya"}
{"name":"Lakshmi","work":"Asst
Prof","password":"Cmrit@123"}
]

Server.js:
// Import express for creating API's endpoints
const express = require("express");
const path = require('path');
const fs = require("fs");
const users = require("./database.json");
var database;
var token;

// Import jwt for API's endpoints authentication


const jwt = require("jsonwebtoken");

// Creates an Express application, initiate


// express top level function

CMR Institute of Technology Page No:50


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

const app = express();

// A port for serving API's


const port = 3000;

// Allow json data


app.use(express.json());

app.get('/',
(req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/welcome',
(req, res) => {
res.sendFile(__dirname + '/welcome.html');
});
app.get('/signup',
(req, res) => {
res.sendFile(__dirname + '/signup.html');
});
app.get('/login',
(req, res) => {
res.sendFile(__dirname + '/login.html');
});

// SignUp route

CMR Institute of Technology Page No:51


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

app.post("/register", (req, res) => {


// Get the name to the json body data
const name = req.body.name;

// Get the password to the json body data


const password = req.body.password;

// Get the profession to the json body data


const work = req.body.work;

// Make two variable for further use


let isPresent = false;
let isPresentIndex = null;

// Read database.json file


fs.readFile("database.json", function(err, data)
{

// Check for errors


if (err) throw err;

// Converting to JSON
database = JSON.parse(data);

// iterate a loop to the data items and


// check what data are matched.

CMR Institute of Technology Page No:52


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

for (let i = 0; i < database.length; i++) {

// If data name are matched so check


// the password are correct or not
if (database[i].name === name
&& database[i].password === password) {

// If both are correct so make


// isPresent variable true
isPresent = true;

// And store the data index


isPresentIndex = i;

// Break the loop after matching


successfully
break;
}
}

// If isPresent is true, then create a


// token and pass to the response
if (isPresent) {
res.json({
signup: false,
token: null,

CMR Institute of Technology Page No:53


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

error: "Already registered",


});
} else {
let user =
{
name: name,
work: work,
password: password,
token: token
};
users.push(user);
fs.writeFile(
"database.json",
JSON.stringify(users),
err => {
// Checking for errors
if (err) throw err;

// Success
res.json({
signup: true,
token: "generated",
data: "Successfully Registered",
});
console.log("Done writing");
});

CMR Institute of Technology Page No:54


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

}
});
});

// Login route
app.post("/auth", (req, res) => {
// Get the name to the json body data

const name = req.body.name;


console.log(name);

// Get the password to the json body data


const password = req.body.password;
console.log(password)
// Make two variable for further use
let isPresent = false;
let isPresentIndex = null;

// Read database.json file


fs.readFile("database.json", function(err, data)
{

// Check for errors


if (err) throw err;

// Converting to JSON
CMR Institute of Technology Page No:55
II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

database = JSON.parse(data);

// iterate a loop to the data items and


// check what data are matched.
for (let i = 0; i < database.length; i++) {

// If data name are matched so check


// the password are correct or not
if (database[i].name === name
&& database[i].password === password) {

// If both are correct so make


// isPresent variable true
isPresent = true;

// And store the data index


isPresentIndex = i;

// Break the loop after matching


successfully
break;
}
}

// If isPresent is true, then create a


// token and pass to the response

CMR Institute of Technology Page No:56


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

if (isPresent) {

// The jwt.sign method are used


// to create token
const token =
jwt.sign(database[isPresentIndex], "secret");

// Pass the data or token in response


res.json({
login: true,
token: token,
data: database[isPresentIndex],
});
} else {

// If isPresent is false return the error


res.json({
login: false,
error: "please check name and
password.",
});
}
});
});

// Verify route

CMR Institute of Technology Page No:57


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

app.post("/verifyToken", (req, res) => {

// Get token value to the json body


const token = req.body.token;

// If the token is present


if (token) {

// Verify the token using jwt.verify method


const decode = jwt.verify(token, "secret");

// Return response with decode data


res.json({
login: true,
data: decode,
});
} else {

// Return response with error


res.json({
login: false,
data: "error",
});
}
});

CMR Institute of Technology Page No:58


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

app.post('/welcome',(req, res) => {


res.redirect("/welcome")
});
app.post('/login',(req, res) => {
res.redirect("/login")
});
app.post('/signup',(req, res) => {
res.redirect("/signup")
});

// Listen the server


app.listen(port, () => {
console.log(`Server is running :
http://localhost:${port}/`);
});

Login.html:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<script src="https://code.jquery.com/jquery-
3.6.0.min.js"></script>
<script>
const form=$("#loginForm");
$(document).ready(function() {
$("#loginForm").submit((event)=>{

CMR Institute of Technology Page No:59


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

event.preventDefault();
var name = $("#username").val();
var password=$("#pwd").val();
//generateToken by making a service
call to /auth with post
$.ajax({
url:"/auth",
type:"POST",
contentType:"application/json",
dataType:"json",
data: JSON.stringify({
name: name,
password: password}),
success: function(data) {
var tokenData=data;
if(tokenData.login==true){

localStorage.setItem("username",tokenData.data.name)
;

localStorage.setItem("job",tokenData.data.work);

if(verifyLogin(tokenData.token))
{

window.location.href="/welcome";

CMR Institute of Technology Page No:60


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

}
else{
alert("Authentication
Failed");
}
}
},
error: function(data ){
console.log("Something went
wrong");
}
});
});
});

function verifyLogin(token)
{
let result=true;
//verifyToken by making a service call to
/verifyToken with get
$.ajax({
url:"/verifyToken",
type:"POST",
contentType:"application/json",
dataType:"json",
data: JSON.stringify({

CMR Institute of Technology Page No:61


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

token: token}),
success: function(data) {
if(data.login==true)
{
result=true;
}
else
{
result=false;
}
},
error: function(data ){
console.log("Wrong Token, Not
Authenticated.");
}
});
return result;
}
</script>
<body>
<center>
<h2>Sign In</h2>
<form id="loginForm">
<label
for="username">Username:</label><br>
<input type="text" id="username"

CMR Institute of Technology Page No:62


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

name="username"><br>
<label for="pwd">Password:</label><br>
<input type="password" id="pwd"
name="pwd"><br><br>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>

Index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-
width, initial-scale=1.0">
<title>YOGO Solutions</title>
</head>
<body>
<center>
<a href="/signup">Click here to SignUp</a>
<br>
<a href="/login">Click here to Login</a>
<br>
</center>

CMR Institute of Technology Page No:63


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

</body>
</html>
Sign Up.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-
width, initial-scale=1.0">
<title>SignUp</title>
<script src="https://code.jquery.com/jquery-
3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#signUpForm').submit(()=>{
event.preventDefault();
var name = $("#username").val();
var password=$("#pwd").val();
var work=$("#work").val();
//generateToken by making a service call to
/register with post
$.ajax({
url:"/register",
type:"POST",
contentType:"application/json",
dataType:"json",

CMR Institute of Technology Page No:64


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

data: JSON.stringify({
name: name,
password: password,
work:work
}),
success: function(data) {
var tokenData=data;
if(tokenData.signup==false){
$("#msg").html('<h6>You are Already
registered with us!!!</h6><br><a id="login-link"
href="\login">Login</a>');
}
else{
$("#msg").html('<h6>Successfully
registered with us!!!</h6><br><a id="login-link"
href="\login">Login</a>');
$("login-link").show();
//window.location.href="/login";
}
},
error: function(data ){
console.log("Something went wrong");

}
});
});

CMR Institute of Technology Page No:65


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

});
</script>
</head>
<body>
<center>
<h2>SignUp</h2>
<form id="signUpForm">
<label
for="username">Username:</label><br>
<input type="text" id="username"
name="username"><br>
<label
for="work">Profession:</label><br>
<input type="text" id="work"
name="work"><br>
<label for="pwd">Password:</label><br>
<input type="password" id="pwd"
name="pwd"><br><br>
<input type="submit" value="Submit">
</form>
<div id="msg"></div>
</center>
</body>
</html>
Welcome.html:
<!DOCTYPE html>

CMR Institute of Technology Page No:66


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-
width, initial-scale=1.0">
<title>Welcome Page</title>
<script src="https://code.jquery.com/jquery-
3.6.0.min.js"></script>
<script>
var user=localStorage.getItem("username");
var job=localStorage.getItem("job");
$(document).ready(function(){
$("#user").append(user);
$("#job").append(job);
});
</script>
</head>
<body>
<center>
<h2>WELCOME TO YOGO SOLUTIONS</h2>
<hr>
<div style="border-style:solid; border-
color: blue; width:400px; height:200px">
<h4 id="user">USER: </h4><br>
<h4 id="job">PROFESSION: </h4>
</div>

CMR Institute of Technology Page No:67


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

</center>
</body>
</html>
Output:

CMR Institute of Technology Page No:68


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Viva Questions:

1.What is the meant by bearer token ?

Ans: Security: Bearer Tokens should be protected from unauthorized access as they grant access rights to whoever
holds them. Transport over secure channels (HTTPS) is mandatory to prevent interception.
Statelessness: Bearer Tokens are self-contained, carrying all the necessary information for authentication. This means
the server does not need to keep a session state, making this method scalable and suitable for distributed systems.
Usage: They are typically included in the HTTP request's Authorization header with the prefix "Bearer", followed by
the token itself. For example: Authorization: Bearer <token>.
Expiration: Bearer Tokens usually have a limited lifetime, after which they expire and can no longer be used. A new
token needs to be obtained after expiration.

2.How the consensus problem is useful in web application ?

Ans: The consensus problem, while traditionally discussed in the context of distributed systems and databases, has

CMR Institute of Technology Page No:69


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

significant implications for web applications, particularly those that operate on a distributed architecture or require
high availability, fault tolerance, and data consistency across multiple nodes or services.

1. Data Consistency
2. High Availability and Fault Tolerance
3. Session Management
4. Distributed Locking
5. Blockchain and Cryptocurrencies
6. Configuration Management

3.What is the use of JWT digital signature ?

Ans:

The digital signature in a JSON Web Token (JWT) serves as a crucial mechanism for ensuring the integrity and
authenticity of the token. JWTs are composed of three parts: the header, the payload, and the signature, and they are
used in various authentication and authorization processes in web applications and APIs. Here’s why the digital
signature is essential:

1.Ensuring Integrity
2.Authenticating the Source
3.Securing Communications
4.Non-repudiation

4. RS256 Vs HS256 ?

Ans: RS256 (RSA Signature with SHA-256) is an asymmetric algorithm, and it uses a public/private key pair: the
identity provider has a private (secret) key used to generate the signature, and the consumer of the JWT gets a public
key to validate the signature. Since the public key, as opposed to the private key, doesn't need to be kept secured, most
identity providers make it easily available for consumers to obtain and use (usually through a metadata URL).

HS256 (HMAC with SHA-256), on the other hand, involves a combination of a hashing function and one (secret) key
that is shared between the two parties used to generate the hash that will serve as the signature. Since the same key is
used both to generate the signature and to validate it, care must be taken to ensure that the key is not compromised.

5.Why backend is prominent in any web application ?

Ans: The backend of a web application plays a crucial role in its functionality, performance, security, and scalability.
It's where the core logic of the application resides,
handling data processing, storage, and communication between the frontend and various other services or databases.
Here's why the backend is prominent and indispensable in any web application:

1. Data Management and Storage


2. Business Logic Implementation
3. Authentication and Authorization
4. Integration with Other Services

CMR Institute of Technology Page No:70


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

5. Performance and Scaling


6. Data Security and Compliance
7. Serving Dynamic Content
8. Asynchronous Processing

7. Write MongoDB model for the user and query to fetch user, validate and register.

Home.js:

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


import { useNavigate } from "react-router-dom";
import toast from "react-hot-toast";
import axios from "axios";
function Home() {
const [userInfo, setUserInfo] = useState(null);

CMR Institute of Technology Page No:71


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

const navigate = useNavigate();


const getData = async () => {
toast.loading();
try {
const token = localStorage.getItem("user");
const response = await
axios.get("/api/user/get-user-info", {
headers: {
Authorization: `Bearer ${token}`,
},
});
toast.dismiss();
if (response.data.success) {
setUserInfo(response.data.data);
} else {
localStorage.removeItem("user");
navigate("/login");
toast.error("Something went wrong");
}
} catch (error) {
localStorage.removeItem("user");
navigate("/login");
toast.error("Something went wrong");
}
};

CMR Institute of Technology Page No:72


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

useEffect(() => {
if (userInfo == null) {
getData();
}
}, [userInfo]);

return (
userInfo !== null && (
<div className="flex items-center justify-
center min-h-screen">
<div className="flex flex-col space-y-5">
<h1 className="text-5xl font-semibold
text-primary">
{userInfo?.name}
</h1>
<h1 className="text-5xl font-semibold
text-primary">
{userInfo?.email}
</h1>
<button
className="border border-primary px-10
py-2 text-primary max-w-max"
onClick={() => {
localStorage.clear();
navigate("/login");
}}

CMR Institute of Technology Page No:73


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

>
LOGOUT
</button>
</div>
</div>
)
);
}

export default Home;

Login.js:
import React, { useState } from "react";
import toast from "react-hot-toast";
import { Link, useNavigate } from "react-router-
dom";
import axios from "axios";
function Login() {
const [showForgotPassword, setShowForgotPassword]
= useState(false);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const navigate = useNavigate();
const loginUser = async () => {
const userObj = {
password,
email,

CMR Institute of Technology Page No:74


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

};
try {
toast.loading("Loading...");
const response = await
axios.post("/api/auth/login", userObj);
toast.dismiss();
if (response.data.success) {
toast.success(response.data.message);
localStorage.setItem("user",
response.data.data);
navigate("/");
} else {
toast.error(response.data.message);
}
} catch (error) {
toast.dismiss();
toast.error("Something went wrong");
}
};

const sendResetPasswordLink = async () => {


try {
toast.loading("");
const response = await
axios.post("/api/auth/send-password-reset-link", {
email,

CMR Institute of Technology Page No:75


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

});
toast.dismiss();
if (response.data.success) {
toast.success(response.data.message);
setShowForgotPassword(false);
} else {
toast.error(response.data.message);
}
} catch (error) {
toast.dismiss();
toast.error("Something went wrong");
}
};

return (
<div className="flex justify-center items-center
h-screen">
{!showForgotPassword && (
<div className="w-[400px] flex space-y-5
flex-col shadow-lg border border-gray-300">
<h1 className="font-semibold text-2xl
text-white bg-primary p-5 rounded-b-full text-
center">
Good to see you again
</h1>

CMR Institute of Technology Page No:76


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

<div className="flex flex-col space-y-5 p-


5">
<input
type="text"
className="py-1 px-3 border-2 border-
secondary focus:outline-none w-full"
placeholder="email"
onChange={(e) =>
setEmail(e.target.value)}
value={email}
/>
<input
type="password"
className="py-1 px-3 border-2 border-
secondary focus:outline-none w-full"
placeholder="password"
onChange={(e) =>
setPassword(e.target.value)}
value={password}
/>
<button
className="py-1 px-5 text-white bg-
primary"
onClick={loginUser}
>
LOGIN

CMR Institute of Technology Page No:77


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

</button>
<div className="flex justify-between
items-end">
<div className="flex space-x-10">
<Link className="underline text-
primary" to="/register">
Click Here To Register
</Link>
<h1
className="underline text-primary
cursor-pointer"
onClick={() =>
setShowForgotPassword(true)}
>
Forgot Password
</h1>
</div>
</div>
</div>
</div>
)}

{showForgotPassword && (
<div className="flex flex-col space-y-5 w-
[400px]">
<h1 className="font-semibold text-3xl

CMR Institute of Technology Page No:78


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

text-primary">
Enter your email
</h1>
<input
type="text"
className="py-1 px-3 border-2 border-
secondary focus:outline-none w-full"
placeholder="email"
onChange={(e) =>
setEmail(e.target.value)}
value={email}
/>
<div className="flex flex-col justify-
between items-end space-y-5">
<button
className="py-1 px-5 text-white bg-
primary w-full"
onClick={sendResetPasswordLink}
>
SEND RESET PASSWORD LINK
</button>
<h1
onClick={() =>
setShowForgotPassword(false)}
className="cursor-pointer underline
text-md text-primary text-left"

CMR Institute of Technology Page No:79


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

>
Click Here To Login
</h1>
</div>
</div>
)}
</div>
);
}

export default Login;

Register.js:
import React, { useState } from "react";
import toast from "react-hot-toast";
import { Link } from "react-router-dom";
import axios from "axios";
function Register() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] =
useState("");

const registerUser = async () => {


if (password === confirmPassword) {
const userObj = {

CMR Institute of Technology Page No:80


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

name,
password,
email,
confirmPassword,
};
try {
toast.loading("Loading...");
const response = await
axios.post("/api/auth/register", userObj);
toast.dismiss();
if (response.data.success) {
toast.success(response.data.message);
} else {
toast.error(response.data.message);
}
} catch (error) {
toast.dismiss();
toast.error("Something went wrong");
}
} else {
toast.error("Passwords Not Matched");
}
};

return (

CMR Institute of Technology Page No:81


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

<div className="flex justify-center items-center


h-screen space-x-40">
<div className="w-[400px] flex space-y-5 flex-
col shadow-lg border border-gray-300">
<h1 className="font-semibold text-2xl text-
white bg-primary p-5 rounded-b-full text-center">
Welcome TO SHEY
</h1>

<div className="flex flex-col space-y-5 p-


5">
<input
type="text"
className="py-1 px-3 border-2 border-
secondary focus:outline-none w-full"
placeholder="name"
onChange={(e) =>
setName(e.target.value)}
value={name}
/>
<input
type="text"
className="py-1 px-3 border-2 border-
secondary focus:outline-none w-full"
placeholder="email"
onChange={(e) =>

CMR Institute of Technology Page No:82


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

setEmail(e.target.value)}
value={email}
/>
<input
type="password"
className="py-1 px-3 border-2 border-
secondary focus:outline-none w-full"
placeholder="password"
onChange={(e) =>
setPassword(e.target.value)}
value={password}
/>
<input
type="password"
className="py-1 px-3 border-2 border-
secondary focus:outline-none w-full"
placeholder="confirm password"
onChange={(e) =>
setConfirmPassword(e.target.value)}
value={confirmPassword}
/>

<div className="flex justify-between


items-end">
<Link className="underline text-primary"
to="/login">

CMR Institute of Technology Page No:83


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Click Here To Login


</Link>

<button
className="py-1 px-5 text-white bg-
primary"
onClick={registerUser}
>
REGISTER
</button>
</div>
</div>
</div>
</div>
);
}

export default Register;

ResetPassword.js:
import React, { useState } from "react";
import toast from "react-hot-toast";
import { Link, useNavigate } from "react-router-
dom";
import { useParams } from "react-router-dom";
import axios from "axios";

CMR Institute of Technology Page No:84


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

function ResetPassword() {
const [password, setPassword] = useState("");
const [confirmpassword, setConfirmPassword] =
useState("");
const params = useParams();
const navigate = useNavigate();
const resetPassword = async () => {
try {
toast.loading();
const response = await
axios.post("/api/auth/reset-password", {
password,
token: params.token,
});
if (response.data.success) {
toast.success(response.data.message);
navigate("/login");
} else {
toast.error("Expired or Invalid Link");
}
toast.dismiss();
} catch (error) {
toast.dismiss();
toast.error("Something went wrong");
}
};

CMR Institute of Technology Page No:85


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

return (
<div className="flex justify-center items-center
h-screen">
<div className="w-[400px] flex space-y-5 flex-
col p-5 shadow-lg border border-gray-300">
<h1 className="font-semibold text-3xl text-
primary">
CHANGE YOUR PASSWORD
</h1>

<input
type="password"
className="py-1 px-3 border-2 border-
secondary focus:outline-none w-full"
placeholder="password"
onChange={(e) =>
setPassword(e.target.value)}
value={password}
/>

<input
type="password"
className="py-1 px-3 border-2 border-
secondary focus:outline-none w-full"
placeholder="confirm password"

CMR Institute of Technology Page No:86


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

onChange={(e) =>
setConfirmPassword(e.target.value)}
value={confirmpassword}
/>

<div className="flex justify-between items-


end">
<button
className="py-1 px-5 text-white bg-
primary"
onClick={resetPassword}
>
RESET PASSWORD
</button>
</div>
</div>
</div>
);
}

export default ResetPassword;

VerifyEmail.js:

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


import { useParams } from "react-router-dom";

CMR Institute of Technology Page No:87


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

import { toast } from "react-hot-toast";


import axios from "axios";
function VerifyEmail() {
const [emailVerified, setEmailVerified] =
useState("");
const params = useParams();

const verifyToken = async () => {


try {
toast.loading();
const response = await
axios.post("/api/auth/verifyemail", {
token: params.token,
});
if (response.data.success) {
setEmailVerified("true");
} else {
setEmailVerified("false");
}
toast.dismiss();
} catch (error) {
toast.dismiss();
setEmailVerified("false");
}
};

CMR Institute of Technology Page No:88


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

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

return (
<div className="flex min-h-screen p-5 justify-
center items-center">
{emailVerified == "" && (
<h1 className="text-primary text-4xl">
Please wait we are verifying your email
</h1>
)}

{emailVerified == "true" && (


<h1 className="text-primary text-4xl">
Your email verified successfully
</h1>
)}

{emailVerified == "false" && (


<h1 className="text-primary text-
4xl">Invalid or Expired Token</h1>
)}
</div>
);
}

CMR Institute of Technology Page No:89


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

export default VerifyEmail;

App.js:

import { BrowserRouter, Routes, Route, Navigate }


from "react-router-dom";
import Home from "./pages/Home";
import Login from "./pages/Login";
import Register from "./pages/Register";
import { Toaster } from "react-hot-toast";
import VerifyEmail from "./pages/VerifyEmail";
import ResetPassword from "./pages/ResetPassword";
function App() {
return (
<BrowserRouter>
<Toaster position="top-center"
reverseOrder={false} />
<Routes>
<Route
path="/"
element={
<ProtectedRoutes>
<Home />
</ProtectedRoutes>
}

CMR Institute of Technology Page No:90


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

/>
<Route
path="/login"
element={
<PublicRoutes>
<Login />
</PublicRoutes>
}
/>
<Route
path="/register"
element={
<PublicRoutes>
<Register />
</PublicRoutes>
}
/>
<Route
path="/verifyemail/:token"
element={
<PublicRoutes>
<VerifyEmail />
</PublicRoutes>
}
/>

CMR Institute of Technology Page No:91


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

<Route
path="/resetpassword/:token"
element={
<PublicRoutes>
<ResetPassword />
</PublicRoutes>
}
/>
</Routes>
</BrowserRouter>
);
}

export function ProtectedRoutes({ children }) {


const user = localStorage.getItem("user");
if (user !== "" && user) {
return children;
} else {
return <Navigate to="/login" />;
}
}

export function PublicRoutes({ children }) {


const user = localStorage.getItem("user");
if (user !== "" && user) {
return <Navigate to="/" />;

CMR Institute of Technology Page No:92


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

} else {
return children;
}
}

export default App;

index.js:

import React from 'react';


import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root =
ReactDOM.createRoot(document.getElementById('root'))
;
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

// If you want to start measuring performance in


your app, pass a function

CMR Institute of Technology Page No:93


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

// to log results (for example:


reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more:
https://bit.ly/CRA-vitals
reportWebVitals();

mongodbConnection.js:

const mongoose = require("mongoose");

mongoose.connect(process.env.MONGO_URL,
{ useNewUrlParser: true });

const connection = mongoose.connection;

connection.on("error", (error) => {


console.log(error);
});

connection.on("connected", () => {
console.log("Mongo DB connection successfull");
});

authMiddleWare.js:

CMR Institute of Technology Page No:94


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

const jwt = require("jsonwebtoken");

module.exports = (req, res, next) => {


const token = req.headers.authorization.split(" ")
[1];
const user = jwt.verify(token, "SHEY");
if (user) {
req.body.user = user;
next();
} else {
res.status(500).send({ message: "Invalid or
Expired Token" });
}
};
tokenModel.js:

const mongoose = require("mongoose");

const tokenSchema = new mongoose.Schema(


{
userid: {
type: String,
required: true,
},
token: {
type: String,

CMR Institute of Technology Page No:95


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

required: true,
},
},
{ timestamps: true }
);

const tokenModel = mongoose.model("tokens",


tokenSchema);

module.exports = tokenModel;

userModel.js:

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({


name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,

CMR Institute of Technology Page No:96


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

required: true,
},
isVerifed: {
type: Boolean,
default: false,
},
});

const userModel = mongoose.model("users",


userSchema);

module.exports = userModel;

auth.js:

const express = require("express");


const router = express.Router();
const User = require("../models/userModel");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const sendEmail = require("../utils/sendEmail");
const Token = require("../models/tokenModel");
router.post("/register", async (req, res) => {
try {
const existingUser = await User.findOne({ email:
req.body.email });

CMR Institute of Technology Page No:97


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

if (existingUser)
return res
.status(200)
.send({ success: false, message: "User
Already Registered" });

const password = req.body.password;


const salt = await bcrypt.genSalt(10);
const hashedPassword = await
bcrypt.hash(password, salt);
req.body.password = hashedPassword;
const newuser = new User(req.body);
const result = await newuser.save();
await sendEmail(result, "verifyemail");
res.status(200).send({
success: true,
message: "Registration successfull , Please
verify your email",
});
} catch (error) {
console.log(error);
res.status(400).send(error);
}
});

router.post("/login", async (req, res) => {

CMR Institute of Technology Page No:98


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

try {
const user = await User.findOne({
email: req.body.email,
});
if (user) {
const passwordsMached = await bcrypt.compare(
req.body.password,
user.password
);
if (passwordsMached) {
if (user.isVerifed) {
const dataToBeSentToFrontend = {
_id: user._id,
email: user.email,
name: user.name,
};
const token =
jwt.sign(dataToBeSentToFrontend, "SHEY", {
expiresIn: 60 * 60,
});
res.status(200).send({
success: true,
message: "User Login Successfull",
data: token,
});
} else {

CMR Institute of Technology Page No:99


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

res
.status(200)
.send({ success: false, message: "Email
not verified" });
}
} else
res.status(200).send({ success: false,
message: "Incorrect Password" });
} else {
res
.status(200)
.send({ success: false, message: "User Does
Not Exists", data: null });
}
} catch (error) {
res.status(400).send(error);
}
});

router.post("/send-password-reset-link", async (req,


res) => {
try {
const result = await User.findOne({ email:
req.body.email });
await sendEmail(result, "resetpassword");
res.send({

CMR Institute of Technology Page No:100


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

success: true,
message: "Password reset link sent to your
email successfully",
});
} catch (error) {
res.status(500).send(error);
}
});

router.post("/reset-password", async (req, res) => {


try {

const tokenData = await Token.findOne({ token:


req.body.token });
if (tokenData) {
const password = req.body.password;
const salt = await bcrypt.genSalt(10);
const hashedPassword = await
bcrypt.hash(password, salt);
await User.findOneAndUpdate({ _id:
tokenData.userid, password: hashedPassword });
await Token.findOneAndDelete({ token:
req.body.token });
res.send({ success: true, message: "Password
reset successfull" });
} else {

CMR Institute of Technology Page No:101


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

res.send({ success: false, message: "Invalid


token" });
}
} catch (error) {
res.status(500).send(error);
}
});

router.post("/verifyemail", async (req, res) => {


try {

const tokenData = await Token.findOne({ token:


req.body.token });
if (tokenData) {
await User.findOneAndUpdate({ _id:
tokenData.userid, isVerifed: true });
await Token.findOneAndDelete({ token:
req.body.token });
res.send({ success: true, message: "Email
Verified Successlly" });
} else {
res.send({ success: false, message: "Invalid
token" });
}
} catch (error) {
res.status(500).send(error);

CMR Institute of Technology Page No:102


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

}
});

module.exports = router;

user.js:

const express = require("express");


const router = express.Router();
const authmiddleWare =
require("../middlewares/authMiddleWare");

router.get("/get-user-info", authmiddleWare, async


(req, res) => {
try {
res.send({ success: true, data:
req.body.user });
} catch (error) {
res.status(400).send(error);
}
});

module.exports = router;

server.js:

CMR Institute of Technology Page No:103


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

const express = require("express");


require("dotenv").config();
const app = express();
app.use(express.json());
const authRoute = require("./routes/auth");
const userRoute = require("./routes/user");
const mongodbConnection =
require("./config/mongodbConnection");
const port = 5000;
app.use("/api/auth", authRoute);
app.use("/api/user", userRoute);
app.get("/", (req, res) => res.send("Hello
World!"));
app.listen(port, () => console.log(`Node JS Server
Running On Port ${port}!`));

Output:

CMR Institute of Technology Page No:104


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

CMR Institute of Technology Page No:105


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

CMR Institute of Technology Page No:106


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

VIVA QUESTIONS:

1.What type of DBMS is MongoDB?

Ans: MongoDB is a NoSQL database management system (DBMS) known for its scalability, flexibility, and
performance. Unlike traditional relational database management systems (RDBMS) that store data in tables with rows
and columns, MongoDB uses a document-oriented approach to store data.

Key Characteristics of MongoDB:


1.Document-Oriented Storage
2.Schema-less
3.Scalability
4.Querying and Indexing
5.Aggregation Framework
6.NoSQL Database

2.Difference between MySQL and MongoDB ?


Ans: MySQL: Uses a relational model where data is stored in tables with rows and columns. Relations among data are
defined through foreign keys. It follows a strict schema, requiring the structure of the data (tables and columns) to be
defined beforehand.

CMR Institute of Technology Page No:107


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

MongoDB: Utilizes a document model, storing data in BSON (binary-encoded JSON) documents. This allows for
more flexible data structures, with the ability to store nested data. MongoDB is schema-less, meaning the documents
in a collection can have different structures.

MySQL: Offers strong consistency and supports ACID (Atomicity, Consistency, Isolation, Durability) transactions,
ensuring reliable processing of transactions even in complex operations involving multiple tables.
MongoDB: Initially favored eventual consistency to provide high availability and partition tolerance but has since
introduced support for ACID transactions since version 4.0. However, its transaction support is generally considered
more limited compared to traditional RDBMS.

3.Which technologies can support multiple databases ?

Ans: 1.ORM (Object-Relational Mapping) Libraries ORM libraries allow developers to interact with a database using
an object-oriented paradigm, abstracting the underlying database interactions.

Hibernate (Java): A robust ORM framework that supports a wide range of databases including MySQL, PostgreSQL,
Oracle, Microsoft SQL Server, and more.
Entity Framework (C#/.NET): Microsoft's ORM for .NET applications, supporting SQL Server, MySQL, PostgreSQL,
SQLite, and more through various providers.
Sequelize (Node.js): A promise-based ORM for Node.js, supporting PostgreSQL, MySQL, MariaDB, SQLite, and
Microsoft SQL Server.
Django ORM (Python): Part of the Django web framework, it supports PostgreSQL, MySQL,SQLite, and Oracle
Database.
SQLAlchemy (Python): A SQL toolkit and ORM that provides full power and flexibility of SQL to Python
applications, supporting numerous databases including PostgreSQLMySQL, and SQLite.
4.How do we perform the join operations in MongoDB ?
Ans: In MongoDB, join operations are primarily performed using the $lookup stage in an aggregation pipeline.
MongoDB's aggregation framework is a powerful tool for data transformation and analysis, allowing for complex
queries and operations on the data, including the capability to perform operations similar to SQL joins. The $lookup
stage lets you pull documents from another collection (table in SQL terminology) into your
aggregation query, effectively performing a "join" between two collections.

5.Explain indexes in MongoDB?

Ans: Indexes in MongoDB are special data structures that store a small portion of the collection's data in an easy-to-
traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field as
specified in the index. They are used to improve the speed of search operations within MongoDB collections by
allowing the database engine to efficiently find documents matching the query criteria without scanning every
document in a collection.

1.Single Field Index


2.Compound Index
3.Multikey Index
4.Text Index
5.Hashed Index

CMR Institute of Technology Page No:108


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

6.Geospatial Index
7.Unique Index
8.Partial Index

8. Design a Single Page Application with different menu items using Angular.

Index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>SpaApp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/
Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>
<body>
<app-root></app-root>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous"></script>
</body>
</html>

CMR Institute of Technology Page No:109


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

main.js:
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));

app.component.spec.ts:

import { TestBed } from '@angular/core/testing';


import { AppComponent } from './app.component';

describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent],
}).compileComponents();
});

it('should create the app', () => {


const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});

it(`should have the 'spa-app' title`, () => {


const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('spa-app');
});

it('should render title', () => {


const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Hello, spa-app');
});
});

app.component.ts:
import { Component } from '@angular/core';
import { RouterModule, RouterOutlet } from '@angular/router';
import { HeaderComponent } from './header/header.component';

@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet,HeaderComponent,RouterModule],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})

CMR Institute of Technology Page No:110


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

export class AppComponent {


title = 'spa-app';
}

app.config.ts:
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {


providers: [provideRouter(routes)]
};

home.component.html:
<section class="container mt-5 text-center ">
<h1>Welcome to SPA REST API Demo</h1>

</section>

home.component.spec.ts:
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { HomeComponent } from './home.component';

describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HomeComponent]
})
.compileComponents();

fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {


expect(component).toBeTruthy();
});
});

home.component.ts:
import { Component } from '@angular/core';
import { RouterModule } from '@angular/router';

@Component({
selector: 'app-home',
standalone: true,

CMR Institute of Technology Page No:111


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

imports: [RouterModule],
templateUrl: './home.component.html',
styleUrl: './home.component.css'
})
export class HomeComponent {

Output:

VIVA QUESTIONS:

1.What is Angular ?

Ans: 1.What is angular ?


Angular is a popular open-source web application framework maintained by Google and a community of individual
developers and corporations. It is written in TypeScript and is designed to make the development and testing of single-
page applications (SPAs) easier and more efficient. Angular provides a comprehensive solution for building client-
side applications with optimized practices and tools to develop, build, and
test your code.

Key Features of Angular:

1.Component-Based Architecture
2.Data Binding
3.Dependency Injection (DI)
4.Directives
5.Routing
6.Forms

CMR Institute of Technology Page No:112


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

7.HTTP Client
8.Angular CLI
9.RxJS

2.What are the main advantages of angular ?

Ans:Angular, a platform and framework for building single-page client applications using HTML and TypeScript,
offers several advantages that make it a popular choice among developers for creating dynamic and complex web
applications. Here are some of the main advantages of using Angular:

1. Component-Based Architecture
2. Two-Way Data Binding
3. Comprehensive Framework
4. Modularity and Lazy Loading
5. Dependency Injection
6. TypeScript
7. Tooling
8. Testing
9. Community and Ecosystem
10. Cross-Platform Development

3.is angular two single-page application?


Ans:
Yes, Angular 2 and later versions (commonly referred to simply as "Angular") are designed to support the
development of single-page applications (SPAs). Single-page applications are web applications that load a single
HTML page and dynamically update that page as the user interacts with the app, rather than loading entire new pages
from the server. This approach provides a more fluid, desktop-like user experience.

1.Component-Based Architecture
2.Client-Side Routing
3.Data Binding and Reactive Programming
4.Services and Dependency Injection

4.What is type script ?


Ans:TypeScript is an open-source programming language developed and maintained by Microsoft. It is a superset of
JavaScript, which means that any valid JavaScript code is also valid TypeScript code. TypeScript adds optional static
typing to JavaScript, among other features, to improve the language's scalability and developer experience for building
large and complex applications.

Key Features of TypeScript:


1.Static Type Checking
2.Type Inference
3.Advanced Types
4.Compatibility with JavaScript
5.Tooling Support

CMR Institute of Technology Page No:113


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

6.Transpilation to JavaScript

5.What is dependency injection in angular ?


Ans:Dependency Injection (DI) is a core concept in Angular that allows a class to receive its dependencies from an
external source rather than creating them itself. This design pattern is integral to the way Angular applications are
structured and provides a way to increase their efficiency, modularity, and testability.

How Dependency Injection Works in Angular:


Providers: In Angular, dependencies are services or objects that a class needs to perform its function. These
dependencies are defined as providers in Angular's DI system. A provider tells the DI system how to obtain or create a
dependency.
Injectors: The DI system has injectors that are responsible for instantiating dependencies and injecting them into
classes. Angular creates and manages an injector for you automatically when the application starts.
Injection Tokens: These are used to register and look up dependencies in the injector. Typically, the token is the class
type of the dependency itself.
Decorators: Angular utilizes decorators to mark a class as a dependency and to inject dependencies into components,
services, or other classes. The most common decorator for injection is @Injectable(), which marks a class as available
to an injector for instantiation.

9.Fetch user details from server using REST API and show in profile menu using Angular.

CMR Institute of Technology Page No:114


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

profile.component.css:
.avatar{
width: 150px;
height: 150px;
border-radius: 200px;
}

th,td{
padding: 10px;
}

profile.component.html:
<div class="card shadow-sm w-50 mt-5 p-2 mx-auto " *ngIf="user">
<img class="avatar d-block mx-auto"
src="https://cdn-icons-png.freepik.com/512/5733/5733290.png" alt="Icon" />
<h2 class="text-center">Hi, {{ user.name }}</h2>
<table class="table table-bordered mt-3">
<tr>
<th>Username</th>
<td>{{user.username}}</td>
</tr>
<tr>
<th>Email</th>
<td>{{user.email}}</td>
</tr>
<tr>
<th>Phone</th>
<td>{{ user.phone }}</td>
</tr>
<tr>
<th>City</th>
<td>{{ user.address?.city }}</td>
</tr>
<tr>
<th>ZIP Code</th>
<td>{{ user.address?.zipcode }}</td>
</tr>
<tr>
<th>Website</th>
<td>{{ user.website }}</td>
</tr>
</table>

</div>

profile.component.spec.ts:
import { ComponentFixture, TestBed } from '@angular/core/testing';

CMR Institute of Technology Page No:115


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

import { ProfileComponent } from './profile.component';

describe('ProfileComponent', () => {
let component: ProfileComponent;
let fixture: ComponentFixture<ProfileComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ProfileComponent]
})
.compileComponents();

fixture = TestBed.createComponent(ProfileComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {


expect(component).toBeTruthy();
});
});

profile.component.ts:
import { CommonModule } from '@angular/common';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-profile',
standalone: true,
imports: [HttpClientModule,CommonModule],
templateUrl: './profile.component.html',
styleUrl: './profile.component.css'
})
export class ProfileComponent implements OnInit {
user:any;
constructor(private http: HttpClient) {}

ngOnInit(): void {
this.http.get('https://jsonplaceholder.typicode.com/users/1').subscribe((data:
any) => {
console.log(data);
this.user = data;
});
}

CMR Institute of Technology Page No:116


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Output:

VIVA QUESTIONS:

1.Elaborate about URL?

Ans: A URL (Uniform Resource Locator) is a reference or address used to access resources on the internet. It provides
a way to retrieve information from across the web, acting as a means to locate and specify the path to a particular piece
of data or resource, such as a webpage, an image, a video file, or any other content accessible through the web. URLs
are a fundamental part of the World Wide Web (WWW) and are standardized by the Internet Engineering Task Force
(IETF).

2.What is the concept of statelessness in REST?


Ans: The concept of statelessness in REST (Representational State Transfer) is a foundational principle that dictates
that each request from a client to a server must contain all the information the server needs to understand and fulfill the
request. This means that the server does not store any state (or context) about the client session on the server side.
Instead, it is the client's responsibility to keep track of the application state and send it with each request when
necessary.

Examples of Statelessness

CMR Institute of Technology Page No:117


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

In a RESTful API, authentication data, such as tokens, are sent with each request rather than relying on a session
stored on the server. This way, the server can authenticate the user without knowing anything about the user's previous
interactions.

A RESTful web service might require clients to include page number and size in request parameters to fetch a specific
subset of resources, rather than keeping track of the client's pagination state between requests.

3.List out the HTTP methods?


Ans:HTTP (Hypertext Transfer Protocol) defines a set of request methods to indicate the desired action to be
performed for a given resource. These methods are sometimes referred to as HTTP verbs. Each has its own specific
purpose and semantics in terms of interaction with web resources. Here's a list of the primary HTTP methods and their
intended use:

1.GET
2.POST
3.PUT
4.DELETE
5.PATCH
6.HEAD
7.OPTIONS
8.CONNECT
9.TRACE

4.What is reactive programming and how does it relate to angular ?

Ans: Advantages of Using Reactive Programming in Angular: Improved Performance: Reactive programming can
improve the performance of Angular applications, as it enables efficient handling of events, asynchronous data, and
state management.

Modularity and Maintainability: By treating data as streams and using functional programming techniques,
applications become more modular and easier to maintain and test.

Scalability: The asynchronous nature of reactive programming fits well with scalable, real-time applications, allowing
Angular applications to easily scale and adapt to complex user interfaces and data flows.

5.What are the differences between REST and AJAX ?

REST (Representational State Transfer) and AJAX (Asynchronous JavaScript and XML) are both concepts used in
web development, but they serve different purposes and operate at different layers of application design.
Understanding the differences between them is crucial for effectively designing and implementing web applications.

REST
Conceptual Framework: REST is an architectural style or set of guidelines for designing networked applications. It is
not tied to any specific protocol, but it is most commonly used over HTTP.

CMR Institute of Technology Page No:118


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Statelessness: A core principle of REST is that each request from a client to a server must contain all the information
the server needs to fulfill the request (statelessness). The server does not retain session state, which helps in scaling the
application.

Resource-Based: In REST, everything is considered a resource, and each resource is accessed via a common interface
(URLs) and manipulated using standard HTTP methods (GET, POST, PUT, DELETE, etc.).

Use of Standard HTTP Methods: RESTful services use standard HTTP methods explicitly for their intended purposes,
e.g., retrieving data with GET, submitting data to be processed to a resource using POST, updating a resource using
PUT, or removing a resource with DELETE.

Data Format Agnostic: While RESTful services can use AJAX under the hood to fetch data asynchronously, they are
agnostic about the format of the data returned. JSON and XML are commonly used, but HTML, plain text, and other
formats can also be RESTfully served.

AJAX
Technology: AJAX is a technique for creating fast and dynamic web pages. It allows web pages to update
asynchronously by exchanging small amounts of data with the server behind the scenes. This means it's possible to
update parts of a web page without reloading the whole page.

Uses JavaScript: AJAX is not a technology in itself, but a term that refers to the use of a group of technologies
together, including HTML or XHTML, Cascading Style Sheets (CSS), JavaScript, the Document Object Model
(DOM), XML, XSLT, and the XMLHttpRequest object. It heavily relies on JavaScript to make asynchronous calls to
the server.

Focused on Client-Side: AJAX is primarily a client-side concept focusing on improving the user experience by
making asynchronous calls from the web page to the server to fetch data or submit data without reloading the web
page.

Partial Page Updates: The key advantage of AJAX is its ability to make partial page updates. AJAX can send data to,
and retrieve data from, a server asynchronously without interfering with the display and behavior of the existing page.

Not Data Format Agnostic: AJAX typically deals with XML or JSON as the format for transferring data between the
client and server, with JSON being the more popular format in modern web applications due to its lightweight nature
and ease of use with JavaScript.

10. Design Single Page Application with different menu items using react.

CMR Institute of Technology Page No:119


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

navbar.css:

.container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 2rem 6rem;
}

.links {
flex: 1;
display: flex;
justify-content: flex-start;
align-items: center;
}

.links-logo {
margin-right: 2rem;
CMR Institute of Technology Page No:120
II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

.links-logo img {
width: 100px;
height: 40px;
}

.links-wrapper {
display: flex;
flex-direction: row;
margin: auto 0;
}

.nav-button {
display: flex;
justify-content: flex-end;
align-items: center;
}

.links-wrapper p a,
.nav-button p,
.nav-menu-wrapper p a {
color: #333333;
font-weight: 500;
font-size: 18px;
line-height: 25px;

CMR Institute of Technology Page No:121


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

text-transform: capitalize;
margin: 0 1rem;
cursor: pointer;
text-decoration: none;
}

.nav-menu-wrapper p a {
color: #fff;
}

.nav-button button,
.nav-menu-wrapper button {
padding: 0.5rem 2rem;
color: #fff;
background-color: #3aafa9;
font-weight: 500;
font-size: 18px;
line-height: 25px;
border-radius: 5px;
border: none;
outline: none;
cursor: pointer;
}

.nav-menu {
margin-left: 1rem;

CMR Institute of Technology Page No:122


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

display: none;
position: relative;
}

.nav-menu-wrapper {
display: flex;
justify-content: flex-end;
align-items: flex-end;
flex-direction: column;
text-align: end;
background: #17252a;
padding: 2rem;
position: absolute;
top: 40px;
right: 0;
margin-top: 1rem;
min-width: 210px;
border-radius: 5px;
box-shadow: 0 0 0 5 rgba(0, 0, 0, 0.2);
}

.nav-menu-wrapper p a {
margin: 1rem 0;
text-decoration: none;
}

CMR Institute of Technology Page No:123


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

.nav-menu-wrapper-button {
display: none;
}

@media screen and (max-width: 1050px) {


.links-wrapper {
display: none;
}

.nav-menu {
display: flex;
}
}

@media screen and (max-width: 700px) {


.container {
padding: 2rem 4rem;
}
}

@media screen and (max-width: 550px) {


.container {
padding: 2rem 4rem;
}

.nav-button {

CMR Institute of Technology Page No:124


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

display: none;
}

.nav-menu-wrapper {
top: 20px;
}

.nav-menu-wrapper-button {
display: block;
}
}
NavComponents.js:

import React, { useState } from "react";


import logo from "../assets/logo.png";
import "./navbar.css";
import { RiCloseLine, RiMenu3Line } from "react-
icons/ri";

const Menu = () => (


<>
<p>
<a href="#home">home</a>
</p>
<p>
<a href="#about">about</a>
</p>
CMR Institute of Technology Page No:125
II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

<p>
<a href="#contact">contact</a>
</p>
<p>
<a href="#services">services</a>
</p>
<p>
<a href="#portfolio">profile</a>
</p>
</>
);

const NavComponent = () => {


const [toggleMenu, setToggleMenu] =
useState(false);
return (
<div className="container">
<div className="links">
<div className="links-logo">
<img src={logo} alt="" srcset="" />
</div>
<div className="links-wrapper">
<Menu />
</div>
</div>
<div className="nav-button">

CMR Institute of Technology Page No:126


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

<button type="button">Hire me</button>


</div>
<div className="nav-menu">
{toggleMenu ? (
<RiCloseLine
color="#333333"
size={27}
onClick={() => setToggleMenu(false)}
/>
) : (
<RiMenu3Line
color="#333333"
size={27}
onClick={() => setToggleMenu(true)}
/>
)}
{toggleMenu && (
<div className="nav-menu-wrapper">
<div className="nav-menu-wrapper-links">
<Menu />
<div className="nav-menu-wrapper-
button">
<button type="button">Hire
me</button>
</div>
</div>

CMR Institute of Technology Page No:127


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

</div>
)}
</div>
</div>
);
};

export default NavComponent;

App.css:

.App {
text-align: center;
}

.App-logo {
height: 40vmin;
pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {


.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}

CMR Institute of Technology Page No:128


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}

.App-link {
color: #61dafb;
}

@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

App.js:

CMR Institute of Technology Page No:129


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

import "./App.css";
import NavComponent from
"./components/NavComponent";
import React from "react";

function App() {
return (
<>
<NavComponent />
</>
);
}

export default App;

App test.js:

import { render, screen } from


'@testing-library/react';
import App from './App';

test('renders learn react link', () => {


render(<App />);
const linkElement = screen.getByText(/learn
react/i);
expect(linkElement).toBeInTheDocument();

CMR Institute of Technology Page No:130


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

});

index.css:

body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont,
'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid
Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

code {
font-family: source-code-pro, Menlo, Monaco,
Consolas, 'Courier New',
monospace;
}

index.js:

import React from 'react';


import ReactDOM from 'react-dom/client';
import './index.css';

CMR Institute of Technology Page No:131


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

import App from './App';


import reportWebVitals from './reportWebVitals';

const root =
ReactDOM.createRoot(document.getElementById('root'))
;
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

// If you want to start measuring performance in


your app, pass a function
// to log results (for example:
reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more:
https://bit.ly/CRA-vitals
reportWebVitals();

Output:

CMR Institute of Technology Page No:132


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

VIVA QUESTIONS:

1.How does react work?

Ans: One of the key innovations of React is the Virtual DOM. Instead of directly manipulating the browser's
Document Object Model (DOM), which can be slow, React applications work with a lightweight in-memory
representation of the DOM called the Virtual DOM

React Hooks:

Introduced in React 16.8, hooks allow functional components to use state and other React features without writing a
class. The most commonly used hooks are useState for managing component state and useEffect for performing side
effects in functional components.

2.What are props in react ?


Ans:
<MyComponent myProp="value" />
class MyComponent extends React.Component {
render() {
return <p>{this.props.myProp}</p>;
}
}
function MyComponent(props) {
return <p>{props.myProp}</p>;
}
function MyComponent({ myProp }) {
return <p>{myProp}</p>;
}
function ParentComponent(props) {
return <div>{props.children}</div>;

CMR Institute of Technology Page No:133


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

// Usage
<ParentComponent>
<ChildComponent />
</ParentComponent>
data.map((item) => <Component key={item.id} {...item} />)

3.Difference between VirtualDOM and RealDOM ?

Real DOM
Definition: The Real DOM is the browser’s programming interface for HTML and XML documents. It represents the
page so that programs can change the document structure, style, and content.
Manipulation: Changes to the Real DOM are slow. The Real DOM is stateful; any change in the DOM can cause page
re-renders, which are expensive in terms of performance.
Updates: Direct manipulation or updates to the Real DOM can be inefficient, especially with frequent updates,
because each change directly affects the elements on the web page, leading to potential performance issues.
Operations Cost: Operations on the Real DOM are expensive. The process of re-rendering or repainting the page due
to DOM manipulations can be heavy, especially for complex applications.
Direct Interaction: JavaScript directly manipulates the Real DOM for adding or removing elements, changing content,
etc.

Virtual DOM
Definition: The Virtual DOM is a lightweight copy or abstraction of the Real DOM. It is a concept implemented by
libraries like React to improve web application performance.
Manipulation: Changes to the Virtual DOM are fast. The Virtual DOM can undergo frequent updates without the
performance costs associated with the Real DOM because these changes do not immediately affect the actual DOM on
the web page.
Updates: The Virtual DOM allows for the batching of updates. Instead of updating the Real DOM after every single
change, the Virtual DOM can aggregate several changes and apply them simultaneously in a single update cycle.
Operations Cost: Operations on the Virtual DOM are inexpensive. Since the Virtual DOM is just a lightweight copy,
manipulating it doesn’t have the same performance implications as manipulating the Real DOM.
Reconciliation Algorithm: Libraries that use the Virtual DOM, like React, implement a "diffing" algorithm. This
algorithm compares the current state of the Virtual DOM with the previous state and calculates the most efficient way
to update the Real DOM to match the Virtual DOM. This selective rendering minimizes direct manipulation of
the Real DOM, thereby improving performance.

4. Describe MVC in reference to angular ?

Ans: The Model-View-Controller (MVC) architecture is a design pattern that separates an


application into three interconnected components: the model, the view, and the controller.
This separation helps manage complex applications by dividing them into smaller, more
manageable parts, each responsible for specific aspects of the application. Although Angular
is often associated with a slightly different architectural pattern (Model-View-ViewModel or
MVVM), it still embodies the core principles of MVC in how it structures applications.

5. Define stateful component ?

CMR Institute of Technology Page No:134


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Ans: A stateful component, in the context of web development frameworks such as React,
Angular, or Vue, is a component that maintains its own state. The state of a component is an
object that holds some information that may change over the lifetime of the component.
Stateful components are aware of changes in this information and can react to those changes
by updating the UI accordingly. These components keep track of changes in data that affect
the render output, making them crucial for creating
dynamic and interactive user interfaces.

11.Install Django and setup a virtual environment. Design Web Application with different menu items
using Django.?

It is suggested to have a dedicated virtual environment for each Django project, and one way to manage a
virtual environment is venv, which is included in Python.

The name of the virtual environment is your choice, in this tutorial we will call it myworld.

Type the following in the command prompt, remember to navigate to where you want to create your project:

This will set up a virtual environment, and create a folder named "myworld" with subfolders and files, like
this:

Then you have to activate the environment, by typing this command:

CMR Institute of Technology Page No:135


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Once the environment is activated, you will see this result in the command prompt:

Install Django:
Django is installed using pip, with this command:

Which will give a result that looks like this (at least on my Windows machine):

Check Django Version:

CMR Institute of Technology Page No:136


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

My First Project:
Once you have come up with a suitable name for your Django project, like mine: my_tennis_club, navigate
to where in the file system you want to store the code (in the virtual environment), I will navigate to
the myworld folder, and run this command in the command prompt:

Run the Django Project


Now that you have a Django project, you can run it, and see what it looks like in a
browser.

Navigate to the /my_tennis_club folder and execute this command in the command
prompt:

py manage.py runserver

Which will produce this result:

CMR Institute of Technology Page No:137


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Watching for file changes with StatReloader


Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly
until you apply the migrations for app(s): admin, auth, contenttypes,
sessions.
Run 'python manage.py migrate' to apply them.
October 27, 2022 - 13:03:14
Django version 4.1.2, using settings 'my_tennis_club.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

Open a new browser window and type 127.0.0.1:8000 in the address bar.

VIVA QUESTIONS:

CMR Institute of Technology Page No:138


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

1. How do I create a virtual environment using venv in Python?

Ans: You can create a virtual environment using the following command: python -m venv <environment_name>.
Replace <environment_name> with the desired name for your virtual environment.

2. Do I need to install venv separately?

Ans: No, venv is included in the Python standard library for versions 3.3 and above, so there’s no need to install it
separately.

3. How do I activate a virtual environment?

On Windows, use <environment_name>\Scripts\activate. On Unix or MacOS, use source


<environment_name>/bin/activate.

4. What is Django?

Django is a Full-stack web development framework that facilitates the creation and maintenance of high-quality
Dynamic pages while also encouraging rapid development and a clean, pragmatic style. Django makes it easier to
automate repeated operations, resulting in a more efficient development process with fewer lines of code.
5. How do you create a Django project?
We can create a Django project with the help of the following command
django-admin startproject projectname

Step1: Open command prompt, check version of python

Step2: Install Django Package

CMR Institute of Technology Page No:139


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Step 3: Check the version of Django

Step4: Create a project

Step5: Check the project folder

Step6: Move to the project folder

Step7: run the server


python manage.py runserver

CMR Institute of Technology Page No:140


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Step8:check the application in browser

VIVA QUESTIONS:
1.What is purpose of Django apps ?

Ans: Django apps are modular components within a Django project, designed to perform a specific function or set of
functions. Each Django app encapsulates a set of related features or behaviors, such as handling user authentication,
managing blog posts, or processing payments. The purpose of structuring a Django project into multiple apps
is to promote modularity, reusability, and maintainability of the codebase. Here are the key purposes and benefits of
using Django apps: Modularity, Reusability, Maintainability, Scalability.

2.How does Django manage static files like CSS, JavaScript and images ?

Ans: Handle Static Files:

CMR Institute of Technology Page No:141


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Static files in your project, like stylesheets, JavaScripts, and images, are not handled
automatically by Django when DEBUG = False.

When DEBUG = True, this worked fine, all we had to do was to put them in the static folder
of the application.

When DEBUG = False, static files have to be collected and put in a specified folder before
we can use it.

Collect Static Files:

To collect all necessary static files for your project, start by specifying
a STATIC_ROOT property in the settings.py file.

This specifies a folder where you want to collect your static files.

You can call the folder whatever you like, we will call it productionfiles

3.Difference between Django and react ?

Ans: Django
Type: Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design.
It follows the Model-View-Template (MVT) architectural pattern.
Language: Python.
Scope: Django is a full-stack web framework that provides built-in solutions for backend development, including
ORM (Object-Relational Mapping), authentication, routing, templating, and more. It's designed to help developers
build complex, database-driven websites quickly.
Use Cases: Django is used for developing the server-side (backend) of web applications. It's well-suited for
applications that require a robust database system, complex backend logic, administrative interfaces, and other
backend functionalities.
Execution Environment: Django applications run on a web server and serve dynamic web pages or RESTful APIs that
interact with a database based on client requests.

React
Type: React is an open-source JavaScript library for building user interfaces, maintained by Facebook and the
community. It follows the component-based architecture.
Language: JavaScript (or TypeScript, if preferred).
Scope: React is primarily concerned with the view layer (frontend) of web applications. It allows developers to create
reusable UI components and manage the state of those components efficiently.
Use Cases: React is used for developing the client-side (frontend) of web applications, particularly single-page
applications (SPAs) where dynamic content needs to be updated without reloading the page. It's well-suited for
applications that require a rich, interactive user experience.
Execution Environment: React applications run in the browser (client-side). They can be served by any backend
server, but they execute and render in the web browser.
4.How can you deploy a Django application in a production server?

CMR Institute of Technology Page No:142


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Ans: Deploying a Django application to a production server involves several key steps to ensure that the application is
secure, efficient, and accessible to users. Here’s a general overview of the process:

1.Prepare Your Application for Production


Settings: Separate your development settings from production settings. This includes database configurations, secret
keys, debug settings (set DEBUG = False in production), and allowed hosts (ALLOWED_HOSTS setting).
Static and Media Files: Configure settings for serving static files (STATIC_ROOT, STATIC_URL) and media files
(MEDIA_ROOT, MEDIA_URL).
Database: Migrate your application to use a production-level database like PostgreSQL, MySQL, or another database
supported by Django.
Dependencies: Ensure all dependencies are correctly specified in a requirements.txt file or using a package manager
like Pipenv.

5.What is content delivery Network (CDN)?

Ans: A Content Delivery Network (CDN) is a globally distributed network of proxy servers and their data centers. The
goal of a CDN is to provide high availability and high performance by spatially distributing the service relative to end-
users. Essentially, a CDN serves content to users with high availability and high speed by caching content in multiple
locations around the world and serving the content from the location closest to each user.

12. Fetch user details from server using REST API and show in profile menu using Django

Step1: create an virtual environment

Step2: activate the environment

Step3: install django package

CMR Institute of Technology Page No:143


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Step4: create a project

Step5: install djangorestframework

Step 6: move to project folder

Step 7: create an application

Step 8: open project/settings.py

Add the below

CMR Institute of Technology Page No:144


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

CMR Institute of Technology Page No:145


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Step 9: create app/urls.py and add below code

Step 10: open app/models.py


Add the below code

CMR Institute of Technology Page No:146


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Step 11: open project/urls.py


Add the below code

Step 12: open app/admin.py


Add below code

CMR Institute of Technology Page No:147


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Step 13: migrate the changes

Step 14: migrate the changes

CMR Institute of Technology Page No:148


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Step 15: create a superuser

Step 16: run the server


Step 17: open browser, run http://127.0.0.1:8000/admin

CMR Institute of Technology Page No:149


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

Step 18: login with created super user

Step 19: add users or groups

Step 20: Save

VIVA QUESTIONS:

1.Why should we use Django ?

Ans:

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic
design. It's designed to help developers take applications from concept to completion as quickly as possible.
Here are several reasons why you might choose to use Django for your web development projects:

CMR Institute of Technology Page No:150


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

1.Rapid Development
2.Batteries Included
3.Highly Scalable
4.Security
5.Versatile
6.Vibrant Community
7.Good for SEO
8.Mature Software
9.Excellent Documentation
10.Python

2.Explain the concept of middleware in Django

Ans: Middleware in Django is a framework of hooks into Django's request/response processing. It's a
lightweight, low-level plugin system for globally altering Django's input or output. Each middleware
component is responsible for doing some specific function. For example, Django includes middleware to
handle sessions, CSRF protection, authentication, and more.

Middleware components are executed during the request and response phases of a webpage and can modify
the request before it reaches the view or the response before it's sent to the client. They are processed in
order for requests, and in reverse order for responses, forming a layer around the view function.

Key Functions of Middleware:

Request Processing: Before a request reaches the view, middleware can process the request for various
purposes like security checks, request modifications, user authentication, session management, etc. Response
Processing: After a view has processed the request, middleware can modify the response before it's sent to
the client. This is useful for tasks like setting cookies, caching, content compression, etc.

Exception Handling: Middleware can catch exceptions raised during request processing and offer custom
error handling or logging. View Alteration: Middleware can modify or replace the view that Django
executes. This could be used for purposes like content negotiation or providing fallback views under certain
conditions.

3.What is the significance of proxy models?

Ans: Proxy models in Django are a subclass of a database model that allows you to change the behavior of the model
it inherits from. They are used when you want to modify the behavior of a model, including the default ordering, the
verbose name, the available managers, or the Python-level methods, without creating a new table in the database. This
means that a proxy model shares the same underlying database table as the model it's proxying for.

Key Uses and Significance of Proxy Models:

CMR Institute of Technology Page No:151


II-B.Tech.II- Semester NODE JS/ANGULAR/REACT JS/DJANGO

1.Different Behaviors for the Same Data


2.Custom Managers and Model Methods
3.Admin Interface Customization
4.Maintaining a Single Source of Truth
5.No Migration Required

4. What is difference between Django Vs react and which is the best ?

Ans: The "best" choice depends on the specific needs of your project:

For Backend Development: If you need a robust, secure backend with lots of out-of-the-box functionalities like an
admin interface, user authentication, and database management, Django is an excellent choice. It's particularly strong
for applications where the backend logic and database design are complex.

For Frontend Development: If your project requires a dynamic, responsive user interface with lots of client-side
interactivity, React is the way to go. It's optimized for building fast, interactive UIs where the page does not need to be
reloaded.

5.What is RESTful API?

Ans: A RESTful API (Representational State Transfer Application Programming Interface) is an architectural style for
designing networked applications. It relies on a stateless, client-server, cacheable communications protocol — in
virtually all cases, the HTTP protocol. The idea of REST is to treat all server-side resources as objects that can be
created, read, updated, or deleted (CRUD operations) using HTTP methods (verbs) such as GET, POST, PUT,
DELETE, and PATCH.

CMR Institute of Technology Page No:152

You might also like