Labmanual of NodeJs
Labmanual of NodeJs
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
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
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
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
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.
1.Demonstrate version control in Git and Github using simple html code.
Explain git architecture ,in that what is working directory,staging area,remote repository
D:\ram\fsd\exp1
In cmd by going to your respected directory type git init - it will initiate a empty git repository which acts as a local
Repository
Now open the local working directory in visual studio code /any code editor and create an html file with your desired name
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
1.
To config credentials
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
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
For modified files we can directly commit using the following command
After typing git push origin master it will ask you authentication msg execute as it
asks
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.
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.
Ans:
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.
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.
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">
</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">
<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>
<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>
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;
/*-----------service----------*/
.service{
margin: 75px 0;
}
.title{
text-align: center;
font-weight: bold;
margin-bottom: 30px;
}
.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{
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{
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;
}
/*----------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;
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:
Viva Questions:
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.
Ans: CSS selectors are used to "find" (or select) the HTML elements you want to style.
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.
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.
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{
//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 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>,
<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>
<!--
-->
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');
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;
#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;
.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:
VIVA QUESTIONS:
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
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.
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;
}
</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');
function changeSlide(direction) {
var currentImg = $('.active');
var nextImg = currentImg.next();
var previousImg = currentImg.prev();
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:
Viva Questions:
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
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:
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
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
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:
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:
// Converting to JSON
database = JSON.parse(data);
});
app.get('/',
CMR Institute of Technology Page No:37
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
token: token,
data: database[isPresentIndex],
});
} else {
// Verify route
app.post("/verifyToken", (req, res) => {
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() {
$("#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);
}
}
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,
}),
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"
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:
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!
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
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.
3. Token Transmission
4. Token Usage
5. Token Validation
6. Access Control
7. Token Expiry and Renewal
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
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;
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
// Converting to JSON
database = JSON.parse(data);
// Success
res.json({
signup: true,
token: "generated",
data: "Successfully Registered",
});
console.log("Done writing");
});
}
});
});
// Login route
app.post("/auth", (req, res) => {
// Get the name to the json body data
// 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);
if (isPresent) {
// Verify route
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)=>{
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";
}
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({
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"
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>
</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",
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");
}
});
});
});
</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>
<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>
</center>
</body>
</html>
Output:
Viva Questions:
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.
Ans: The consensus problem, while traditionally discussed in the context of distributed systems and databases, has
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
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.
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:
7. Write MongoDB model for the user and query to fetch user, validate and register.
Home.js:
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");
}}
>
LOGOUT
</button>
</div>
</div>
)
);
}
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,
};
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");
}
};
});
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>
</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
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"
>
Click Here To Login
</h1>
</div>
</div>
)}
</div>
);
}
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("");
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 (
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}
/>
<button
className="py-1 px-5 text-white bg-
primary"
onClick={registerUser}
>
REGISTER
</button>
</div>
</div>
</div>
</div>
);
}
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";
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");
}
};
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"
onChange={(e) =>
setConfirmPassword(e.target.value)}
value={confirmpassword}
/>
VerifyEmail.js:
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>
)}
App.js:
/>
<Route
path="/login"
element={
<PublicRoutes>
<Login />
</PublicRoutes>
}
/>
<Route
path="/register"
element={
<PublicRoutes>
<Register />
</PublicRoutes>
}
/>
<Route
path="/verifyemail/:token"
element={
<PublicRoutes>
<VerifyEmail />
</PublicRoutes>
}
/>
<Route
path="/resetpassword/:token"
element={
<PublicRoutes>
<ResetPassword />
</PublicRoutes>
}
/>
</Routes>
</BrowserRouter>
);
}
} else {
return children;
}
}
index.js:
const root =
ReactDOM.createRoot(document.getElementById('root'))
;
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
mongodbConnection.js:
mongoose.connect(process.env.MONGO_URL,
{ useNewUrlParser: true });
connection.on("connected", () => {
console.log("Mongo DB connection successfull");
});
authMiddleWare.js:
required: true,
},
},
{ timestamps: true }
);
module.exports = tokenModel;
userModel.js:
required: true,
},
isVerifed: {
type: Boolean,
default: false,
},
});
module.exports = userModel;
auth.js:
if (existingUser)
return res
.status(200)
.send({ success: false, message: "User
Already Registered" });
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 {
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);
}
});
success: true,
message: "Password reset link sent to your
email successfully",
});
} catch (error) {
res.status(500).send(error);
}
});
}
});
module.exports = router;
user.js:
module.exports = router;
server.js:
Output:
VIVA QUESTIONS:
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.
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.
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.
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.
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>
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:
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent],
}).compileComponents();
});
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'
})
app.config.ts:
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
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';
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();
});
home.component.ts:
import { Component } from '@angular/core';
import { RouterModule } from '@angular/router';
@Component({
selector: 'app-home',
standalone: true,
imports: [RouterModule],
templateUrl: './home.component.html',
styleUrl: './home.component.css'
})
export class HomeComponent {
Output:
VIVA QUESTIONS:
1.What is Angular ?
1.Component-Based Architecture
2.Data Binding
3.Dependency Injection (DI)
4.Directives
5.Routing
6.Forms
7.HTTP Client
8.Angular CLI
9.RxJS
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
1.Component-Based Architecture
2.Client-Side Routing
3.Data Binding and Reactive Programming
4.Services and Dependency Injection
6.Transpilation to JavaScript
9.Fetch user details from server using REST API and show in profile menu using Angular.
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';
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();
});
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;
});
}
Output:
VIVA QUESTIONS:
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).
Examples of Statelessness
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.
1.GET
2.POST
3.PUT
4.DELETE
5.PATCH
6.HEAD
7.OPTIONS
8.CONNECT
9.TRACE
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.
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.
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.
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;
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;
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;
}
.nav-menu-wrapper-button {
display: none;
}
.nav-menu {
display: flex;
}
}
.nav-button {
display: none;
}
.nav-menu-wrapper {
top: 20px;
}
.nav-menu-wrapper-button {
display: block;
}
}
NavComponents.js:
<p>
<a href="#contact">contact</a>
</p>
<p>
<a href="#services">services</a>
</p>
<p>
<a href="#portfolio">profile</a>
</p>
</>
);
</div>
)}
</div>
</div>
);
};
App.css:
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
.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:
import "./App.css";
import NavComponent from
"./components/NavComponent";
import React from "react";
function App() {
return (
<>
<NavComponent />
</>
);
}
App test.js:
});
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:
const root =
ReactDOM.createRoot(document.getElementById('root'))
;
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Output:
VIVA QUESTIONS:
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.
// Usage
<ParentComponent>
<ChildComponent />
</ParentComponent>
data.map((item) => <Component key={item.id} {...item} />)
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.
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:
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):
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:
Navigate to the /my_tennis_club folder and execute this command in the command
prompt:
py manage.py runserver
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:
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.
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.
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
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 ?
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.
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
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?
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:
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
VIVA QUESTIONS:
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:
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
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.
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.
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.
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.
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.