Node.js Lab Manual for Students
Node.js Lab Manual for Students
JavaProgramming(MallaReddyGroupofInstitutions)
Scantoopenon Studocu
Studocuisnotsponsoredorendorsedbyanycollegeor university
Downloaded by CHAITANYA B
MALLAREDDYENGINEERINGCOLLEGE(Autonomous)
Maisammaguda,Dhulapally(post&viaKompally),Secunderabad-500100.
DepartmentofComputerScienceandEngineeringNOD
EJS/REACTJS/DJANGOLAB
SUBJECTCODE:C0522
[Link]-IIISemester(MR22)
ACADEMICYEAR:2023-24
Downloaded by CHAITANYA B
2023-24
MALLAREDDYENGINEERINGCOLLEGE [Link]
Onwards
(Autonomous)
(MR-22) IIISem
Code:C0514 L T P
Credits:0 NODEJS/REACTJS/DJANGOLAB - - 2
Prerequisites:ObjectOrientedProgrammingthroughJava,HTMLBasics
SoftwareRequirement:JDK,TomcatServer,PHPandWAMPServer
CourseObjectives:
● ToimplementthestaticwebpagesusingHTMLanddoclientside validation
using JavaScript.
● TodesignandworkwithdatabasesusingJava
● Todevelopanend-to-endapplicationusingjavafullstack.
● TointroduceNodeJSimplementationforserver-sideprogramming.
● ToexperimentwithsinglepageapplicationdevelopmentusingReact
Listofexperiments:
1. Buildaresponsivewebapplicationforshoppingcartwithregistration,login,catalog and
cart pages using CSS3 features, flex and grid.
2. MaketheabovewebapplicationresponsivewebapplicationusingBootstrap framework.
3. UseJavaScriptfordoingclient–sidevalidationofthepagesimplementedinexperiment 1
andexperiment 2.
4. Explore the features of ES6 like arrow functions, callbacks, promises, async/await.
[Link] and
display the information in the form of a graph on the web page.
5. Developajavastandaloneapplicationthatconnectswiththedatabase(Oracle/mySql) and
perform the CRUD operation on the database tables.
6. [Link].
7. Designacontrollerwithservletthatprovidestheinteractionwithapplicationdeveloped
inexperiment 1 and the database created in experiment 5.
8. [Link]
sessiontracking mechanism (Cookies, HTTP Session)
9. CreateacustomserverusinghttpmoduleandexploretheothermodulesofNodeJSlike OS,path,
event.
10. DevelopanexpresswebapplicationthatcaninteractwithRESTAPItoperform 14
CRUDoperationsonstudentdata.(UsePostman)
11. FortheaboveapplicationcreateauthorizedendpointsusingJWT(JSONWebToken).
12. Createareactapplicationforthestudentmanagementsystemhavingregistration,login,
contact, about pages and implement routing to navigate through these pages.
13. [Link] and
the display the current and historical weather information using graphical representation
[Link]
14. CreateaTODOapplicationinreactwithnecessarycomponentsanddeployitinto
github.
Downloaded by CHAITANYA B
REFERENCEBOOKS
1. JonDuckett,BeginningHTML,XHTML,CSS,andJavaScript,WroxPublications,2010
2. BryanBasham,KathySierraandBertBates,HeadFirstServletsandJSP,O‟Reilly
Media,2ndEdition, 2008.
3. VasanSubramanian,ProMERNStack,FullStackWebAppDevelopmentwith
Mongo,Express, React, and Node, 2nd Edition, A Pres
CourseOutcomes:
Attheendofthecourse,students willbeableto:
● BuildacustomwebsitewithHTML,CSS,andBootstrapandlittleJavaScript.
● DemonstrateAdvancedfeaturesofJavaScriptandlearnaboutJDBC
● DevelopServer–sideimplementationusingJavatechnologieslike
● Developtheserver–sideimplementationusingNodeJS.
● DesignaSinglePageApplicationusingReact
Downloaded by CHAITANYA B
CO-POMapping
(3/2/1indicatesstrengthofcorrelation)3-Strong,2-Medium,1-Weak
ProgramOutcomes(POs) PSOs
Cos
PO PO2 PO PO PO PO PO PO PO PO PO PSO PSO PSO
1 3 4 5 6 7 8 9 10 12 1 2 3
CO1 2 3 1 2 1
CO2 2 2 2 2
CO3 1 2 1 1
Downloaded by CHAITANYA B
1. Buildaresponsivewebapplicationforshoppingcartwithregistration,login,catal
ogandcartpagesusingCSS3features,flexandgrid.
[Link]
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width,initial-scale=1.0">
<title>Shopify</title>
<linkrel="stylesheet"href="./css/[Link]">
<linkrel="stylesheet"href="./css/[Link]">
<link href="[Link]
family=Poppins:ital,wght@1,900&display=swap" rel="stylesheet">
<scriptsrc="[Link]
[Link]"crossorigin="anonymous"></script>
<linkrel="shortcuticon"href="./assests/Citycons_bag-[Link]"type="image/x-icon">
</head>
<body>
<section>
<nav>
<span><ahref="[Link]"><iclass="fasfa-shopping-bag"></i>shopping
cart</a></span>
<ul>
<li><ahref="[Link]">Home</a></li>
<li><ahref="[Link]">signup</a></li>
<li><ahref="[Link]">login</a></li>
<li><spanonclick="openBucket()"><iclass="fasfa-shopping-cart"></i></span>
<spanclass="items-count"></span>
</li>
</ul>
<spanonclick="openBucket()"class="cart-icon"><iclass="fasfa-shopping-
cart"></i></span>
</nav>
<mainclass="fruits-side">
Downloaded by CHAITANYA B
<span>BuyFruits</span>
<button><ahref="[Link]">ShopNow<iclass="fasfa-caret-
right"></i></a></button>
</main>
<div class="cart">
<header><span><ahref="[Link]"><iclass="fasfa-shopping-bag"></i>
Shopify</a></span><span
class="exit"><iclass="fasfa-times"></i></span></header>
<main>
<ol>
<li>Item-Name</li>
<li>Qty</li>
<li>Total</li>
</ol>
<section>
<ulid="ul"></ul>
</section>
</main>
</div>
</section>
<script>
top_items_count.innerHTML=0;
bottom_items_count.innerHTML= 0;
function openBucket()
{ [Link]="visible";
[Link] = "1";
[Link]="9";
Downloaded by CHAITANYA B
[Link]="all0.5s";
}
[Link]('click',
()=>{ [Link] =
"hidden"; [Link] = "0";
[Link] = "-9";
[Link]="all0.5s";
});
top_items_count.innerHTML = count;
bottom_items_count.innerHTML=count;
</script>
</body>
</html>
Registration:[Link]
<!DOCTYPEhtml>
<htmllang="en">
<html>
<head>
<title>SignUp</title>
<metaname="viewport"content="width=device-width,initial-scale=1.0"/>
<metacharset="utf-8"/>
<linkrel="stylesheet"type="text/css"href="signup_style.css"/>
<link
rel="stylesheet"
href="[Link]
[Link]"
/>
<link href="[Link]
family=Titillium+Web:400,300,600" rel="stylesheet"
type="text/css"
/>
<script src="[Link]
[Link]"></script>
<link rel="stylesheet"
href="[Link]
vp86vTRFVJgpjF9jiIGPEEqYqlDwgyBgEF109VFjmqGmIY/Y4HV4d3Gp2irVfcrp"
crossorigin="anonymous">
</head>
<divclass="login-page">
<div class="form">
Downloaded by CHAITANYA B
<form>
<lottie-player
src="[Link]
lVWDCa8LSqgS/[Link]"
background="transparent"
speed="1"
style="justify-
content:center"loop
autoplay
></lottie-player>
<inputtype="text"placeholder="fullname"/>
<inputtype="text"placeholder="emailaddress"/>
<inputtype="text"placeholder="pickausername"/>
<inputtype="password"id="password"placeholder="setapassword"/>
<iclass="fasfa-eye"onclick="show()"></i>
<br>
<br>
</form>
<formclass="login-form">
<buttontype="button"onclick="[Link]='[Link]'">
SIGN UP
</button>
</form>
</div>
</div>
</body>
<script>
functionshow(){
varpassword=[Link]("password"); var
icon = [Link](".fas");
//==========Checkingtypeofpassword=========== if
([Link] === "password") {
[Link]="text";
}else {
[Link]="password";
}
}
</script>
</html>
</html>
SignIn:[Link]<!DOCTYPEHTML>
<htmllang="en">
<html>
<head>
<title>Login</title>
<metaname="viewport"content="width=device-width,initial-scale=1.0">
<metacharset="utf-8">
Downloaded by CHAITANYA B
<linkrel="stylesheet"type="text/css"href="login_style.css">
<link rel="stylesheet" href="[Link]
awesome/4.7.0/css/[Link]">
<link href='[Link]
family=Titillium+Web:400,300,600'rel='stylesheet' type='text/css'>
<link href='[Link]
family=Titillium+Web:400,300,600'rel='stylesheet' type='text/css'>
<script src="[Link]
[Link]"></script>
<linkrel="stylesheet"href="[Link]
[Link]"integrity="sha384-
vp86vTRFVJgpjF9jiIGPEEqYqlDwgyBgEF109VFjmqGmIY/Y4HV4d3Gp2irVfcrp"
crossorigin="anonymous">
</head>
<divclass="login-page">
<divclass="form">
<form>
<lottie-player
src="[Link]
WDCa8LSqgS/[Link]" background="transparent" speed="1" style="justify-
content: center;" loopautoplay></lottie-player>
<inputtype="text"placeholder="username"/>
<inputtype="password"id="password"placeholder="password"/>
<iclass="fasfa-eye"onclick="show()"></i>
<br>
<br>
<button>LOGIN</button>
<p class="message"></p>
</form>
<formclass="login-form">
<buttontype="button"onclick="[Link]='[Link]'">SIGN
UP</button>
</form>
</div>
</div>
<script>
functionshow(){
varpassword=[Link]("password");
var icon = [Link](".fas")
//==========Checkingtypeofpassword=========== if([Link]
=== "password"){
[Link]="text";
}
else{
Downloaded by CHAITANYA B
[Link]="password";
}
};
</script>
</body>
</html>
Shoppingcart:[Link](shoppingfruits)
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width,initial-scale=1.0">
<title>Fruit-Aisle</title>
<linkrel="stylesheet"href="./css/[Link]">
<linkrel="stylesheet"href="./css/[Link]">
<link href="[Link]
family=Poppins:ital,wght@1,900&display=swap" rel="stylesheet">
<script src="[Link]
crossorigin="anonymous"></script>
<linkrel="shortcuticon"href="./assests/Citycons_bag-[Link]"type="image/x-
icon">
</head>
<body>
<section>
<nav>
<span><ahref="[Link]"><iclass="fasfa-shopping-bag"></i>Shopify shopping
cart</a></span>
<ul>
<li><ahref="[Link]">Home</a></li>
<li><ahref="[Link]">signup</a></li>
<li><ahref="[Link]">login</a></li>
<li><spanonclick="openBucket()"><iclass="fasfa-shopping-
cart"></i></span>
<spanclass="items-count"></span>
</li>
</ul>
<spanonclick="openBucket()"class="cart-icon"><iclass="fasfa-shopping-
cart"></i></span>
Downloaded by CHAITANYA B
</nav>
<main>
<divclass="itemsitem-1"data-item="Apples"data-price="100"></div>
<divclass="itemsitem-2"data-item="Lemons"data-price="200"></div>
<divclass="itemsitem-3"data-item="Strawberries"data-price="300"></div>
<divclass="itemsitem-4"data-item="Bananas"data-price="400"></div>
</main>
<divclass="cart">
<header><span><ahref="[Link]"><iclass="fasfa-shopping-bag"></i>
Shopify</a></span><span
class="exit"><iclass="fasfa-times"></i></span></header>
<main>
<ol>
<li>Item-Name</li>
<li>Qty</li>
<li>Total</li>
</ol>
<section>
<ulid="ul">
</ul>
</section>
</main>
</div>
</section>
<scriptsrc="./js/[Link]"></script>
</body>
Downloaded by CHAITANYA B
</html>
[Link]
@media(min-width:0px)and(max-width:425px)
{ section > nav {
grid-template-columns:auto13vw;
}
section>nav>ul{ dis
play: none;
}
.cart-icon
{ color:#32323
2;
font-size:1.3rem;
}
.fruits-
side>button{ height:
10vh;
width: 53vw;
font-size:1.2rem;
letter-spacing: 1px;
margin-bottom:30px;
}
.cart{
position:fixed;
height: 100vh;
width: 100%;
top:0%;
left:0%;
transform:scale(0.9);
}
.cart>main>ol>li:nth-child(1)
{ padding: 0px 12px;
}
}
@media(min-width:426px)and(max-width:1023px){ section
Downloaded by CHAITANYA B
> nav {
Downloaded by CHAITANYA B
grid-template-columns:auto60vw;
}
section>nav>span{ fo
nt-size: 1.6rem;
}
section>nav>ul>li>a{ font-
size: 1.1rem;
}
.fruits-
side>button{ height:
10vh;
width: 25vw;
font-size:1.2rem;
letter-spacing: 1px;
margin-bottom:30px;
}
.cart{
position:fixed;
height: 100vh;
width: 100%;
top:0%;
left:0%;
transform:scale(0.9);
}
.cart>main>ol>li:nth-child(1)
{ padding: 0px 12px;
}
section>footer{
grid-template-columns:auto60vw;
}
section>footer>ul>li{ padd
ing: 10px 15px;
}
}
Downloaded by CHAITANYA B
[Link]
*,
body{
margin:0;
padding:0;
list-style: none;
text-decoration:none;
outline: none;
letter-spacing:1px;
transition: all 0.5s;
color: inherit;
scroll-behavior:smooth;
font-family:"Poppins",sans-serif;
}
section{
position:relative;
width: 100%;
display: grid;
grid-template-columns:0.99fr;
grid-template-rows:15vhrepeat(3,80vh)15vh;
align-content: space-around;
justify-content:space-evenly;
}
section>nav{ display
: grid;
grid-template-columns:15vw50vw;
grid-template-rows: 0.8fr;
align-content: space-around;
justify-content: space-around;
background-color:whitesmoke;
}
section>nav>span{ disp
lay: flex;
align-items:center;
justify-content:space-evenly;
font-weight: bold;
font-size:2rem;
color: grey;
text-transform:capitalize;
}
Downloaded by CHAITANYA B
section>nav>span>a>i{ color:
#323232;
}
section>nav>ul{ disp
lay: flex;
align-items:center;
justify-content:space-evenly;
}
section>nav>ul>li{ posi
tion: relative;
}
section>nav>ul>li>a{ font-
weight: bold;
font-size: 1.3rem;
letter-spacing:1px;
color: grey;
}
section>nav>ul>li>a>i{ color:
#323232;
font-size:2rem;
}
.cart-icon{
display:none;
}
.items-count
{ position:absolut
e; padding: 5px;
background-color:red;
color: white;
font-weight: bold;
font-size: 0.9rem;
border-radius:30px;
top: -40%;
}
.fruits-side{
background-image:url("../assests/[Link]");
background-size: 100% 100%;
display:grid;
align-content: space-around;
justify-content:space-evenly;
}
.fruits-side>span{
Downloaded by CHAITANYA B
font-weight:bold;
font-size: 8rem;
color: white;
text-transform:capitalize;
padding-top: 80px;
}
.fruits-
side>button{ height
: 8.5vh; width:
13vw;
background-color:transparent;
border: 1.5px solid white;
border-radius: 10px;
font-weight:bold;
font-size:1.2rem;
color: white;
letter-spacing: 1px;
justify-self: center;
margin-bottom:30px;
}
.fruits-
side>button>a{ display:
flex;
align-items:center;
justify-content:space-evenly;
}
.fruits-
side>button:hover{ transition: all
0.5s;
cursor: pointer;
background-color:white;
border: none;
color:rgba(0,0,0,0.5);
}
.fruits-
side>button>a>i{ font-
size: 1.8rem;
}
.bottom-items-count
{ position: absolute;
padding: 5px;
background-color:red;
color: white;
font-weight: bold;
font-size: 0.9rem;
Downloaded by CHAITANYA B
border-radius:30px;
bottom: 40%;
}
Downloaded by CHAITANYA B
.cart{
position:fixed;
height: 98.5%;
width: 25vw;
background-color:whitesmoke;
top: 0.5%;
right: 0.5%;
display:grid;
grid-template-columns:0.95fr;
grid-template-rows:10vh60vh10vh;
align-content: space-around;
justify-content:space-evenly;
box-shadow:0px0px10px5pxrgba(0,0,0,0.5);
border-radius: 5px;
opacity: 0;
visibility: hidden;
z-index: -9;
transition:all0.5s;
}
.cart>header{ display
: flex;
align-items:center;
justify-content:space-around;
}
.cart>header>span{ disp
lay: flex;
align-items:center;
justify-content:space-evenly;
font-weight: bold;
font-size:1.5rem;
color: grey;
text-transform:capitalize;
}
.cart>header>span>a>i{ color:
#323232;
}
.exit> i{
font-size: 2rem;
color: #323232;
cursor: pointer;
transition:all0.5s;
}
.cart>main {
box-shadow:0px0px10px1pxrgba(0,0,0,0.5);
Downloaded by CHAITANYA B
border-radius:5px;
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 5vh 1fr;
align-content: space-around;
justify-content:space-evenly;
transition: all 0.5s;
}
.cart>main>ol{ displ
ay: flex;
align-items:center;
justify-content:space-around;
}
.cart>main>ol>li{ fon
t-weight: lighter;
border:1pxsolidrgba(0,0,0,0.5);
padding: 0px 21px;
color: grey;
}
.cart>main>section{ ov
erflow: scroll;
transition: all 0.5s;
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr;
align-content: space-around;
justify-content:space-evenly;
}
.cart>main>section>ul>li{ display:
flex;
align-items:center;
justify-content:space-between;
height: 5vh;
border-bottom:1pxsolidrgba(0,0,0,0.5); cursor:
pointer;
transition:all 0.5s;
}
[Link]
*,
body{
margin:0;
padding:0;
list-style: none;
Downloaded by CHAITANYA B
text-decoration:none;
outline: none;
letter-spacing:1px;
transition: all 0.5s;
color: inherit;
scroll-behavior:smooth;
font-family:"Poppins",sans-serif;
}
section
{ width:100
%;
display:grid;
grid-template-columns:0.99fr;
grid-template-rows:15vh90vh15vh;
align-content: space-around;
justify-content:space-evenly;
transition: all 0.5s;
}
section>nav{ display
: grid;
grid-template-columns:15vw50vw;
grid-template-rows: 0.8fr;
align-content: space-around;
justify-content: space-around;
background-color:whitesmoke;
}
section>nav>span{ disp
lay: flex;
align-items:center;
justify-content:space-evenly;
font-weight: bold;
font-size:2rem;
color: grey;
text-transform:capitalize;
}
section>nav>span>a>i{ color:
#323232;
}
section>nav>ul{ disp
lay: flex;
align-items:center;
justify-content:space-evenly;
}
section>nav>ul>li{ posi
tion: relative;
Downloaded by CHAITANYA B
}
section>nav>ul>li>a{ font-
weight: bold;
font-size: 1.3rem;
letter-spacing:1px;
color: grey;
}
section>nav>ul>li>a>i{ color:
#323232;
font-size:2rem;
}
.items-count
{ position:absolut
e; padding: 5px;
background-color:red;
color: white;
font-weight: bold;
font-size: 0.9rem;
border-radius:30px;
top: -40%;
}
.cart-icon
{ display:non
e;
}
section>main{ displa
y: grid;
grid-template-columns:repeat(4,23.5vw);
grid-template-rows: 55vh;
align-content: space-around;
justify-content:space-evenly;
}
.items{
border-radius:5px;
position: relative;
transition: all 0.5s;
}
.item-1{
background-image: url("../assests/fruit-img/close-up-photography-of-apples-
[Link]");
background-size:100%100%;
}
.item-1::after{
Downloaded by CHAITANYA B
content:"Apples";
position:absolute;
bottom: -13.5%;
left:0;
font-weight: bold;
font-size:1.75rem;
color: #323232;
}
.item-1::before
{content:"AddToCart";
position: absolute;
font-weight:bold;
font-size:1.2rem;
color: white;
background-color:transparent;
padding: 10px;
border-radius:20px;
cursor: pointer;
left:27%;
top: 45%;
cursor:pointer;
opacity: 0;
visibility: hidden;
transition: all 0.5s;
border:2pxsolidwhite;
}
.item-
1:hover::before{ opa
city: 1;
visibility: visible;
transition:all0.5s;
}
.item-1:hover{
background-image:linear-gradient(rgba(0,0,0,0.3),rgba(0,0,0,0.3)),
url("../assests/fruit-img/[Link]");
}
.item-2{
background-image:url("../assests/fruit-img/[Link]");
background-size: 100% 100%;
}
.item-2::after
{ content:"Lemons
"; position:
absolute; bottom: -
13.5%;
left:0;
Downloaded by CHAITANYA B
font-weight:bold;
Downloaded by CHAITANYA B
font-size:1.75rem;
color: #323232;
}
.item-2::before
{content:"AddToCart";
position: absolute;
font-weight:bold;
font-size:1.2rem;
color: white;
background-color:transparent;
padding: 10px;
border-radius:20px;
cursor: pointer;
left:27%;
top: 45%;
cursor:pointer;
opacity: 0;
visibility: hidden;
transition: all 0.5s;
border:2pxsolidwhite;
}
.item-
2:hover::before{ opa
city: 1;
visibility: visible;
transition:all0.5s;
}
.item-2:hover{
background-image:linear-gradient(rgba(0,0,0,0.3),rgba(0,0,0,0.3)),
url("../assests/fruit-img/[Link]");
}
.item-3{
background-image: url("../assests/fruit-img/white-bowl-of-whole-strawberries-
[Link]");
background-size:100%100%;
}
.item-3::after{
content:"Strawberries";
position: absolute;
bottom: -13.5%;
left:0;
font-weight: bold;
font-size:1.75rem;
color: #323232;
}
Downloaded by CHAITANYA B
.item-3::before
{content:"AddToCart";
position: absolute;
font-weight:bold;
font-size:1.2rem;
color: white;
background-color:transparent;
padding: 10px;
border-radius:20px;
cursor: pointer;
left:27%;
top: 45%;
cursor:pointer;
opacity: 0;
visibility: hidden;
transition: all 0.5s;
border:2pxsolidwhite;
}
.item-
3:hover::before{ opa
city: 1;
visibility: visible;
transition:all0.5s;
}
.item-3:hover{
background-image: linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)),
url("../assests/fruit-img/[Link]");
}
.item-4{
background-image: url("../assests/fruit-img/[Link]");
background-size: 100% 100%;
}
.item-4::after
{ content:"Bananas
"; position:
absolute; bottom: -
13.5%;
left:0;
font-weight: bold;
font-size:1.75rem;
color: #323232;
}
.item-4::before
{content:"AddToCart";
font-size:1.2rem;
Downloaded by CHAITANYA B
position: absolute;
font-weight:bold;
font-size:1.2rem;
Downloaded by CHAITANYA B
color:white;
background-color:transparent;
padding: 10px;
border-radius:20px;
cursor: pointer;
left:27%;
top: 45%;
cursor:pointer;
opacity: 0;
visibility: hidden;
transition: all 0.5s;
border:2pxsolidwhite;
}
.item-
4:hover::before{ opa
city: 1;
visibility: visible;
transition:all0.5s;
}
.item-4:hover{
background-image:linear-gradient(rgba(0,0,0,0.3),rgba(0,0,0,0.3)),
url("../assests/fruit-img/[Link]");
}
@media(min-width:0px)and(max-width:425px)
{ section {
grid-template-rows:15vh250vh 15vh;
}
section>main {
grid-template-columns:repeat(1,85vw);
grid-template-rows: repeat(4, 50vh);
}
.item-1::before,
.item-2::before,
.item-3::before,
.item-4::before
{ padding:10px15px;
left: 20%;
top:43%;
}
.item-1::after,
.item-2::after,
.item-3::after,
.item-4::after
{ bottom: -18%;
font-size:1.5rem;
Downloaded by CHAITANYA B
}
.item-4{
margin-bottom:10%;
}
}
@media(min-width:426px)and(max-width:1023px){ section
{
grid-template-rows:15vh140vh 15vh;
}
section>main {
grid-template-columns:repeat(2,35vw);
grid-template-rows: repeat(2, 55vh);
}
.item-1::before,
.item-2::before,
.item-3::before,
.item-4::before
{ padding:10px15px;
left: 20%;
top:43%;
}
.item-1::after,
.item-2::after,
.item-3::after,
.item-4::after
{ bottom: -18%;
font-size:1.5rem;
}
}
OUTPUT:
Downloaded by CHAITANYA B
Downloaded by CHAITANYA B
Downloaded by CHAITANYA B
2. MaketheabovewebapplicationresponsivewebapplicationusingBootstrapframework
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>Bootstrap4-ShoppingCart</title>
<linkrel="stylesheet"href="assets/bootstrap/[Link]">
<scriptsrc="assets/js/[Link]"></script>
<linkrel="stylesheet"href="assets/fontawesome/css/[Link]">
<scriptsrc="assets/js/[Link]"></script>
<linkrel="stylesheet"href="assets/css/[Link]">
<linkrel="icon"href="images/[Link]"type="image/x-icon"/>
</head>
<body>
<!--partial:[Link]-->
Downloaded by CHAITANYA B
<!--Nav-->
<navclass="navbarnavbar-inversebg-inversefixed-topbg-faded">
<divclass="row">
<divclass="col">
<spandata-toggle="modal"data-target="#cart">
<iclass="fasfa-shopping-cartfa-2xfa-bordericon-grey
zoom-sm"><span class="badge total-count"></span></i>
</span>
<buttonclass="clear-cartbtnbtn-dangerml-2"id="clearCart">
<iclass="fasfa-undo"></i>Clear
</button>
</div>
</div>
</nav>
<!--Main-->
<divclass="container">
<br>
<h3class="text-center">Bootstrap4-Shopping Cart</h3>
<hr>
<divclass="row">
<divclass="col-sm-12col-md-6col-xl-4">
<figureclass="cardcard-productzoom">
<divclass="img-wrap"><imgsrc="images/[Link]"class="roundedp-
1"></div>
<figcaptionclass="info-wrap">
<h4class="title">Beautifuldress</h4>
<pclass="desc">Somesmalldescriptiongoes here</p>
<divclass="rating-wrap">
<divclass="label-rating">132reviews</div>
<divclass="label-rating">154orders</div>
<br/>
<smallclass="text-muted">★★
★★☆</small>
</div><!--rating-wrap.//-->
</figcaption>
<divclass="bottom-wrap">
<ahref=""class="btnbtn-smbtn-primaryfloat-rightadd-to-cartshow-
toast" data-product_id="1" data-pimage="images/[Link]" data-name="Beautiful
dress"data-price="220">
<iclass="fasfa-shopping-cart"></i>Addtocart
Downloaded by CHAITANYA B
</a>
<divclass="price-wraph5">
<spanclass="price-new">$220</span><delclass="price-
old">$300</del>
</div><!--price-wrap.//-->
</div><!--bottom-wrap.//-->
</figure>
</div><!--col//-->
<divclass="col-sm-12col-md-6col-xl-4">
<figureclass="cardcard-productzoom">
<divclass="img-wrap"><imgsrc="images/[Link]"class="roundedp-1">
</div>
<figcaptionclass="info-wrap">
<h4class="title">Elegantstyle</h4>
<pclass="desc">Somesmalldescriptiongoes here</p>
<divclass="rating-wrap">
<divclass="label-rating">132reviews</div>
<divclass="label-rating">154orders</div>
<br/>
<smallclass="text-muted">★★
★★☆</small>
</div><!--rating-wrap.//-->
</figcaption>
<divclass="bottom-wrap">
<a href="" class="btn btn-sm btn-primary float-right add-to-
cartshow-toast"data-product_id="2"data-pimage="images/[Link]"data-name="Elegant
style" data-price="115">
<iclass="fasfa-shopping-cart"></i>Addtocart
</a>
<divclass="price-wraph5">
<spanclass="price-new">$115</span><del
class="price-old">$180</del>
</div><!--price-wrap.//-->
</div><!--bottom-wrap.//-->
</figure>
</div><!--col//-->
<divclass="col-sm-12col-md-6col-xl-4">
<figureclass="cardcard-productzoom">
<divclass="img-wrap"><imgsrc="images/[Link]"class="roundedp-
1"></div>
<figcaptionclass="info-wrap">
<h4class="title">Modernfashion</h4>
<pclass="desc">Somesmalldescriptiongoes here</p>
<divclass="rating-wrap">
<divclass="label-rating">132reviews</div>
<divclass="label-rating">154orders</div>
<br/>
<smallclass="text-muted">★★
★★☆</small>
</div><!--rating-wrap.//-->
</figcaption>
<divclass="bottom-wrap">
Downloaded by CHAITANYA B
<ahref=""class="btnbtn-smbtn-primaryfloat-rightadd-to- cart
show-toast" data-product_id="3"data-pimage="images/[Link]" data- name="Modern
fashion" data-price="680">
<iclass="fasfa-shopping-cart"></i>Addtocart
</a>
<divclass="price-wraph5">
<spanclass="price-new">$680</span><del
class="price-old">$980</del>
</div><!--price-wrap.//-->
</div><!--bottom-wrap.//-->
</figure>
</div><!--col//-->
</div><!--row.//-->
<divclass="rowp-2">
<pclass="text-infofont-weight-bold">
Easytoaddtoaneworexistingproject.RequiresBootstrap4Css&Js,Jquery,and Fontawesome. Just
add the resources <code class="text-danger">*/[Link]</code> and
<codeclass="text-danger">*/[Link]</code>togetgoing.
</p>
<pclass="text-infofont-weight-bold">
[Link]<kbd>Add to
Cart</kbd> buttton with the <code class="text-danger">data-product_id</code>, <code
class="text-danger">data-pimage</code>
<codeclass="text-danger">data-name</code>,and<codeclass="text-danger">data- price</code>
attributes.
</p>
<pclass="text-infofont-weight-bold">
The cart form data is generated with the function <code class="text-
danger">displayCart()</code>inthe<codeclass="text-danger">[Link]</code>[Link] can
modify it to your own preference.
</p>
</div>
</div>
<!--container.//-->
<!--Modal-->
<divclass="modalfade"id="cart"tabindex="-1"role="dialog"aria-
labelledby="exampleModalLabel" aria-hidden="true">
<divclass="modal-dialogmodal-lg"role="document">
<divclass="modal-content">
<formaction="[Link]"method="get"class="cart-form">
<divclass="modal-header">
<h5class="modal-title"id="exampleModalLabel"><iclass="fasfa-shopping-
cart text-black"></i> Shopping Cart</h5>
<buttontype="button"class="close"data-dismiss="modal"aria-label="Close">
<spanaria-hidden="true">×</span>
</button>
</div>
<divclass="modal-body">
<tableclass="show-carttable">
Downloaded by CHAITANYA B
</table>
<divclass="font-weight-bold">Totalprice:$<spanclass="total-carttext-
danger"></span></div>
</div>
<divclass="modal-footer">
<buttontype="button"class="btnbtn-danger"data-
dismiss="modal">Close</button>
<buttontype="submit"class="btnbtn-success">Checkout</button>
</div>
</form>
</div>
</div>
</div>
<!--partial-->
<scriptsrc='assets/js/[Link]'></script>
<scriptsrc="assets/js/[Link]"></script>
<!--ShoppingCartAddToast-->
<divid="product-toast">
<divid="img">
<iclass="fasfa-shopping-cart"></
i>Cart
</div>
<divid="desc"><spanid="item-name"></span>addedtocart</div>
</div>
</body>
</html>
[Link]
//************************************************
//ShoppingCartAPI
//************************************************
//Constructor
functionItem(product_id,name,price,pimage,count){ "use
strict";
this.product_id=product_id;
[Link] = name;
[Link] = price;
[Link]=pimage;
[Link] = count;
}
//Savecart
functionsaveCart(){
Downloaded by CHAITANYA B
"usestrict";
[Link]('shoppingCart',[Link](cart));
}
//Loadcart
functionloadCart()
{ "use strict";
cart= [Link]([Link]('shoppingCart'));
}
if([Link]("shoppingCart")!=null){
loadCart();
}
//=============================
//Publicmethodsandpropeties
//=============================
varobj= {};
//Addtocart
[Link]=function(product_id,name,price,pimage,count)
{ "use strict";
for(var item in cart)
{ if(cart[item].product_id===product_id){
cart[item].count ++;
saveCart();
return;
}
}
varitem=newItem(product_id,name,price,pimage,count);
[Link](item);
saveCart();
}
//Setcount fromitem
[Link]=function(product_id,count)
{ "use strict";
for(variincart) {
if(cart[i].product_id===product_id)
{ cart[i].count = count;
break;
}
}
};
// Remove item from cart
[Link]=function(product_id)
{ "use strict";
for(var item in cart)
{ if(cart[item].product_id===product_id){
cart[item].count --;
if(cart[item].count===0)
{ [Link](item, 1);
}
break;
}
Downloaded by CHAITANYA B
}
saveCart();
}
//Clear cart
[Link]=function()
{ "use strict";
cart = [];
saveCart();
}
//Countcart
[Link]=function()
{ "use strict";
var totalCount = 0;
for(varitemincart){
totalCount+= cart[item].count;
}
return totalCount;
}
//Totalcart
[Link]=function()
{ "use strict";
var totalCart = 0;
for(varitemincart){
totalCart+=cart[item].price*cart[item].count;
}
return Number([Link](2));
}
//List cart
[Link]=function(){ var
cartCopy = [];
for(i in cart)
{ item = cart[i];
itemCopy={};
for(pinitem){
itemCopy[p]= item[p];
}
[Link]=Number([Link]*[Link]).toFixed(2);
[Link](itemCopy)
Downloaded by CHAITANYA B
}
return cartCopy;
}
//cart:Array
//Item:Object/Class
//addItemToCart:Function
//removeItemFromCart:Function
//removeItemFromCartAll: Function
//clearCart: Function
//countCart: Function
//totalCart: Function
//listCart: Function
//saveCart: Function
//loadCart:Function
return obj;
})();
//*****************************************
//Triggers/Events
//*****************************************
//Add item
$('.add-to-cart').on("click",function(event)
{ "use strict";
[Link]();
varproduct_id=$(this).data('product_id');
var name = $(this).data('name');
varprice=Number($(this).data('price'));
var pimage = $(this).data('pimage');
[Link](product_id,name,price,pimage,1);
displayCart();
});
//Clear items
$('.clear-cart').on("click",function()
{ "use strict";
[Link]();
displayCart();
});
functiondisplayCart()
{ "use strict";
varcartArray=[Link]();
var output = "";
var total_order = 0;
for(variincartArray){
total_order++;
output+="<divclass='col-12'>"
+"<divclass='rowjustify-content-center'>"
+"<divclass='col-5'>"
+"<divclass='row'>"
+"<divclass='col-9text-left'>"
Downloaded by CHAITANYA B
+"<imgsrc='"+cartArray[i].pimage+"'class='rounded-circle'width='50'height='50'/>"
+"<spanclass='text-infopl-3font-weight-bold'>"+cartArray[i].name+"</span>"
+ "</div>"
+"<divclass='col-3'>"
+"<spanclass='text-darkpl-2mr-1'>("+cartArray[i].price+")</span>"
+ "</div>"
+ "</div>"
+ "</div>"
+"<divclass='col-4'>"
+"<divclass='input-group'><buttonclass='minus-iteminput-group-addonbtnbtn-primary'data- product_id="
+ cartArray[i].product_id + ">-</button>"
+"<inputtype='number'class='item-countform-control'data-product_id='"+
cartArray[i].product_id + "' value='" + cartArray[i].count + "'>"
+"<buttonclass='plus-itembtnbtn-primaryinput-group-addon'data-product_id="+
cartArray[i].product_id + ">+</button></div>"
+ "</div>"
+"<divclass='col-3'>"
+"<buttonclass='delete-itembtnbtn-danger'data-product_id="+cartArray[i].product_id+
">X</button>"
+"<spanclass='text-dartpl-2'><kbd>"+cartArray[i].total+"</kbd></span>"
+ "</div>"
+ "</div>"
+ "</div>"
+"<divclass='row'id='hedden-fields'><inputtype='hidden'class='sr-only'name='ProductID[]'
id='ProductName' value='" + cartArray[i].product_id + "'>"
+"<inputtype='hidden'class='sr-only'name='ProductName[]'id='ProductName'value='"+ cartArray[i].name
+ "'>"
+"<inputtype='hidden'class='sr-only'name='ProductPrice[]'id='ProductPrice'value='"+ cartArray[i].price +
"'>"
+"<inputtype='hidden'class='sr-only'name='ProductQuantity[]'id='ProductQuantity'value='"+
cartArray[i].count + "'>"
+"<inputtype='hidden'class='sr-only'name='TotalOrderedItems'id='TotalOrderedItems'value='"
+total_order+"'></div>"
+"<hr/>";
}
$('.show-cart').html(output);
$('.total-cart').html([Link]());
$('.total-count').html([Link]());
}
//Deleteitembutton
$('.show-cart').on("click",".delete-item",function(event)
{ "use strict";
varname= $(this).data('name');
var product_id = $(this).data('product_id');
[Link](product_id);
displayCart();
})
//-1
Downloaded by CHAITANYA B
$('.show-cart').on("click",".minus-item",function(event)
{ "use strict";
varname= $(this).data('name');
var product_id = $(this).data('product_id');
[Link](product_id);
displayCart();
})
//+1
$('.show-cart').on("click",".plus-item",function(event){ "use
strict";
varname= $(this).data('name');
varproduct_id=$(this).data('product_id');
[Link](product_id);
displayCart();
})
//Itemcountinput
$('.show-cart').on("change",".item-count",function(event)
{ "use strict";
var name = $(this).data('name');
varcount=Number($(this).val());
var product_id = $(this).data('product_id');
[Link](product_id,count);
displayCart();
});
displayCart();
//=============================
//Carttoast display
//=============================
$('.show-toast').on("click",function(){
"use strict";
constx=[Link]("product-toast"); var
item_name = $(this).data('name');
$("#item-name").text(item_name);
[Link] = "show";
setTimeout(function(){[Link]=[Link]("show","");},3000);
});
body{
padding-top:80px;
}
/*productcartdesign*/
.show-
cartli{ displa
y:flex;
}
.card{
margin-bottom:20px;
}
Downloaded by CHAITANYA B
.card-img-top
{ width: 200px;
height: 200px;
align-self:center;
}
.card-product .img-wrap
{ border-radius:3px3px00;
overflow: hidden;
position:relative;
height: 220px;
text-align:center;
}
.[Link]-
wrapimg{ max-height:
100%;
max-width:100%;
object-fit: cover;
}
.[Link]-
wrap{ overflow: hidden;
padding: 15px;
border-top:1pxsolid#eee;
}
.[Link]-
wrap{ padding: 15px;
border-top:1pxsolid#eee;
}
.label-rating{margin-right:10px;
color: #333;
display: inline-block;
vertical-align:middle;
}
.[Link]-
old{ color: #999;
}
.fa-2x-cart{
font-size:24px
}
/*shoppingcart counter*/
.header{background:rgb(0,178,255);color:#fff;}
#lblCartCount {
font-size: 12px;
background:#ff0000;
color: #fff;
padding: 0 5px;
vertical-align: top;
margin-left:-10px;
}
.badge{
padding-left:9px;
Downloaded by CHAITANYA B
padding-right:9px;
-webkit-border-radius:9px;
-moz-border-radius:9px;
border-radius: 9px;
}
.label-warning[href],
.badge-warning[href]
{ background-
color:#c67605;
}
/*shoppingcartcounterstyle*/
[Link]-shopping-cart {
width:2.2em;
text-align:center;
vertical-align:middle;
}
.fa-shopping-cart
{ margin-
top:0.2em;
position: relative;
}
.badge{
font-size: .25em;
display: block;
position:absolute;
top: -.70em;
right: -.70em;
width: 2.5em;
height: 2.4em;
line-height:2em;
border-radius:50%;
text-align: center;
color:#fff;
background:rgba(207,0,15,1);
}
.zoom:hover
{ transform:scale(1.05
);
}
.zoom-sm:hover
{ transform:scale(1.03
);
Downloaded by CHAITANYA B
}
Downloaded by CHAITANYA B
/*shoppingcarttoast*/
#product-toast
{ visibility: hidden;
max-width:50px;
height: 50px;
margin: auto;
background-color:#333;
color: #fff;
text-align: center;
border-radius:2px;
position:fixed;
z-index: 1;left:
0;right:0;
bottom: 30px;
font-size: 17px;
white-space:nowrap;
}
#product-
toast#img{ width:
70px;height: 50px;
float:left;
padding-top: 16px;
padding-bottom:16px;
box-sizing:border-box;
background-color:#111;
color: #fff;
}
#product-toast#desc{
color: #fff;
padding:16px;
overflow: hidden;
white-space:nowrap;
}
#product-
[Link]{ visibilit
y: visible;
-webkit-animation:fadein0.5s,expand0.5s0.5s,stay3s1s,shrink0.5s2s,fadeout0.5s2.5s; animation:
fadein 0.5s, expand 0.5s 0.5s,stay 3s 1s, shrink 0.5s 4s, fadeout 0.5s 4.5s;
}
@-webkit-keyframes fadein
{ from {bottom: 0; opacity:
0;}
to{bottom:30px;opacity:1;}
Downloaded by CHAITANYA B
}
Downloaded by CHAITANYA B
@keyframesfadein{
from {bottom: 0; opacity: 0;}
to{bottom:30px;opacity:1;}
}
@-webkit-
keyframesexpand{ from {min-
width: 50px}
to{min-width:350px}
}
@keyframes expand
{ from{min-
width:50px} to {min-
width: 350px}
}
@-webkit-
keyframesstay{ from
{min-width: 350px} to
{min-width: 350px}
}
@keyframesstay{
from{min-width:350px}
to {min-width: 350px}
}
@-webkit-
keyframesshrink{ from
{min-width: 350px;} to
{min-width: 50px;}
}
@keyframesshrink{
from{min-width:350px;}
to {min-width: 50px;}
}
@-webkit-keyframes fadeout
{ from{bottom:30px;opacity:1;}
to {bottom: 60px; opacity: 0;}
}
@keyframesfadeout{
from{bottom:30px;opacity:1;} to
{bottom: 60px; opacity: 0;}
}
Downloaded by CHAITANYA B
3. UseJavaScriptfordoingclient–sidevalidationofthepages
implemented in experiment 1 andexperiment 2.
const top_items_count = [Link]('.items-count'),
bottom_items_count=[Link]('.bottom-items-count'),
exit = [Link]('.exit'),
bucket=[Link]('.cart').style;
varitems= [Link]('.items');
top_items_count.innerHTML = count;
bottom_items_count.innerHTML=count;
function openBucket()
{ [Link]="visible";
[Link] = "1";
[Link] = "9";
[Link]="all0.5s";
}
[Link]('click',
()=>{ [Link] = "hidden";
[Link] = "0";
[Link] = "-9";
[Link]="all0.5s";
});
varfood_cart=[];
() => {
if(localStorage.food_cart){
food_cart=[Link](localStorage.food_cart); showCart();
}
Downloaded by CHAITANYA B
}
varqty=1;
for(i=0;i<=[Link]-1;i++){ var
count=0;
items[i].onclick=e=>{ coun
t=count+1
var itemName = [Link];
var price = [Link];
addToCart(itemName, price, qty);
top_items_count.innerHTML=count;
bottom_items_count.innerHTML=count;
}
}
functionaddToCart(itemName,price,qty)
var itemArray =
{ Product:itemNam
e, Price: price,
Qty:qty
}
food_cart.push(itemArray)
saveCart();
showCart();
}
functionsaveCart(){
if([Link]){
localStorage.food_cart=[Link](food_cart);
}
}
functiondeleteItem(index)
{ food_cart.splice(index,1
); showCart();
saveCart();
}
functionshowCart(){
if(food_cart.length==0){
var_ul= [Link]('#ul');
_ul.innerHTML="";
Downloaded by CHAITANYA B
return;
}
var_ul= [Link]('#ul');
_ul.innerHTML = "";
for(variinfood_cart){
varitem= food_cart[i];
varli= [Link]("li")
varrow=`<span>${[Link]}</span><spanonclick='deleteItem("+i+")'><iclass='fasfa-
trash'></i></span><span>${[Link]}</span><span>${[Link] * [Link]}</span>`;
[Link]+=row;
var_ul= [Link]('#ul');
_ul.appendChild(li);
}
}
4. ExplorethefeaturesofES6likearrowfunctions,callbacks,promises,async/
[Link]
[Link].
ArrowfunctionsareintroducedinES6,whichprovidesyouamoreaccuratewa
[Link]
ax.
Arrowfunctionsmakeyourcodemorereadableandstructured.
1. constfunctionName=(arg1,arg2,?..)=>{
Downloaded by CHAITANYA B
2. //bodyofthefunction
3.}
TherearethreepartstoanArrowFunctionorLambdaFunction:
o Parameters:Anyfunctionmayoptionallyhavetheparameters.
o Fat arrow notation/lambda notation:It is
the notation forthearrow(=>).
o Statements:Itrepresentstheinstructionsetofthefunction.
//functionexpression
varmyfun1=functionshow()
{[Link]("ItisaFunctionExpression");
}
//
Anonymousfunctionvarm
yfun2=function(){
[Link]("ItisanAnonymousFunction");
}
//
Arrowfunctionvarm
yfun3=()=>{
[Link]("ItisanArrowFunction");
};
myfun1();
myfun2();
myfun3();
Output
ItisaFunctionExpressionItis
anAnonymousFunctionItisanAr
rowFunction
ES6Promises
[Link]
neitherberejectedorresolvedbasedontheoperationoutcome.
ES6Promiseistheeasiestwaytoworkwithasynchronousprogramming
[Link]
essesindividuallyfromthemainthreadandnotifiesthemainthreadwhe
[Link],Callbackswereusedtoperfor
Downloaded by CHAITANYA B
masynchronousprogramming.
Downloaded by CHAITANYA B
Callback
ACallbackisawaytohandlethefunctionexecutionafterthecompletion
oftheexecutionofanotherfunction.
[Link],afunctio
ncanbepassedasaparametertoanotherfunction.
Syntax
1. constPromise=newPromise((resolve,reject)=>{ });
Example
1. letPromise=newPromise((resolve,reject)=>{
2. leta=3;
3. if(a==3){
4. resolve('Success');
5. }
6. else{
7. reject('Failed');
8. }
9.}
) [Link]((message)=>{
10.
11. [Link]("[Link]:?
+message)
12. }).catch((message)=>{
13. [Link]("[Link]:?
+message)
14. })
Outpu
t
[Link]:Success
JavaScriptAsync/Await
JavaScript is always synchronous and single-threaded that provides the event loops. The event loops
[Link] program
that queued the action has completed the execution. However, our program contains a large number of
functionalities, which causes our code to be [Link]/Await functionality is one of
[Link]/Await is an extension of promises that we get as language support.
1. <!DOCTYPEhtml>
2. <html>
Downloaded by CHAITANYA B
3. <head>
4. <metacharset="utf-8">
5. <title>JavaScriptAsync</title>
6. </head>
7. <body>
8. <h2>JavaScriptAsync</h2>
9. <pid="main"></p>
10. <script>
11. functionmyDisplayer(some){
12. [Link]("main").innerHTML=some;
13. }
14. asyncfunctionmyfirstFunction(){
15. return"HelloWorld!!!";
16. }
17. myfirstFunction().then(
18. function(value){myDisplayer(value);},
19. function(error){myDisplayer(error);}
20.);
21. </script>
22. </body>
23. </html>
Output:Afterexecutingtheabovecode,wewillgettheoutputshownbe
lowinthescreenshot.
JavaScriptAwait
[Link]
[Link]
Downloaded by CHAITANYA B
[Link]
uctsJavaScripttowaitforanasynchronousactiontocompletebeforecontinui
[Link]'ssimilartoa"pauseuntildone"[Link]
ywordisusedtoretrieveavaluefromafunctionwherewewillusuallybeused
thethen()[Link],we'dus
eawaittoallocateavariabletotheresultandthenusetheresultinthecodeasw
ewillinthesynchronouscode.
1. <!DOCTYPEhtml>
2. <html>
3. <head>
4. <metacharset="utf-8">
5. <title>JavaScriptAwait</title>
6. </head>
7. <body>
8. <h2>JavaScriptAwait</h2>
9. <pid="main"></p>
10. <script>
11. asyncfunctionmyDisplay(){
12. letmyPromise=newPromise(function(myResolve,myReject)
{
13. myResolve("HelloWorld!!");
14. });
15.
[Link]("main").innerHTML=awaitmyPro
mise;
16. }
17. myDisplay();
18. </script>
19. </body>
20. </html>
Output:Afterexecutingthiscode,wewillgettheoutputasshownbelow
inthescreenshot:
Downloaded by CHAITANYA B
[Link] information in
the form of a graph on the web page.
[Link]
<!DOCTYPEhtml>
<html>
<head>
<title>WeatherReport</title>
<linkrel="icon"href="[Link]">
<linkrel="stylesheet"href="[Link]">
<linkhref=
'[Link]
family=DeliusSwashCaps'rel='stylesheet'>
</head>
<body>
<pid="data"class="styleIt"></p>
<scriptsrc="[Link]"></script>
</body>
</html>
[Link]
[Link]
{
background-color:rgb(182,182,182);
border:2pxsolidrgb(182,182,182);b
order-radius:8px;
text-align:center;
box-shadow:6px5px2pxrgb(182,182,182),0025pxrgb(0,0,0),005px
rgb(182,182,182);
font-family:'DeliusSwashCaps';
}
body{
background:rgb(120,120,120);
margin:0;position
:absolute;
Downloaded by CHAITANYA B
top:50%;
left:50%;
margin-right:-50%;
transform:translate(-50%,-50%)
}
[Link]
vardata=[Link]
tById("data");
varLatitude;va
rLongitude;
varkey="------PutYourOwnKey--------------";
varurl="[Link]
weather?";functiongetLocation(){
if([Link]){
[Link](showPosition);
}
else{
data_of_Lat_Lon.innerHTML="Geolocationisnotsuppo
[Link]!";
}
}
functionshowPosition(position)
{Latitude=[Link]
de;
Longitude=[Link];getD
ata(Latitude,Longitude);
}
functiongetData(Lat,Lon)
{constreadyToSent=
(url+"lat="+Lat+"&lon="+Lon+"&appid="+key);fe
tch(readyToSent)
.then(response=>[Link]())
.then(data=>{
[Link](data);fetchData(d
ata)
})
}
functionfetchData(data)
{consticon=
"[Link]
Downloaded by CHAITANYA B
wn/"+[Link][0].icon+"@[Link]"
Downloaded by CHAITANYA B
[Link]("data").innerHTML="<b
>TheweatherreportofyourLocationis
:-</b><br>"+
"<imgsrc="+icon+"><br>"+"<b>Coun
try:</b>"+[Link]+
"<br><b>LocalAreaName:</
b>"+[Link]+"<br><b>Temp.:</
b>"+parseFloat(([Link]-
273.15)).toFixed(1)+"℃"+
"<br><b>ButYouwillfeellike
:</b>"+parseFloat(([Link].feels_like-
273.15)).toFixed(1)+"℃"+
"<br><b>[Link].
:</b>"+parseFloat(([Link].temp_min-
273.15)).toFixed(1)+"℃"+
"<br><b>[Link].
:</b>"+parseFloat(([Link].temp_max-
273.15)).toFixed(1)+"℃"+
"<br><b>Pressure:</
b>"+[Link]+"hPa"+"<br><b>Humidity:
</
b>"+[Link]+"%"+"<br><b>Weather:</
b>"+[Link][0].description+"<br>"
}
getLocation();showPosi
tion();getData();
Downloaded by CHAITANYA B
TocreateaDjangoapplicationthatperformsCRUDoperations,followthefollo
wingsteps.
1. CreateaProject
1. $django-adminstartprojectcrudexample
2. CreateanApp
1. $[Link]
3. ProjectStructure
nitially,ourprojectlookslikethis:
Downloaded by CHAITANYA B
4. DatabaseSetup
//[Link]
1. DATABASES={
2. 'default':{
3. 'ENGINE':'[Link]',
4. 'NAME':'djangodb',
5. 'USER':'root',
6. 'PASSWORD':'mysql',
7. 'HOST':'localhost',
8. 'PORT':'3306'
9. }
10. }
5. CreateaModel
[Link].
//[Link]
Downloaded by CHAITANYA B
1. [Link]
2. classEmployee([Link]):
3. eid=[Link](max_length=20)
4. ename=[Link](max_length=100)
5. eemail=[Link]()
6. econtact=[Link](max_length=15)
7. classMeta:
8. db_table="employee"
6. CreateaModelForm
//[Link]
1. fromdjangoimportforms
2. [Link]
3. classEmployeeForm([Link]):
4. classMeta:
5. model=Employee
6. fields="all"
7. CreateViewFunctions
//[Link]
1. [Link],redirect
2. [Link]
3. [Link]
4. #Createyourviewshere.
5. defemp(request):
6. [Link]=="POST":
7. form=EmployeeForm([Link])
8. ifform.is_valid():
9. try:
10. [Link]()
11. returnredirect('/show')
12. except:
13. pass
14. else:
15. form=EmployeeForm()
Downloaded by CHAITANYA B
16. returnrender(request,'[Link]',{'form':form})
17. defshow(request):
18. employees=[Link]()
19. returnrender(request,"[Link]",
{'employees':employees})
20. defedit(request,id):
21. employee=[Link](id=id)
22. returnrender(request,'[Link]',{'employee':employee})
23. defupdate(request,id):
24. employee=[Link](id=id)
25. form=EmployeeForm([Link],instance=employee)
26. ifform.is_valid():
27. [Link]()
28. returnredirect("/show")
29. returnrender(request,'[Link]',{'employee':employee})
30. defdestroy(request,id):
31. employee=[Link](id=id)
32. [Link]()
33. returnredirect("/show")
8. ProvideRouting
ProvideURLpatternstomapwithviewsfunction.
//[Link]
1. [Link]
2. [Link]
3. fromemployeeimportviews
4. urlpatterns=[
5. path('admin/',[Link]),
6. path('emp',[Link]),
7. path('show',[Link]),
8. path('edit/<int:id>',[Link]),
9. path('update/<int:id>',[Link]),
10. path('delete/<int:id>',[Link]),
11. ]
9. OrganizeTemplates
Downloaded by CHAITANYA B
Createatemplatesfolderinsidetheemployeeappandcreatethree(i
ndex,edit,show)[Link]
below
//[Link]
1. <!DOCTYPEhtml>
2. <htmllang="en">
3. <head>
4. <metacharset="UTF-8">
5. <title>Index</title>
6. {%loadstaticfiles%}
7. <linkrel="stylesheet"href="{%static'css/[Link]'%}"/>
8. </head>
9. <body>
10. <formmethod="POST"class="post-form"action="/emp">
11. {%csrf_token%}
12. <divclass="container">
13. <br>
14. <divclass="form-grouprow">
15. <labelclass="col-sm-1col-form-label"></label>
16. <divclass="col-sm-4">
17. <h3>EnterDetails</h3>
18. </div>
19. </div>
20. <divclass="form-grouprow">
21. <labelclass="col-sm-2col-form-label">EmployeeId:</
label
>
22. <divclass="col-sm-4">
23. {{[Link]}}
24. </div>
25. </div>
26. <divclass="form-grouprow">
27. <labelclass="col-sm-2col-form-
label">EmployeeName:</label>
28. <divclass="col-sm-4">
29. {{[Link]}}
30. </div>
Downloaded by CHAITANYA B
31. </div>
32. <divclass="form-grouprow">
33. <labelclass="col-sm-2col-form-
label">EmployeeEmail:</label>
34. <divclass="col-sm-4">
35. {{[Link]}}
36. </div>
37. </div>
38. <divclass="form-grouprow">
39. <labelclass="col-sm-2col-form-
label">EmployeeContact:<
/label>
40. <divclass="col-sm-4">
41. {{[Link]}}
42. </div>
43. </div>
44. <divclass="form-grouprow">
45. <labelclass="col-sm-1col-form-label"></label>
46. <divclass="col-sm-4">
47. <buttontype="submit"class="btn
btn-primary">Submit</button>
48. </div>
49. </div>
50. </div>
51. </form>
52. </body>
53. </html>
//[Link]
1. <!DOCTYPEhtml>
2. <htmllang="en">
3. <head>
4. <metacharset="UTF-8">
5. <title>EmployeeRecords</title>
6. {%loadstaticfiles%}
7. <linkrel="stylesheet"href="{%static'css/[Link]'%}"/>
8. </head>
Downloaded by CHAITANYA B
9. <body>
10. <tableclass="tabletable-stripedtable-borderedtable-sm">
11. <theadclass="thead-dark">
12. <tr>
13. <th>EmployeeID</th>
14. <th>EmployeeName</th>
15. <th>EmployeeEmail</th>
16. <th>EmployeeContact</th>
17. <th>Actions</th>
18. </tr>
19. </thead>
20. <tbody>
21. {%foremployeeinemployees%}
22. <tr>
23. <td>{{[Link]}}</td>
24. <td>{{[Link]}}</td>
25. <td>{{[Link]}}</td>
26. <td>{{[Link]}}</td>
27. <td>
28. <ahref="/edit/
{{[Link]}}"><spanclass="glyphiconglyphic
on-pencil">Edit</span></a>
29. <ahref="/delete/{{[Link]}}">Delete</a>
30. </td>
31. </tr>
32. {%endfor%}
33. </tbody>
34. </table>
35. <br>
36. <br>
37. <center><ahref="/emp"class="btnbtn-
primary">AddNewRecord</a></center>
38. </body>
39. </html>
//[Link]
1. <!DOCTYPEhtml>
Downloaded by CHAITANYA B
2. <htmllang="en">
3. <head>
4. <metacharset="UTF-8">
5. <title>Index</title>
6. {%loadstaticfiles%}
7. <linkrel="stylesheet"href="{%static'css/[Link]'%}"/>
8. </head>
9. <body>
10. <formmethod="POST"class="post-form"action="/update/
{{[Link]}}">
11. {%csrf_token%}
12. <divclass="container">
13. <br>
14. <divclass="form-grouprow">
15. <labelclass="col-sm-1col-form-label"></label>
16. <divclass="col-sm-4">
17. <h3>UpdateDetails</h3>
18. </div>
19. </div>
20. <divclass="form-grouprow">
21. <labelclass="col-sm-2col-form-label">EmployeeId:</
label
>
22. <divclass="col-sm-4">
23. <inputtype="text"name="eid"id="id_eid"required
maxlength="20"value="{{[Link]}}"/>
24. </div>
25. </div>
26. <divclass="form-grouprow">
27. <labelclass="col-sm-2col-form-
label">EmployeeName:</label>
28. <divclass="col-sm-4">
29. <inputtype="text"name="ename"id="id_ename"r
equiredmaxlength="100"value="{{[Link]}}"/
>
30. </div>
31. </div>
32. <divclass="form-grouprow">
Downloaded by CHAITANYA B
33. <labelclass="col-sm-2col-form-
label">EmployeeEmail:</label>
34. <divclass="col-sm-4">
35. <inputtype="email"name="eemail"id="id_eemail"
requiredmaxlength="254"value="{{[Link]}}"
/>
36. </div>
37. </div>
38. <divclass="form-grouprow">
39. <labelclass="col-sm-2col-form-
label">EmployeeContact:<
/label>
40. <divclass="col-sm-4">
41. <inputtype="text"name="econtact"id="id_econta
ct"requiredmaxlength="15"value="{{[Link]
}}"/>
42. </div>
43. </div>
44. <divclass="form-grouprow">
45. <labelclass="col-sm-1col-form-label"></label>
46. <divclass="col-sm-4">
47. <buttontype="submit"class="btn
btn-success">Update</button>
48. </div>
49. </div>
50. </div>
51. </form>
52. </body>
53. </html>
12. CreateMigrations
Createmigrationsforthecreatedmodelemployee,usethefollowingcomma
nd.
1. $[Link]
Downloaded by CHAITANYA B
Aftermigrations,executeonemorecommandtoreflectthemigrationin
[Link],mentionnameofapp(employee)inINSTA
LLED_APPSofsettings.pyfile.
//[Link]
1. INSTALLED_APPS=[
2. '[Link]',
3. '[Link]',
4. '[Link]',
5. '[Link]',
6. '[Link]',
7. '[Link]',
8. 'employee'
9.]
Runthecommandtomigratethemigrations.
1.$[Link]
Downloaded by CHAITANYA B
Now,ourapplicationhassuccessfullyconnectedandcreatedtablesind
atabase.Itcreates10defaulttablesforhandlingproject(session,authe
nticationetc)andonetableofourmodelthatwecreated.
Seelistoftablescreatedaftermigratecommand.
RunServer
Torunserverusethefollowingcommand.
1.$[Link]
Downloaded by CHAITANYA B
AccesstotheBrowser
Accesstheapplicationbyenteringlocalhost:8000/
show,itwillshowalltheavailableemployeerecords.
Initially,[Link],itshowsnorecordmessage.
AddingRecord
[Link].
Downloaded by CHAITANYA B
Fillingthedetails.
Downloaded by CHAITANYA B
6. Create an xml for the bookstore. Validate the same using both DTD
and XSD
<[Link]>
<!ELEMENT books (book+)>
<!ELEMENT book (title,author,ISBN,publisher,edition,price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT ISBN (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT edition (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<[Link]>
<?xml version="1.0"?>
<!DOCTYPE books SYSTEM "[Link]">
<?xml:stylesheet type="text/xsl" href="[Link]"?>
<books>
<book>
<title>Web programming, building internet applications</title>
<author>Chris Bates</author>
<ISBN>0-07-049543-7</ISBN>
<publisher>Wiley Dreamtech</publisher>
<edition>2nd edition</edition>
<price>Rs.250</price>
</book>
<book>
<title>Computer Networks</title>
<author>Andrew S Tanebaum</author>
<ISBN>81-203-1165-5</ISBN>
<publisher>Pearson</publisher>
<edition>2nd edition</edition>
<price>Rs.350</price>
</book>
<book>
<title>Frontiers of Electronic commerce</title>
<author>Kalakata</author>
<ISBN>978-81-265-1173-0</ISBN>
<publisher>Pearson</publisher>
<edition>1st edition</edition>
<price>Rs.350</price>
</book>
<book>
<title>Java Programming with CORBA</title>
<author>[Link]</author>
<ISBN>978-81-265-1173-0</ISBN>
<publisher>Wiley Dreamtech</publisher>
<edition>2nd edition</edition>
Downloaded by CHAITANYA B
<price>Rs.250</price>
</book>
<book>
<title>The Unified Modelling language User Guide</title>
<author>Grady Booch, James Rumbaugh, Ivar Jacabson</author>
<ISBN>81-7758-372-7</ISBN>
<publisher>Perarson Education</publisher>
<edition>2nd edition</edition>
<price>Rs.400</price>
</book>
<book>
<title>Data mining-Concepts and techniques</title>
<author>JiaweiH Anand Kamber</author>
<ISBN>978-81-312-0538-8</ISBN>
<publisher>Pearson</publisher>
<edition>1st edition</edition>
<price>Rs.550</price>
</book>
</books>
<[Link]>
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="[Link]
version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<body>
<table align="center" cellspacing="5"cellpadding="10">
<caption>BOOKS INFORMATION</caption>
<tr bgcolor="light brown">
<th>Title</th>
<th>Author</th>
<th>ISBN</th>
<th>Publisher</th>
<th>Edition</th>
<th>Price</th>
</tr>
<xsl:for-each select="books/book">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
<td><xsl:value-of select="ISBN"/></td>
<td><xsl:value-of select="publisher"/></td>
<td><xsl:value-of select="edition"/></td>
<td><xsl:value-of select="price"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
Downloaded by CHAITANYA B
</xsl:stylesheet>
Output:
Designacontrollerwithservletthatprovidestheinteractionwithapplicationdevelopedinexperiment1andthedata
basecreatedinexperiment5.
Mysqldatabase
Procedure:
[Link]:
<html>
<head>
<title>validation</title>
</head>
<bodybgcolor="magenta">
<formaction="[Link]"method="post">
Downloaded by CHAITANYA B
<h1align="center">REGISTRATIONFORM</h1>
<tableborder="0">
<tr>
<td>Name:</td>
<td><inputtype="text"name="t1"minlength="6"></td>
</tr>
<tr>
<td>Password:</td>
<td><inputtype="password"name="t2"></td>
</tr>
<tr>
<td>Phonenumber:</td>
<td><inputtype="text"name="t3"></td>
</tr>
<tr>
<td>E-mailid:</td>
<td><inputtype="text"name="t4"></td>
</tr>
<tr>
<td><inputtype="submit"value="submit"></td>
<td><inputtype="reset"value="cancel"></td>
</tr>
</table>
</form>
</body>
</html>
Downloaded by CHAITANYA B
[Link]:
<%@pagelanguage="java"import="[Link].*,[Link].*"%>
<html>
<form>
<%
String v1,v2,v3,v4,str;
v1=[Link]("t1");
v2=[Link]("t2");
v3=[Link]("t3");
v4=[Link]("t4");
try{
[Link]("[Link]");
Connection cn=[Link]("jdbc:odbc:oradsn","system","ravindra");
Statement st=[Link]();
[Link]("insertintoregistervalues('"+v1+"','"+v2+"',"+v3+",'"+v4+"')"); if(cn!
=null)
{
%>
</form>
RegistrationSuccessful
<%
}
else
{
[Link]("Registrationfailed");
}
[Link]();
[Link]();
}catch(Exceptione){[Link]("Registrationfailed");
%>
<P><ahref="[Link]"target=f2><B>Back<B></a>
<%
}
%>
</body></html>
Execution:
Createatablewithnameregisterwithname(varchar2(10)),password(varchar2(10)),
Phone(number (10)) ,Email-ID (varchar2(10)).
CreatetheDatasource name.
Start->settings->controlpanel->AdministrativeTools->DataSources.
Under SystemDSN add Microsoft ODBC for Oracle.
SetDataSourcenameto oradsn.
Output:1
Downloaded by CHAITANYA B
Output:2
Downloaded by CHAITANYA B
7. [Link]
sessiontracking mechanism (Cookies, HTTP Session)
[Link];impo
[Link];
[Link];
[Link];imp
[Link];importjav
[Link];importjava
[Link];
[Link];
[Link];i
[Link];i
[Link];
/**
*ServletimplementationclassLoginServlet
*/@WebServlet("/
LoginServlet")
publicclassLoginServletextendsHttpServlet{privatesta
ticfinallongserialVersionUID=1L;privatefinalS
tringuserID="admin";
privatefinalStringpassword="password";
protectedvoiddoPost(HttpServletRequestrequest,
HttpServletResponseresponse)throwsServletException,IOException{
Downloaded by CHAITANYA B
//
getrequestparametersforuserIDandpasswordStrin
guser=[Link]("user");Stringpwd=
[Link]("pwd");
if([Link](user)&&[Link](pwd))
{HttpSessionsession=[Link]();[Link]
tAttribute("user","Pankaj");
//
[Link]
nactiveInterval(30*60);CookieuserName=new
Cookie("user",user);[Link](30
*60);[Link](userName);response.
sendRedirect("[Link]");
}else{
RequestDispatcherrd=
getServletContext().getRequestDispatcher("/[Link]");
PrintWriterout=[Link]();
[Link]("<fontcolor=red>Eitherusernameorpasswordis
wrong.</font>");
[Link](request,response);
}
[Link].
<%@pagelanguage="java"contentType="text/html;charset=US-
ASCII"pageEncoding="US-ASCII"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""https://
[Link]/TR/html4/[Link]">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=US-ASCII">
<title>LoginSuccessPage</title>
</head>
<body>
<%
//
allowaccessonlyifsessionexistsStringuse
r=null;if([Link]("user")=
=null){
[Link]("[Link]");
}elseuser=(String)[Link]("user");String
userName=null;
StringsessionID=null;
Cookie[]cookies=[Link]();if(coo
kies!=null){
for(Cookiecookie:cookies){
if([Link]().equals("user"))userName=[Link]();if(cookie.
Downloaded by CHAITANYA B
getName().equals("JSESSIONID"))sessionID=[Link]();
Downloaded by CHAITANYA B
}
}
%>
<h3>Hi<%=userName%>,[Link]=<%=sessionID%></h3>
<br>User=<
%=user%>
<br>
<ahref="[Link]">CheckoutPage</a>
<formaction="LogoutServlet"method="post">
<inputtype="submit"value="Logout">
</form>
</body>
</html>
WhenaJSPresourceisused,containerautomaticallycreatesasessionforit,sowecan’tcheckifsession
isnulltomakesureifuserhascomethroughloginpage,soweareusingsessionattributetovalidaterequ
[Link]’scodeisgivenbelow.
<%@pagelanguage="java"contentType="text/html;charset=US-
ASCII"pageEncoding="US-ASCII"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""https://
[Link]/TR/html4/[Link]">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=US-ASCII">
<title>LoginSuccessPage</title>
</head>
<body>
<%
//
allowaccessonlyifsessionexistsif([Link]
ttribute("user")==null){
[Link]("[Link]");
}
StringuserName=null;Stri
ngsessionID=null;
Cookie[]cookies=[Link]();if(coo
kies!=null){
for(Cookiecookie:cookies){
if([Link]().equals("user"))userName=[Link]();
}
}
%>
<h3>Hi<%=userName%>,dothecheckout.</h3>
<br>
<formaction="LogoutServlet"method="post">
<inputtype="submit"value="Logout">
</form>
</body>
</html>
[Link]
[Link];
Downloaded by CHAITANYA B
[Link];
[Link];impor
[Link];import
[Link];
[Link];
[Link];i
[Link];i
[Link];
/**
*ServletimplementationclassLogoutServlet
*/@WebServlet("/
LogoutServlet")
publicclassLogoutServletextendsHttpServlet{privatest
aticfinallongserialVersionUID=1L;
protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletExce
ption,IOException{
[Link]("text/
html");Cookie[]cookies=[Link]();i
f(cookies!=null){
for(Cookiecookie:cookies)
{if([Link]().equals("JSESSIONID")){
[Link]("JSESSIONID="+[Link]());brea
k;
}
}
}
//invalidatethesessionifexists
HttpSessionsession=[Link](false);[Link]("
User="+[Link]("user"));if(session!=null){
[Link]();
}
[Link]("[Link]");
}
Downloaded by CHAITANYA B
[Link].
8. CreateacustomserverusinghttpmoduleandexploretheothermodulesofNodeJSlikeOS,path
,event.
[Link]()methodincludesrequestandresponsepara
[Link]
getinformationaboutthecurrentHTTPrequeste.g.,url,requesthea
der,[Link]
currentHTTPrequest.
ThefollowingexampledemonstrateshandlingHTTPrequestandrespo
[Link].
varhttp=require('http');//[Link]
varserver=[Link](function(req,res){//createwebserver
if([Link]=='/'){//checktheURLofthecurrentrequest
//setresponseheader
[Link](200,{'Content-Type':'text/html'});
Downloaded by CHAITANYA B
//setresponsecontent
[Link]('<html><body><p>This is home
Page.</p></body></
html>');[Link]();
}
elseif([Link]=="/student"){
[Link](200,{'Content-Type':'text/html'});
[Link]('<html><body><p>This is
studentPage.</p></body></html>');
[Link]();
}
elseif([Link]=="/admin"){
[Link](200,{'Content-Type':'text/html'});
[Link]('<html><body><p>This is admin
Page.</p></body></
html>');[Link]();
}
else
[Link]('InvalidRequest!');
});
[Link](5000);//6-
[Link]('[Link]
ratport5000isrunning..')
Now,runtheabovewebserverasshownbelow.
C:\>[Link]
Node.jswebserveratport5000isrunning..
Totestit,youcanusethecommand-
lineprogramcurl,whichmostMacandLinuxmachineshavepre-
installed.
curl-i[Link]
Downloaded by CHAITANYA B
Youshouldseethefollowingresponse.
Downloaded by CHAITANYA B
HTTP/1.1200OK
Content-Type:text/plain
Date:Tue,8Sep20[Link]GMT
Connection:keep-
aliveThisishomepage
ForWindowsusers,pointyourbrowsertohttp://
localhost:5000andseethefollowingresult.
[Link]
9. DevelopanexpresswebapplicationthatcaninteractwithREST APItoperform14
CRUDoperations on student data. (Use Postman)
#1)Installations.
#2)[Link]
.js#3)CRUDOperationsandHTTPmethods.
#4)TestingAPIwithPostman.
InstallationRequired
Downloaded by CHAITANYA B
• [Link](NodePackageManager)
• VSCode(Optional)—Acodeeditor.
[Link]
er,openyourterminalorCMDandrunnode-
[Link]'sinstalled.
Otherwisegototheselinksandinstall:
→[Link](YoushouldchooseLTSve
rsion).
→ClickheretodownloadVSCode
Expressapplicationgenerator:
[Link]
ationgeneratortool(`express-
generator`).Theapplicationgeneratorusesnpxcommand(avail
[Link]).
→ClickheretoknowmoreaboutExpressapplicationgenerator.
Wewillnotuseexpress-
generatorinthisarticle,insteadwewillcreateeverythingbyoursel
ftoavoidextrafilesgeneratedfromgeneratorandtounderstandi
ndepth.
#2)CreateNewProject([Link])
Createanewfolder(attheplaceyouwanttokeepyourproject).N
amethatfolder:node-ex-api
Downloaded by CHAITANYA B
Createtwofilesinsidenode-ex-apifolder:
→[Link].
→[Link].
Openupandupdateyournode-ex-api/
[Link]:
{
"name":"node-ex-api",
"version":"1.0.0","scripts
":{
"start":"[Link]"
},
"dependencies":
{"express":"^4.17.1"
}
}
Openupandupdateyournode-ex-api/[Link]:
consthttp=require('http');constexpress=require('express');
constapp=express();[Link]([Link]());
//[Link]('/',function(req,res){
[Link]('node-ex-apiworks:-)');
});
constserver=[Link](app);constport=3000;[Link](port);
[Link]('Serverlisteningonport'+port);
Aftercreatingabovetwofiles,openyourterminalinthe"node-ex-
api"folderandrunthiscommand:
npminstall
Downloaded by CHAITANYA B
Thiscommand↑willinstallthedependenciesdefin
edin"[Link]"file.
(YoumayuseVSCode-Acodeeditor↓).
Afterdependencyinstallationthiswillcreate"node_modules"folde
rattherootofthe"node-ex-api"folder.
RunProject
WehavejustcreatedaNode-
ExpressProjectLet’[Link]
mand:
npmstart
Downloaded by CHAITANYA B
TotestthisAPI—OpenyourwebbrowserandenterthisURL
→localhost:3000
Thelocalhost:[Link]
simplestring“node-ex-apiworks:-)”
CRUDOperationsandHTTPmethods.
Yetwehavealistofitems(localhost:3000/
items).[Link]
UD
operationsCreate,Read,UpdateandDeleteoverthelistofitems.
[Link]('/',..............)
→localhost:3000/items(Withpostrequest)
ForReadwealreadyhavetwoend-points:
→localhost:3000/items(Returnsallobjects)
→localhost:3000/items/1(Returnssingleobjectofid=1)
[Link]('/',..............)
→localhost:3000/items(Withputrequest)
[Link]('/',..............)
→localhost:3000/items(Withdeleterequest)
Now,Openupandupdateyournode-ex-api/routes/
Downloaded by CHAITANYA B
[Link]:(HTTPmethods ↓↓)
Downloaded by CHAITANYA B
Importantexplanationaboutabove↑code:
→WeworkedonstaticarrayofJSONobjectsnamed:data.
→AllHTTPmethodsGET,POST,PUTandDELETEarejust
manipulatingthisJSONarray.
→Feelfreetouseanydatabaseinsteadofusinglocalstaticarray.
ThedatabasecodecanbewritteninsidetheseHTTPmethodstod
ooperationslikeGET,POST,PUTandDELETE.
TestingAPIwithPostman.
WehavetestedtheGETmethodsofourAPIinourwebbrowser
(check#4)[Link]’ttestPOST,PUTa
[Link]
dsweusePostmanoryoumayuseanotherhttputilitytocallAP
Is.
[Link].
Now,runnpmstartifyourserverisnotrunning.
AfterPostmaninstallationskipstartwindow(ifcomes),thenlogi
nwithGoogleoremail/
password(whicheveryouprefer)andfinallyyoumustseethisscr
een:
Downloaded by CHAITANYA B
10. FortheaboveapplicationcreateauthorizedendpointsusingJWT(JSONWebToken).
CreateAPIendpoints
Ourdefaultendpointreturnsstring—
[Link]’llcreateanotherAPIendpoint,thatisa
notherURLwhichreturnssomeusefuldata.
Beforeproceed,let’sdosomemoreexercise:
→Createafolderinsidetheprojectrootwithname"routes".
→Thencreateafileinsidethis"routes"folderwithname"[Link]".
Next,Openupandupdateyournode-ex-api/routes/
[Link]:
//
importrequiredessentialsconstexpr
Downloaded by CHAITANYA B
//createnewrouter
constrouter=[Link]();
//
createaJSONdataarrayletdat
a=[
{id:1,title:'Createaproject',
order:1,completed:true,createdOn:newDate()},
{id:2,title:'Takeacofféé',
order:2,completed:true,createdOn:newDate()},
{id:3,title:'Writenewarticle',order:3,completed:true,create
dOn:newDate()},
{id:4,title:'Walktowardhome',order:4,completed:false,create
dOn:newDate()},
{id:5,title:'Havesomedinner',order:5,completed:false,create
dOn:newDate()},
];
//thisend-
[Link]('/',function(
req,res){
[Link](200).json(data);
});
//thisend-pointreturnsanobjectfromadataarrayfindbyid
//weget`id`fromURLend-
[Link]('/:id',function(req,res){
//
findanobjectfrom`data`arraymatchby`id`letfound=da
[Link](function(item){
[Link]===parseInt([Link]);
});
//ifobjectfoundreturnanobjectelsereturn404not-
foundif(found){
[Link](200).json(found);
}else{
[Link](404);
}
});
[Link]=router;
□Seebelow↓↓
Downloaded by CHAITANYA B
RegisterAPIendpoints
Let’sregisteritinthe"[Link]"filetomakeuseofnewendpoints.
DonotforgettoinstallCORS.
Openyourterminalinthe"node-ex-
api"folderandrunthiscommand:
npminstallcors
Now,openupyournode-ex-api/
[Link]:
//
importrequiredessentialsconsthttp
=require('http');constexpress=requ
ire('express');
varcors=require('cors');//
import`items`from`routes`folderconstitemsRouter=require('./
routes/items');
//
createnewappconstapp=
Downloaded by CHAITANYA B
//allowingbelowURLtoaccesstheseAPIsend-points
//youcanreplacethisURL([Link]
//
[Link](cors({origi
n:'[Link]
/*this'/items'URLwillhavetwoend-points:
→localhost:3000/items/(thisreturnsarrayofobjects)
→localhost:3000/items/:id(thisreturnssingleobject)
*/
[Link]('/items',itemsRouter);
//
[Link]('/',func
tion(req,res){
[Link]('node-ex-apiworks:-)');
});
constserver=[Link](app);c
onstport=3000;[Link](port);
□Seebelow↓↓
The"[Link]"and"[Link]"filewilllooklikethis↑
RunAPIendpoints
Downloaded by CHAITANYA B
Now,[Link]
reeend-points:
→localhost:3000(Default)
→localhost:3000/items(Returnsallobjects)
→localhost:3000/items/1(Returnssingleobjectofid=1)
□Seebrowserbelow↓
ClickimageIfyoucan’tseethis.
11. Createareactapplicationforthestudentmanagementsystemhavingregistration,login,contact,a
boutpagesandimplementroutingtonavigatethroughthesepages.
Createtheprojectfoldercontainingtwosub-
foldersnamedclientandserver.
mkdirauth-
systemcdauth-
systemmkdirclie
ntserver
[Link].
cdserver&npminit-y
[Link],CORS,andNodemon.
npminstallexpresscorsnodemon
Downloaded by CHAITANYA B
[Link],minimalistframeworkthatprovi
desseveralfeaturesforbuildingwebapplicationsin
[Link]
[Link]
[Link]
detectingfilechanges.
[Link]-theentrypointtothewebserver.
[Link]
[Link]:
constexpress=require("expres
s");constcors=require("cors");
constapp=express()
;constPORT=4000;
[Link]([Link]({extended:true}));[Link]
([Link]());
[Link](cors());
[Link]("/api",
(req,res)=>{[Link]({messa
ge:"Helloworld"});
});
[Link](PORT,()=>{
[Link](`Serverlisteningon${PORT}`);
});
Buildingtheappuserinterface
Inthissection,we'llbuildtheuserinterfacefortheapplica
tionallowinguserstoregisterandsignintoanapplication.
Userscancreateanaccount,login,andperform2FAviaS
MSbeforetheyareauthorisedtoviewthedashboard.
[Link].
cdclient
npxcreate-react-app./
Downloaded by CHAITANYA B
Deletetheredundantfilessuchasthelogoandthetestfile
sfromtheReactapp,[Link]
lloWorldasbelow.
functionApp()
{return(
<div>
<p>HelloWorld!</p>
</div>
);
}
exportdefaultApp;
Navigateintothesrc/
[Link]
uiredforstylingthisproject.
@importurl("[Link]
family=Space+Grotesk:wght@300;400;500;600;700&display=swap");
*{
box-sizing:border-
box;margin:0;
padding:0;
font-family:"SpaceGrotesk",sans-serif;
}
input{
height:45px;paddi
ng:10px15px;mar
gin-bottom:15px;
}
button{
width:200px
;outline:non
e;border:non
e;padding:1
5px;cursor:p
ointer;font-
size:16px;
}
.logincontainer,
.signupcontainer,
.verify,
.dashboard
{width:10
0%;
min-
height:100vh;pad
ding:50px70px;dis
play:flex;
flex-
direction:column;ali
gn-
items:center;justify
Downloaded by CHAITANYA B
-content:center;
Downloaded by CHAITANYA B
}
.loginform,
.verifyform,
.signupform
{width:10
0%;displa
y:flex;
flex-direction:column;
}
.loginBtn,
.signupBtn,
.codeBtn{
background-
color:green;color:#fff;
margin-bottom:15px;
}
.signOutBtn{
background-
color:#c21010;color:#fff;
}
.link{
cursor:pointer;
color:rgb(39,147,39);
}
.code{
width:50%;
text-align:center;
}
.verifyform{
align-items:center;
}
@mediascreenand(max-width:800px){
.logincontainer,
.signupcontainer,
.verify{
padding:30px;
}
}
InstallReactRouter-
aJavaScriptlibrarythatenablesustonavigatebetweenpages
inaReactapplication.
npminstallreact-router-dom
CreateacomponentsfolderwithintheReactappcontaini
[Link],[Link],[Link].
mkdircomponents
Downloaded by CHAITANYA B
cdcomponents
[Link]
[Link]
mponentsondifferentroutesviaReactRouter.
import{BrowserRouter,Route,Routes}from"react-router-
dom";importLoginfrom"./components/Login";
importSignupfrom"./components/Signup";
importDashboardfrom"./components/
Dashboard";importPhoneVerifyfrom"./
components/PhoneVerify";
functionApp()
{return(
<BrowserRouter>
<Routes>
<Routepath='/'element={<Login/>}/>
<Routepath='/register'element={<Signup/>}/>
<Routepath='/dashboard'element={<Dashboard/>}/>
<Routepath='phone/verify'element={<PhoneVerify/>}/>
</Routes>
</BrowserRouter>
);
}
exportdefaultApp;
TheLoginpage
[Link]
ilandpasswordfromtheuser.
importReact,{useState}from"react";
import{useNavigate}from"react-router-dom";
constLogin=()=>{
const[email,setEmail]=useState("");
const[password,setPassword]=useState("
");constnavigate=useNavigate();
consthandleSubmit=(e)=>
{[Link]();
[Link]({email,password});setPass
word("");
setEmail("");
};
constgotoSignUpPage=()=>navigate("/register");
Downloaded by CHAITANYA B
return(
<divclassName='logincontainer'>
<h2>Login</h2>
<formclassName='loginform'onSubmit={handleSubmit}>
<labelhtmlFor='email'>Email</label>
<input
type='text'id
='email'name
='email'value
={email}re
quired
onChange={(e)=>setEmail([Link])}
/>
<labelhtmlFor='password'>Password</label>
<input
type='password'nam
e='password'id='pass
word'minLength={8
}requiredvalue={p
assword}
onChange={(e)=>setPassword([Link])}
/>
<buttonclassName='loginBtn'>SIGNIN</button>
<p>
Don'thaveanaccount?{""}
<spanclassName='link'onClick={gotoSignUpPa
ge}>Signup
</span>
</p>
</form>
</div>
);
};
exportdefaultLogin;
Downloaded by CHAITANYA B
TheSignuppage
[Link]
ail,username,telephone,andpasswordfromtheuser.
importReact,{useState}from"react";
import{useNavigate}from"react-router-dom";
constSignup=()=>{
const[email,setEmail]=useState("");
const[username,setUsername]=useState("
");const[tel,setTel]=useState("");
const[password,setPassword]=useState("
");constnavigate=useNavigate();
consthandleSubmit=(e)=>
{[Link]();
[Link]({email,username,tel,password});
setEmail("");
setTel("");
setUsername("");
setPassword("");
};
constgotoLoginPage=()=>navigate("/");
return(
<divclassName='signupcontainer'>
<h2>Signup</h2>
Downloaded by CHAITANYA B
<formclassName='signupform'onSubmit={handleSubmit}>
<labelhtmlFor='email'>EmailAddress</label>
<input
type='email'name
='email'id='email'v
alue={email}req
uired
onChange={(e)=>setEmail([Link])}
/>
<labelhtmlFor='username'>Username</label>
<input
type='text'id='user
name'name='usern
ame'value={user
name}required
onChange={(e)=>setUsername([Link])}
/>
<labelhtmlFor='tel'>PhoneNumber</label>
<input
type='tel'
name='tel
'id='tel'va
lue={tel}
required
onChange={(e)=>setTel([Link])}
/>
<labelhtmlFor='tel'>Password</label>
<input
type='password'nam
e='password'id='pass
word'minLength={8
}requiredvalue={p
assword}
onChange={(e)=>setPassword([Link])}
/>
<buttonclassName='signupBtn'>SIGNUP</button>
<p>
Alreadyhaveanaccount?{""}
<spanclassName='link'onClick={gotoLoginPage
}>Login
</span>
</p>
</form>
</div>
);
};
Downloaded by CHAITANYA B
exportdefaultSignup;
12. Create a service in react that fetches the weather information from [Link]
and the display the current and historical weather information using graphical representation
[Link]
//PAGELOAD//
//***GETSAVEDITEMSFROMLOCALSTORAGE***//
let savedSearchArray =
[Link]([Link]('savedSearchArray'));
if(!savedSearchArray)
{ savedSearchArray = [
'Columbus',
'Bend',
'LosAngeles',
'SanFrancisco',
Downloaded by CHAITANYA B
'Savannah',
'NewYork',
'Nashville'
];
}
//DefineGlobalDateVariables
// [Link]
let time = [Link]('#time');
[Link] = moment().format('h:mm a');
let today = [Link]('#today');
[Link]=moment().format('MMMD');
//DefinevariablesforgetCurrent function
const searchBtnEl = [Link]('#search-btn');
constsearchInputEl=[Link]('#search-input');
//DefinegetCurrentfunctiontoaccesscurrentweatherconditions
function getCurrent(searchInputEl) {
//CurrentWeatherDataAPIcall
const currentWeatherUrl =
'[Link]
'&units=imperial&appid=c6a9bf78cf3b504fe7e8382ca53765c4';
fetch(currentWeatherUrl).then(function(response)
{ if ([Link]) {
[Link]().then(function(data){
[Link](data)
Downloaded by CHAITANYA B
//Append datafromAPItoDOM
constcityName=[Link]('#city-name');
[Link] = [Link];
constdescription=[Link]('#desc');
[Link] = [Link][0].main;
consthumidity=[Link]('#current-humid');
[Link]='Humidity:'+[Link]+
` %`;
//accessuvindexfromonecallused for5dayforecast
})
}
})
};
//definefunctiontoget5dayforecast//accesslatandlonfromprevious function
//useonecallAPIinsteadof5dayforecast//betteraccessibilitytoneeded information
functiongetForecast(latitude,longitude){
constforecastUrl='[Link]
+latitude+'&lon='+longitude+
Downloaded by CHAITANYA B
'&units=imperial&exclude=hourly,minutely&appid=c6a9bf78cf3b504fe7e8
382ca53765c4';
fetch(forecastUrl).then(function(response){ if
([Link]) {
[Link]().then(function(data){
[Link](data)
//appenduvdatatocurrentconditionsdiv
constuvIndex=[Link]('#current_uv');
[Link] = 'UV Index: ' + [Link];
//Rendericonsforeach dayinforecast
//Note:Mustuse<img>[Link] set the
img src
consticon1=[Link]('#icon1');
const icon1Call = [Link][1].weather[0].icon;
[Link]('src','[Link]
+icon1Call+'@[Link]');
consticon2=[Link]('#icon2');
const icon2Call = [Link][2].weather[0].icon;
[Link]('src','[Link]
+icon2Call+'@[Link]');
consticon3=[Link]('#icon3');
const icon3Call = [Link][3].weather[0].icon;
[Link]('src','[Link]
+icon3Call+'@[Link]');
consticon4=[Link]('#icon4');
const icon4Call = [Link][4].weather[0].icon;
[Link]('src','[Link]
+icon4Call+'@[Link]');
consticon5=[Link]('#icon5');
const icon5Call = [Link][5].weather[0].icon;
[Link]('src','[Link]
+icon5Call+'@[Link]');
Downloaded by CHAITANYA B
//descriptionforecast
//TODO:forloop
const desc1 = [Link]('#desc_1');
[Link]=([Link][1].weather[0].main);
const desc2 = [Link]('#desc_2');
[Link]=([Link][2].weather[0].main);
const desc3 = [Link]('#desc_3');
[Link]=([Link][3].weather[0].main);
const desc4 = [Link]('#desc_4');
[Link]=([Link][4].weather[0].main);
const desc5 = [Link]('#desc_5');
[Link]=([Link][5].weather[0].main);
//temp forecast
//TODOforloop
//for(i=0;i<[Link]; i++)
const temp1 = [Link]('#temp_1');
[Link]=[Link]([Link][1].[Link])+
`º`;
const temp2 = [Link]('#temp_2');
[Link]=[Link]([Link][2].[Link])+
`º`;
const temp3 = [Link]('#temp_3');
[Link]=[Link]([Link][3].[Link])+
`º`;
const temp4 = [Link]('#temp_4');
[Link]=[Link]([Link][4].[Link])+
`º`;
const temp5 = [Link]('#temp_5');
[Link]=[Link]([Link][5].[Link])+
`º`;
//humidity forecast
//TODOforloop
//for(i=0;i<[Link]; i++)
const humid1 = [Link]('#humid_1');
[Link]=([Link][1].humidity)+`%`;
const humid2 = [Link]('#humid_2');
[Link]=([Link][2].humidity)+`%`;
const humid3 = [Link]('#humid_3');
[Link]=([Link][3].humidity)+`%`;
const humid4 = [Link]('#humid_4');
Downloaded by CHAITANYA B
[Link]=([Link][4].humidity)+`%`;
const humid5 = [Link]('#humid_5');
[Link]=([Link][5].humidity)+`%`;
})
}
})
};
//selecteachsearchhistorylistitem
const searchHistCon = [Link]('#search-history-list')
constsearchedItemEl=[Link]('[Link]-history-
item');
[Link](searchedItemEl);
//definefunctiontorendersearchhistory
function renderSearchHistory() {
//clear previous selection before appending
for(i=0;i<[Link];i++){
constnewSearchedItem=[Link]('li');
[Link]('search-history-item');
[Link] = savedSearchArray[i];
[Link]('click',function(event)
{ let newUserInput = [Link];
getCurrent(newUserInput);
})
}
}
//addevent listenertosearchbutton
Downloaded by CHAITANYA B
[Link]('click',function(event){
[Link]();
//useeventtoaccessuserinput
[Link](event);
letuserInput=[Link]; getCurrent(userInput);
//TODO:ifstatementtocheckedgecasesofmisspelledcities,etc
[Link](userInput);
//callfunctiontorendersearchhistorywithinthisfunctionforaccessto needed
variables
renderSearchHistory();
[Link]('savedSearchArray',
[Link](savedSearchArray));
});
constsearchHistoryMenuLi=[Link]('#search-hist-menu-
li');
[Link]('click',renderSearchHistory());
getCurrent('Columbus');
[Link]
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width,initial-
scale=1.0">
Downloaded by CHAITANYA B
<metahttp-equiv="X-UA-Compatible"content="ie=edge"/>
<link
href="[Link]
" rel="stylesheet" integrity="sha384-
EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65Vohhpuu
COmLASjC" crossorigin="anonymous">
<link
rel="stylesheet"href="[Link]
css/[Link]"
integrity="sha384-
50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhn
dOJK28anvf" crossorigin="anonymous" />
<linkrel="preconnect"href="[Link]
<linkrel="preconnect"href="[Link]
<link href="[Link]
family=Josefin+Sans:ital,wght@0,100;0,200;0,300;0,400;0,500;1,100;1,200
;1,300;1,400&family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;
0,600;0,700;0,800;0,900;1,100;1,200;1,300&family=Noto+Sans:ital,wght@
0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300&
family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,80
0;0,900;1,100;1,200;1,300&family=Roboto:ital,wght@0,100;0,300;0,400;0,
500;0,700;0,900;1,100;1,300;1,400&family=Rubik+80s+Fade&family=Sour
ce+Sans+Pro:wght@300&display=swap" rel="stylesheet">
<linkrel="stylesheet"href="assets/css/[Link]"/>
<linkrel="stylesheet"href="assets/css/[Link]"/>
<linkrel="stylesheet"href="assets/css/[Link]"/>
<title>CurrentWeather</title>
</head>
<body>
<divclass="navbar">
<!--Dropdownmenu-->
<navclass="btn-groupdropend">
<buttontype="button"class="btndropdown-toggle"data-bs-
toggle="dropdown" aria-expanded="false"></button>
<ulclass="dropdown-menu"id="popout-menu">
<liclass="nav-itemdropdown-item"id="search-box-
txt">Search
<formclass="activesearch-form"aria-current="page"
href="#">
<divclass="input-group">
Downloaded by CHAITANYA B
<inputtype="text"class="input"id="search-input">
<divclass="input-group-div"id="search-btn-group">
<buttonclass="btnbtn-default"id="search-btn"
type="submit">
<iclass="fasfa-search"id="search-icon"></i>
</button>
</div>
</div>
</form>
</li>
<liid="search-hist-menu-li"class="nav-itemdropdown-item">
History
<ulid="search-history-list">
<!--appendsearchhistoryinscript-->
</ul>
</li>
<!--<liclass="nav-itemdropdown-item">Starred
<ulid="favorites-list">-->
<!--appendsearchhistoryinscript-->
<!--</ul>
</li>-->
</ul>
</nav>
</div>
<mainclass="d-flexflex-columngy-2">
<!--CurrentWeatherDisplay-->
<divclass="container"id="current-conditions">
<divclass="d-flexflex-columnalign-items-center">
<divclass="" id="time"></div>
<divclass="" id="today"></div>
<divclass="display-1"id="current-temp"></div>
<divclass="current-icon-wrapper">
<divclass="leadtext-muted"id="desc"></div>
<imgclass="display-1"id="current-icon"/>
</div>
</div>
Downloaded by CHAITANYA B
<divclass="hidden">
<divclass=""id="current-humid"></div>
<divclass=""id="current_wind">WindSpeed:</div>
<divclass=""id="current_uv">UVIndex:</div>
</div>
</div>
<!--ForecastCardContainer-->
<divclass="forecast-content-wrappercontainerd-flexflex-row
justify-content-center" id="week-forecast">
<divclass="forecast-card">
<divclass="day"id="date_1"></div>
<divclass="temperature"id="temp_1"></div>
<divclass="description"id="desc_1"></div>
<imgclass="weather-icon"alt="weather-
icon"id="icon1"></img>
<divclass="humidity"id="humid_1"></div>
</div>
<divclass="forecast-card">
<divclass="day"id="date_2"></div>
<divclass="temperature"id="temp_2"></div>
<divclass="description"id="desc_2"></div>
<imgclass="weather-icon"alt="weather-
icon"id="icon2"></img>
<divclass="humidity"id="humid_2"></div>
</div>
<divclass="forecast-card">
<divclass="day"id="date_3"></div>
<divclass="temperature"id="temp_3"></div>
<divclass="description"id="desc_3"></div>
Downloaded by CHAITANYA B
<imgclass="weather-icon"alt="weather-
icon"id="icon3"></img>
<divclass="humidity"id="humid_3"></div>
</div>
<divclass="forecast-card">
<divclass="day"id="date_4"></div>
<divclass="temperature"id="temp_4"></div>
<divclass="description"id="desc_4"></div>
<imgclass="weather-icon"alt="weather-
icon"id="icon4"></img>
<divclass="humidity"id="humid_4"></div>
</div>
<divclass="forecast-card">
<divclass="day"id="date_5"></div>
<divclass="temperature"id="temp_5"></div>
<divclass="description"id="desc_5"></div>
<imgclass="weather-icon"alt="weather-
icon"id="icon5"></img>
<divclass="humidity"id="humid_5"></div>
</div>
</div>
<divclass="text-mutedcontainer"id="city-name">Searcha City</div>
</main>
<script
src="[Link]
[Link]" integrity="sha384-
MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcX
n/tWtIaxVXM" crossorigin="anonymous"></script>
Downloaded by CHAITANYA B
<script
src="[Link]
pt>
<script
src="[Link]
"></script>
<scriptsrc="assets/[Link]"></script>
</body>
</html>
13. CreateaTODOapplicationinreactwithnecessarycomponentsanddepl
oyitintogithub.
<!
DOCTYP
E
html> <htmllang="en">
<head>
<metacharset="utf-8"/>
<linkrel="icon"href="%PUBLIC_URL%/[Link]"/>
<metaname="viewport"content="width=device-width,initial-scale=1"/>
<metaname="theme-color"content="#000000"/>
<meta
name="description"
content="Websitecreatedusingcreate-react-app"
Downloaded by CHAITANYA B
/>
<linkrel="apple-touch-icon"href="%PUBLIC_URL%/[Link]"/>
<!--
[Link]'s
[Link]
[Link]
-->
<linkrel="manifest"href="%PUBLIC_URL%/[Link]"/>
<!--
Noticetheuseof%PUBLIC_URL%inthetagsabove.
ItwillbereplacedwiththeURLofthe`public`[Link]
esinsidethe`public`[Link]"/
[Link]"or"[Link]","%PUBLIC_URL%/
[Link]"willworkcorrectlybothwithclient-sideroutingandanon-
[Link]-
rootpublicURLbyrunning`npmrunbuild`.
-->
<title>TodoList</title>
</head>
<body>
<noscript>YouneedtoenableJavaScripttorunthisapp.</noscript>
<divid="root"></div>
<!--
ThisHTMLfileisatemplate.
Ifyouopenitdirectlyinthebrowser,[Link]
dwebfonts,metatags,oranalyticstothisfile.
Thebuildstepwillplacethebundledscriptsintothe<body>[Link]
ginthedevelopment,run`npmstart`or`yarnstart`.
Tocreateaproductionbundle,use`npmrunbuild`or`yarnbuild`.
-->
</body>
</html>
[Link]:-
import
Reactf
rom"re
act"
;
import"./[Link]";
import{Button,Card,Form}from'react-
bootstrap';import'bootstrap/dist/css/
[Link]';
Downloaded by CHAITANYA B
functionTodo({todo,index,markTodo,removeTodo})
{return(
<div
className="todo"
>
<spanstyle={{textDecoration:[Link]?"line-through":
""}}>{[Link]}</span>
<div>
<Buttonvariant="outline-
success"onClick={()=>markTodo(index)}>✓</Button>{''}
<Buttonvariant="outline-
danger"onClick={()=>removeTodo(index)}>✕</Button>
</div>
</div>
);
}
functionFormTodo({addTodo}){
const[value,setValue]=[Link]("");
consthandleSubmit=e=>{[Link]
ventDefault();
if(!
value)return;addTodo(v
alue);setValue("");
};
return(
<FormonSubmit={handleSubmit}>
<[Link]>
<[Link]><b>AddTodo</b></[Link]>
<[Link]="text"className="input"value={value}onChange={e=>setValu
e([Link])}placeholder="Addnewtodo"/>
</[Link]>
<Buttonvariant="primarymb-
3"type="submit">Submit
</Button>
Downloaded by CHAITANYA B
</Form>
);
}
functionApp(){
const[todos,setTodos]=[Link]([
{
text:"Thisisasampetodo",isDone:
false
}
]);
constaddTodo=text=>{
constnewTodos=[...todos,
{text}];setTodos(newTodos);
};
constmarkTodo=index=>{constne
wTodos=[...todos];newTodos[
index].isDone=true;setTodos
(newTodos);
};
constremoveTodo=index=>{const
newTodos=[...todos];newTodo
[Link](index,1);setTodos(
newTodos);
};
return(
<divclassName="app">
<divclassName="container">
<h1className="text-centermb-4">TodoList</h1>
<FormTodoaddTodo={addTodo}/>
<div>
{[Link]((todo,index)=>(
<Card>
Downloaded by CHAITANYA B
<[Link]>
<Todokey={ind
ex}index={ind
ex}todo={todo
}
markTodo={markTodo}removeTodo={rem
oveTodo}
/>
</[Link]>
</Card>
))}
</div>
</div>
</div>
);
}
exportdefaultApp;
1. React:ApopularJavaScriptlibrarydevelopedbyFacebookw
hichisusedtocreateandhandleflexiblecomponentsfortheuseri
nterface.
2. Git:Anamazingopen-
sourceversioncontrolsystemtohandlesmallandlargeprojec
[Link]
Downloaded by CHAITANYA B
developersandtokeeptrackofchangesinsourcecodeduringsoft
waredevelopment.
3. GitHub:Acodehostingplatformforcollaborationandversi
[Link]
ts.
4. GithubPages:ItallowsyoutoturnyourGitHubrepositoriesin
toanelegantwebsitetoshowcaseyourportfolio,projects,docum
entation,oranythingelseyouwanttomakelivebutrememberth
atthereisnodatabasetosetupandnoservertoconfigure.
5. NodeJSandnpm:[Link]
unningJavascriptontheserverandnpmisapackagemanageruse
dtodownloadandinstalldifferentpackagesforJavaScriptprojects
.
Prerequisites
1. DownloadGitandgothroughthedefaultinstallationprocess.
2. [Link]
reisthecommandtochecktheinstallationandversion.
$node--version
$npm--version
3. Anadequateversionofcreate-react-
[Link]
dversion.
$create-react-app--version
Ifit’snotinstalledthenusethecommandbelowtoinstallitglobally.
$npminstall-gcreate-react-app
4. AGitHubaccount.
NowTheRealFunBegins(Procedure)
1. FirstlycreateaReactapplicationinyoursystemusingthecomm
[Link]“react-
deploy”[Link]
[Link]“react-
deploy”inyourdirectory.
$create-react-appreact-deploy
2. Nowenteryournewapplicationandrunthefollowingcommand
[Link]
ocaldevelopmentserver[Link]
#changedirectory
$cdreact-deploy
#runapplicationinthedevelopmentenvironment
Downloaded by CHAITANYA B
$npmstart
3. Aftercheckingthatyourapplicationrunsperfectlywithoutany
erroronalocalserver,[Link]
vingthisname“my-
app”whichisdifferentfromtheapplicationnameyouhavecreate
[Link],youcanalsochoosethesamena
mei.e.“react-
deploy”[Link]’stotallyuptoyou.
4. Installthegh-pagespackageasa“dev-dependency”oftheapp.
#installgh-pagespackage
$npminstall--savegh-pages
5. Addsomepropertiestotheapp’[Link]
plevel,[Link]
string[Link]
{username}isyourGitHubusername,and{repo-
name}isthenameoftheGitHubrepository(my-
app)youcreatedinstep3.
Takealookattheexamplegivenbelow…
"homepage":"[Link]
[Link]
perty,addapredeploypropertyandadeployproperty,eachhav
ingthevaluesshownbelow:
"scripts":{
//...
"predeploy":"npmrunbuild","d
eploy":"gh-pages-dbuild",
//...
"build":"react-scriptsbuild&&cpbuild/[Link]/
[Link]",//thiswillpreventpagereloadstogivea
404error
}
[Link]
oksomethinglikethis…
Downloaded by CHAITANYA B
Next,ifyouareusingtheRouterfromreact-router-
domthenyouneedtochangetheBrowserroutertagsto
//...
BrowserRouterbasename={[Link].PUBLIC_URL}
//...
6. Inthisstepcreateagitrepositoryintheapp’sfolderandaddtheG
itHubrepositoryasa“remote”[Link]
makeitsothegh-
pagespackageknowswhereyouwantittodeployyourappinstep7
.Itwillalsomakeitsogitknowswhereyouwantittopushyoursourc
ecode([Link])instep8.
#createanewgitrepository
$gitinit
#addremoterepository
$gitremoteaddorigin[Link]
7. [Link]
roductionbuildofyourapp,todeployyourcodeonGitHubpages. #dep
loyapplication
$npmrundeploy
Downloaded by CHAITANYA B
That’[Link]
youwanttoverifyitjustgotothesettingstabofyourapplicationiny
[Link]
elow…
Inourcase,theappisaccessible
at:[Link]
8. Atthispoint,ifyouwillexploretheGitHubrepositoryyouwillnoti
cethatthemasterbranchdidnotexist,agh-
[Link]
ode,asopposedtotheapp’[Link]
sterbranchandpushyoursourcecodetoitrunthecommandgiven
below…
#addallchangedfilepathstostagedchanges
$gitadd.
#commitallstagedchanges
$gitcommit-
m"CreateaReactappandpublishittoGitHubPages"#pushedlocalreposito
rytoremoterepositoryonGitHub
$gitpushoriginmaster
[Link]
willnoticethatamasterbranchnowexisted,anditcontainedthea
pp’[Link]
epository.
Downloaded by CHAITANYA B