0% found this document useful (0 votes)
9 views118 pages

CY409PC NODE JS REACT JS DJANGO LAB Manual

Gsvg

Uploaded by

Usha Sree
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views118 pages

CY409PC NODE JS REACT JS DJANGO LAB Manual

Gsvg

Uploaded by

Usha Sree
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 118

1.

Build a responsive web application for shopping cart with registration, login, catalog
and cart pages using CSS3 features, flex and grid.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
<title>Home - PEC</title>
</head>
<body>
<div class="wrapper">
<div class="container">
<header>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tr>
<th width="20%"><img src="PEC Header.png" alt="PEC LOGO" width=""
height="100"/></th>

<th colspan=4>
<h1 style="color:white;">PEC - WORLD BEST ONLINE EBOOKS WEBSITE</h1>
</th>
</tr>
</table>
</header>
<nav>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tbody align="center" style="font-weight:bold;font-size:18px;"">
<tr>
<td width="20%"><hr><a href="index.html">Home</a><hr></td>
<td width="20%"><hr><a href="login.html">Login</a><hr></td>
<td width="20%"><hr><a ref="registration.html">Registration</a><hr></td>
<td width="20%"><hr><a href="cart.html" >Cart</a><hr></td>
</tr>
</tbody>
</table>
</nav>
</div>
<div class="container1">
<div class="sidebar1"></div>
<div class="container2">
<main>
<center>
<h2>Welcome to PEC e-Book's Website</h2>
<p>Shopping at <font size=5>PEC</font> can be both <font
size=5>fun</font>
and <font size=5>savings</font>.</br>Shop with us in this
special <font
size=5>discount</font> season and save upto
<font size=5>90%</font> on all your
purchases.</br></p>
<br/><br/><br/><br/><br/><br/><br/><br/>
</main>
</div>
<div class="sidebar2"></div>
</div>
<footer><font color="white">(C) 2024 All rights reserved by PEC
ebooks</font></footer>
</div>
</body>
</html>
registration.html

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
<title>Registration - PEC</title>
</head>
<body>
<div class="wrapper">
<div class="container">
<header>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tr>
<th width="20%"><img src="PEC Header.png" alt="PEC LOGO" width="130"
height="100"/></th>

<th colspan=4>
<h1 style="color:white;">PEC - WORLD BEST ONLINE EBOOKS WEBSITE</h1>
</th>
</tr>
</table>
</header>
<nav>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tbody align="center" style="font-weight:bold;font-size:18px;"">
<tr>
<td width="20%"><hr><a href="index.html">Home</a><hr></td>
<td width="20%"><hr><a href="login.html">Login</a><hr></td>
<td width="20%"><hr><a href="registration.html">Registratio</a><hr></td>
<td width="20%"><hr><a href="cart.html" >Cart</a><hr></td>
</tr>
</tbody>
</table>
</nav>
</div>
<div class="container1">
<div class="sidebar1"></div>
<div class="container2">
<main>
<center><br>
<h3>Registration Form </h3>
<br/>
<form name="f1">
<table cellpadding="1" align="center" >
<tr><td> Name:*</td>
<td><input type="text" name="username"></td></tr>
<tr><td>Password:*</td>
<td><input type="password" name="password"></td></tr>
<tr><td>Email ID:*</td>
<td><input type="text" name="email"></td></tr>
<tr><td>Phone Number:*</td>
<td><input type="text" name="phno"></td></tr>
<tr><td valign="top">Gender:*</td>
<td><input type="radio" name="radio" value="1">Male &nbsp;&nbsp;
<input type="radio" name="radio" value="2">Female</td></tr>
<tr> <td valign="top">Language Known:*</td>
<td> <input type="checkbox" name="checkbox"
value="English">English<br/>
<input type="checkbox" name="checkbox" value="Telugu">Telugu<br>
<input type="checkbox" name="checkbox" value="Hindi">Hindi<br>
<input type="checkbox" name="checkbox" value="Tamil">Tamil
</td></tr>
<tr> <td valign="top">Address:*</td>
<td><textarea name="address"></textarea></td>
<tr><td></td><td><input type="submit" value="submit"
hspace="10">
<input type="reset" value="reset"></td></tr>
<tr> <td colspan=2 >*<font color="#FF0000">fields are
mandatory</font>
</td>
</tr>
</table>
</form>
</center>
</main>
</div>
<div class="sidebar2"></div>
</div>
<footer><font color="white">(C) 2024 All rights reserved by PEC
ebooks</font></footer>
</div>
</body>
</html>
login.html

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
<title>Login - PEC</title>
</head>
<body>
<div class="wrapper">
<div class="container">
<header>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tr>
<th width="20%"><img src="PEC Header.png" alt="PEC LOGO" width="130"
height="100"/></th>
<th colspan=4>
<h1 style="color:white;">PEC - WORLD BEST ONLINE EBOOKS WEBSITE</h1>
</th>
</tr>
</table>
</header>
<nav>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tbody align="center" style="font-weight:bold;font-size:18px;"">
<tr>
<td width="20%"><hr><a href="index.html">Home</a><hr></td>
<td width="20%"><hr><a href="login.html">Login</a><hr></td>
<td width="20%"><hr><a
href="registration.html">Registration</a><hr></td>
<td width="20%"><hr><a href="cart.html" >Cart</a><hr></td>
</tr>
</tbody>
</table>
</nav>
</div>
<div class="container1">
<div class="sidebar1"></div>
<div class="container2">
<main>
<center><br>
<h3> Login Details</h3> <br/>
<form name="f1">
<table width="100%" align="center" >
<tr>
<td> User Name : </td>
<td> <input type="text" name="username"></td>
</tr>
<tr><td><br></td></tr>
<tr>
<td> Password : </td>
<td> <input type="password" name="password"></td>
</tr>
<tr><td><br></td></tr>
<tr><td></td>
<td><input type="submit" value="SUBMIT">
<input type="reset" value="RESET"></td>
</tr>
</table>
</form>
</center>
</main>
</div>
<div class="sidebar2"></div>
</div>
<footer><font color="white">(C) 2024 All rights reserved by PEC
ebooks</font></footer>
</div>
</body>
</html>
cart.html

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
<title>Cart - PEC</title>
</head>
<body>
<div class="wrapper">
<div class="container">
<header>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tr>
<th width="20%"><img src="PEC Header.png" alt="PEC LOGO" width="130"
height="100"/></th>
<th colspan=4>
<h1 style="color:white;">PEC - WORLD BEST ONLINE EBOOKS WEBSITE</h1>
</th>
</tr>
</table>
</header>
<nav>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tbody align="center" style="font-weight:bold;font-size:18px;"">
<tr>
<td width="20%"><hr><a href="index.html">Home</a><hr></td>
<td width="20%"><hr><a href="login.html">Login</a><hr></td>
<td width="20%"><hr><a href="registration.html">Registation</a><hr></td>
<td width="20%"><hr><a href="cart.html" >Cart</a><hr></td>
</tr>
</tbody>
</table>
</nav>
</div>
<div class="container1">
<div class="sidebar1"></div>
<div class="container2">
<main>
<center>
<h3>Cart</h3>
<table width="100%" align="center" >
<tbody>
<tr>
<th width="40%"><hr>BookName<hr></th>
<th width="20%"><hr>Price<hr></th>
<th width="20%"><hr>Quantity<hr></th>
<th width="20%"><hr>Amount<hr></th> </tr>
</tbody>
<tbody align=center>
<tr> <td>Java Programming </td>
<td>Rs. 2300/-</td>
<td>2</td>
<td>Rs. 4600/-</td></tr>
<tr><td>Web Technologies</td>
<td>Rs. 3000/-</td>
<td>1</td>
<td>Rs. 3000/-</td></tr>
<tr><td></td>
<td><hr><font color="#996600">Total Amount:</font><hr></td>
<td><hr>3<hr></td>
<td><hr>Rs. 7600/-<hr></td> </tr>
</tbody>
</table>
</center>
</main>
</div>
<div class="sidebar2"></div>
</div>
<footer><font color="white">(C) 2024 All rights reserved by PEC
ebooks</font></footer>
</div>
</body>
</html>
style.css

body{
font-family: monospace;
}

main {
background-color: #efefef;
color: #330000;
margin-left: 10px;
height: 60vh;
}

header, footer {
background-color: #000d57;
color: #fff;
padding: 1rem;
height: 50px;
}

header, nav{
margin-bottom: 10px;
flex-basis: 50%;
}

footer{
margin-top: 10px;
}
nav {
background-color: #fff;
color: #000;
padding: 1rem;
height: 20px;
}

.sidebar1, .sidebar2 {
flex-basis: 10%;
background-color: #fff;
color: #000;
}

.sidebar2{
margin-left: 10px;
}
.container1{
display: flex;
}

.container2 {
display: flex;
flex-direction: column;
flex: 1;
}

header, nav, main, .sidebar1, .sidebar2, footer{


display: flex;
align-items: center;
justify-content: center;
border-radius: 10px;
}

.wrapper {
display: flex;
flex-direction: column;
font-weight: 600;
}
2. Make the above web application responsive web application using Bootstrap
framework.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home - PEC</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]
alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
background-color: #f8f9fa;
}
.header-img {
height: 100px;
}
.custom-header {
background-color: #ffffff;
color: white;
padding: 20px 0;
}
.custom-nav a {
color: white;
text-decoration: none;
padding: 10px 20px;
display: inline-block;

}
.custom-nav a:hover {

border-radius: 5px;
}
nav{
background-color:#0b6620;
}
</style>
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container-fluid">
<div class="container-fluid">
<!-- Header Section -->
<header class="custom-header text-center">
<div class="container d-flex align-items-center justify-content-
between">
<img src="PEC Header.png" alt="PEC LOGO" class="header-img">
<h1 class="mb-0">PEC - WORLD BEST ONLINE EBOOKS WEBSITE</h1>
</div>
</header>

<!-- Navigation Section -->


<nav class="custom-nav text-center">
<a href="index.html">Home</a>
<a href="login.html">Login</a>
<a href="registration.html">Register</a>
<a href="cart.html">Cart</a>
</nav>

<!-- Main Content -->


<main class="mt-4">
<div class="container text-center">
<h2>Welcome to PEC</h2>
<img src="PECBuilding_F1.png" alt="" width="70%" height="50%">
<p>Your one-stop destination for online eBooks.</p>
<button class="btn btn-primary">Explore Now</button>
</div>
</main>

<!-- Footer Section -->


<footer class="bg-dark text-white text-center py-3 mt-4">
<p>&copy; 2025 PEC. All rights reserved.</p>
</footer>
</div>

<!-- Bootstrap JS -->


<script src="https://cdn.jsdelivr.net/npm/[email protected]
alpha1/dist/js/bootstrap.bundle.min.js"></script>
</div>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login - PEC</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]
alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
background-color: #f8f9fa;
}
.header-img {
height: 100px;
}
.custom-header {
background-color: #ffffff;
color: white;
padding: 20px 0;
}
.custom-nav a {
color: white;
text-decoration: none;
padding: 10px 20px;
display: inline-block;
}
.custom-nav a:hover {
background-color: #495057;
border-radius: 5px;
}
</style>
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container-fluid">
<div class="container-fluid">
<!-- Header Section -->
<header class="custom-header text-center">
<div class="container d-flex align-items-center justify-content-
between">
<img src="PEC Header.png" alt="PEC LOGO" class="header-img">
<h1 class="mb-0">PEC - WORLD BEST ONLINE EBOOKS WEBSITE</h1>
</div>
</header>

<!-- Navigation Section -->


<nav class="bg-dark custom-nav text-center">
<a href="index.html">Home</a>
<a href="login.html">Login</a>
<a href="registration.html">Register</a>
<a href="cart.html">Cart</a>
</nav>

<!-- Login Form Section -->


<main class="mt-4">
<div class="container">
<h2 class="text-center">Login</h2>
<form class="mx-auto mt-3" style="max-width: 400px;">
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username"
placeholder="Enter your username">
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password"
placeholder="Enter your password">
</div>
<div class="mb-3 form-check">
<input type="checkbox" class="form-check-input"
id="rememberMe">
<label class="form-check-label" for="rememberMe">Remember
Me</label>
</div>
<button type="submit" class="btn btn-primary w-
100">Login</button>
</form>
</div>
</main>

<!-- Footer Section -->


<footer class="bg-dark text-white text-center py-3 mt-4">
<p>&copy; 2025 PEC. All rights reserved.</p>
</footer>
</div>

<!-- Bootstrap JS -->


<script src="https://cdn.jsdelivr.net/npm/[email protected]
alpha1/dist/js/bootstrap.bundle.min.js"></script>
</div>
</body>
</html>
registration.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Page</title>
<!-- Bootstrap CSS -->
<link
href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.cs
s" rel="stylesheet">
<link rel="stylesheet" href="stylecss">
<style>
body {
background-color: #f8f9fa;
}
.header-img {
height: 100px;
}
.custom-header {
background-color: #ffffff;
color: white;
padding: 20px 0;
}
.custom-nav a {
color: white;
text-decoration: none;
padding: 10px 20px;
display: inline-block;
}
.custom-nav a:hover {
background-color: #495057;
border-radius: 5px;
}
</style>
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container-fluid">
<!-- Header Section -->
<header class="custom-header text-center">
<div class="container d-flex align-items-center justify-content-between">
<img src="PEC Header.png" alt="PEC LOGO" class="header-img">
<h1 class="mb-0">PEC - WORLD BEST ONLINE EBOOKS WEBSITE</h1>
</div>
</header>
<!-- Navigation Section -->
<nav class="bg-dark custom-nav text-center">
<a href="index.html">Home</a>
<a href="login.html">Login</a>
<a href="registration.html">Register</a>
<a href="cart.html">Cart</a>
</nav>

<!-- Main Content -->


<main class="container my-5">
<h1 class="text-center mb-4">Registration</h1>
<form class="row g-3">
<div class="col-md-6">
<label for="firstName" class="form-label">First Name</label>
<input type="text" class="form-control" id="firstName"
placeholder="Enter your first name">
</div>
<div class="col-md-6">
<label for="lastName" class="form-label">Last Name</label>
<input type="text" class="form-control" id="lastName"
placeholder="Enter your last name">
</div>
<div class="col-md-12">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control" id="email"
placeholder="Enter your email">
</div>
<div class="col-md-12">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password"
placeholder="Enter your password">
</div>
<div class="col-md-12">
<label for="confirmPassword" class="form-label">Confirm
Password</label>
<input type="password" class="form-control" id="confirmPassword"
placeholder="Confirm your password">
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary w-
100">Register</button>
</div>
</form>
</main>

<!-- Footer -->


<footer class="bg-dark text-white text-center py-3">
<p class="mb-0">&copy; 2025 Your Brand. All rights reserved.</p>
</footer>

<!-- Bootstrap JS -->


<script
src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.m
in.js"></script>
</div>
</body>
</html>
cart.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cart Page</title>
<!-- Bootstrap CSS -->
<link
href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.cs
s" rel="stylesheet">
<link rel="stylesheet" href="stylecss">
<style>
body {
background-color: #f8f9fa;
}
.header-img {
height: 100px;
}
.custom-header {
background-color: #ffffff;
color: white;
padding: 20px 0;
}
.custom-nav a {
color: white;
text-decoration: none;
padding: 10px 20px;
display: inline-block;
}
.custom-nav a:hover {
background-color: #495057;
border-radius: 5px;
}
</style>
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container-fluid">
<!-- Header Section -->
<header class="custom-header text-center">
<div class="container d-flex align-items-center justify-content-between">
<img src="PEC Header.png" alt="PEC LOGO" class="header-img">
<h1 class="mb-0">PEC - WORLD BEST ONLINE EBOOKS WEBSITE</h1>
</div>
</header>
<!-- Navigation Section -->
<nav class="bg-dark custom-nav text-center">
<a href="index.html">Home</a>
<a href="login.html">Login</a>
<a href="registration.html">Register</a>
<a href="cart.html">Cart</a>
</nav>

<!-- Main Content -->


<main class="container my-5">
<h1 class="text-center mb-4">Your Cart</h1>
<div class="table-responsive">
<table class="table table-bordered">
<thead class="table-dark">
<tr>
<th>Item</th>
<th>Description</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>Sample Item 1</td>
<td>Lorem ipsum dolor sit amet.</td>
<td>$10.00</td>
<td><input type="number" value="1" class="form-control"
style="width: 80px;"></td>
<td>$10.00</td>
<td><button class="btn btn-danger btn-
sm">Remove</button></td>
</tr>
<tr>
<td>Sample Item 2</td>
<td>Consectetur adipiscing elit.</td>
<td>$20.00</td>
<td><input type="number" value="1" class="form-control"
style="width: 80px;"></td>
<td>$20.00</td>
<td><button class="btn btn-danger btn-
sm">Remove</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="4" class="text-end">Grand Total</th>
<th colspan="2">$30.00</th>
</tr>
</tfoot>
</table>
</div>
<div class="text-center mt-4">
<button class="btn btn-primary">Proceed to Checkout</button>
</div>
</main>

<!-- Footer -->


<footer class="bg-dark text-white text-center py-3">
<p class="mb-0">&copy; 2025 Your Brand. All rights reserved.</p>
</footer>

<!-- Bootstrap JS -->


<script
src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.m
in.js"></script>
</div>
</body>
</html>
registration.html
<html>
<head>
<title> Welcome to NNRG e-Book's website</title>
<script language="javascript">
function validate() {
// username validation
var uname = f1.username.value;
if (uname.length<=0)
{
alert("Please Enter UserName");
f1.username.focus();
return false;
}
if (uname.length < 8)
{
alert("Please enter UserName not less than 8");
f1.username.focus();
return false;
}
//password validation
var pwd = f1.password.value;
if (pwd.length<=0)
{
alert("Please Enter password");
f1.password.focus();
return false;
}
if (pwd.length < 6)
{
alert("Please enter Password not less than 6");
f1.password.focus();
return false;
}
// email validation
var email = f1.email.value;
if (email.length<=0)
{
alert("Please Enter email");
f1.email.focus();
return false;
}
else {
let eflag=false;
for(i=0;i<email.length;i++) {
if(email.charAt(i)=="@")
{
eflag=true;
}
}
if(!(eflag))
{
alert("Please enter a valid Email ID");
f1.email.focus();
return false;
}
}
// phone number validation
var phno = f1.phno.value;
if (phno.length<=0)
{
alert("Please Enter Phone Number");
f1.phno.focus();
return false;
}
if (isNaN(phno))
{
alert("Please Enter Valid Phone Number");
f1.phno.focus();
return false;
}
if (phno.length != 10)
{
alert("Please Enter Valid Phone Number");
f1.phno.focus();
return false;
}
// gender validation
let flag=false;
for(i=0;i<f1.gen.length;i++)
if(f1.gen[i].checked)
flag=true;
if(!(flag))
{
alert("Please choose a Gender");
return false;
}
// Language validation
flag=false;
for(i=0;i<f1.lang.length;i++)
if(f1.lang[i].checked)
flag=true;
if(!(flag))
{
alert("Please select at least one of the Language options.");
return false;
}
// address validation
var addr = f1.address.value;
if (addr.length<=0)
{
alert("Please Enter address");
f1.address.focus();
return false;
}
// to display Success message
alert("Registration Successful");
}
</script>
</head>
<body>
<center><br>
<h3>Registration Form </h3>
<br/>
<form name="f1">
<table cellpadding="1" align="center" >
<tr><td> User Name:*</td>
<td><input type="text" name="username"></td></tr>
<tr><td>Password:*</td>
<td><input type="password" name="password"></td></tr>
<tr><td>Email ID:*</td>
<td><input type="text" name="email"></td></tr>
<tr><td>Phone Number:*</td>
<td><input type="text" name="phno"></td></tr>
<tr><td valign="top">Gender:*</td>
<td><input type="radio" name="gen" value="Male">Male &nbsp;&nbsp;
<input type="radio" name="gen" value="Female">Female</td></tr>
<tr> <td valign="top">Language Known:*</td>
<td> <input type="checkbox" name="lang" value="English">English<br/>
<input type="checkbox" name="lang" value="Telugu">Telugu<br>
<input type="checkbox" name="lang" value="Hindi">Hindi<br>
<input type="checkbox" name="lang" value="Tamil">Tamil
</td></tr>
<tr> <td valign="top">Address:*</td>
<td><textarea name="address"></textarea></td>
<tr><td></td><td><input type="button" value="SUBMIT" hspace="10"
onclick="validate()">
<input type="reset" value="RESET"></td></tr>
<tr> <td colspan=2 >*<font color="#FF0000">fields are mandatory</font>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
4. Explore the features of ES6 like arrow functions, callbacks, promises, async/await. Implement
an application for reading the weather information from openweathermap.org and display the
information in the form of a graph on the web page.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App with ES6 Features</title>
<link rel="stylesheet" href="styles.css">
<!-- Chart.js for data visualization -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="container">
<h1>Weather App with ES6 Features</h1>

<div class="search-container">
<input type="text" id="city-input" placeholder="Enter city name">
<button id="search-btn">Search</button>
</div>

<div class="weather-container">
<div id="current-weather" class="weather-card">
<h2>Current Weather</h2>
<div id="weather-info"></div>
</div>

<div id="weather-chart-container">
<canvas id="weather-chart"></canvas>
</div>
</div>

<div class="es6-demo-container">
<h2>ES6 Features Demo</h2>
<div class="feature-section">
<h3>Arrow Functions</h3>
<button id="arrow-demo-btn">Run Demo</button>
<div id="arrow-result" class="result"></div>
</div>
<div class="feature-section">
<h3>Callbacks</h3>
<button id="callback-demo-btn">Run Demo</button>
<div id="callback-result" class="result"></div>
</div>

<div class="feature-section">
<h3>Promises</h3>
<button id="promise-demo-btn">Run Demo</button>
<div id="promise-result" class="result"></div>
</div>

<div class="feature-section">
<h3>Async/Await</h3>
<button id="async-demo-btn">Run Demo</button>
<div id="async-result" class="result"></div>
</div>
</div>
</div>

<script src="es6Features.js"></script>
<script src="weatherApp.js"></script>
</body>
</html>

style.css

* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Arial', sans-serif;
}

body {
background-color: #f5f5f5;
color: #333;
line-height: 1.6;
}
.container {
max-width: 1000px;
margin: 0 auto;
padding: 20px;
}

h1 {
text-align: center;
margin-bottom: 30px;
color: #2c3e50;
}

h2 {
color: #3498db;
margin-bottom: 15px;
}

h3 {
color: #2c3e50;
margin-bottom: 10px;
}

.search-container {
display: flex;
justify-content: center;
margin-bottom: 30px;
}

#city-input {
padding: 10px;
width: 300px;
border: 1px solid #ddd;
border-radius: 4px 0 0 4px;
font-size: 16px;
}

#search-btn {
padding: 10px 20px;
background-color: #3498db;
color: white;
border: none;
border-radius: 0 4px 4px 0;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s;
}

#search-btn:hover {
background-color: #2980b9;
}

.weather-container {
display: flex;
flex-direction: column;
gap: 20px;
margin-bottom: 40px;
}

.weather-card {
background-color: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

#weather-chart-container {
background-color: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
height: 300px;
}

.es6-demo-container {
background-color: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.feature-section {
margin-bottom: 25px;
padding-bottom: 15px;
border-bottom: 1px solid #eee;
}

.feature-section:last-child {
border-bottom: none;
}
button {
padding: 8px 15px;
background-color: #3498db;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin-bottom: 10px;
transition: background-color 0.3s;
}

button:hover {
background-color: #2980b9;
}

.result {
background-color: #f9f9f9;
padding: 10px;
border-radius: 4px;
border-left: 3px solid #3498db;
min-height: 40px;
white-space: pre-wrap;
}

@media (min-width: 768px) {


.weather-container {
flex-direction: row;
}

.weather-card {
flex: 1;
}

#weather-chart-container {
flex: 2;
}
}
es6Feastures.js

// ES6 Features Demonstration

// ===== Arrow Functions =====


document.getElementById('arrow-demo-btn').addEventListener('click', () => {
const resultElement = document.getElementById('arrow-result');
resultElement.innerHTML = '';

// Traditional function
function traditionalSum(a, b) {
return a + b;
}

// Arrow function
const arrowSum = (a, b) => a + b;

// Arrow function with multiple statements


const arrowMultipleStatements = (a, b) => {
const sum = a + b;
const product = a * b;
return `Sum: ${sum}, Product: ${product}`;
};

// Array methods with arrow functions


const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
const filtered = numbers.filter(num => num > 2);

resultElement.innerHTML = `
Traditional function: ${traditionalSum(5, 3)} <br>
Arrow function: ${arrowSum(5, 3)} <br>
Arrow function with multiple statements: ${arrowMultipleStatements(5, 3)}
<br>
Array.map with arrow function: [${doubled}] <br>
Array.filter with arrow function: [${filtered}]
`;
});

// ===== Callbacks =====


document.getElementById('callback-demo-btn').addEventListener('click', () => {
const resultElement = document.getElementById('callback-result');
resultElement.innerHTML = 'Processing...';

// Simulating asynchronous operation with callbacks


const fetchData = (callback) => {
setTimeout(() => {
const data = { name: 'Weather Data', temperature: 25 };
callback(null, data);
}, 1500);
};

const processData = (error, data) => {


if (error) {
resultElement.innerHTML = `Error: ${error.message}`;
} else {
resultElement.innerHTML = `
Callback received after 1.5 seconds: <br>
Name: ${data.name} <br>
Temperature: ${data.temperature}°C
`;
}
};

// Execute the callback pattern


fetchData(processData);
});

// ===== Promises =====


document.getElementById('promise-demo-btn').addEventListener('click', () => {
const resultElement = document.getElementById('promise-result');
resultElement.innerHTML = 'Processing...';

// Creating a promise
const fetchDataPromise = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = true; // Change to false to simulate error

if (success) {
const data = { name: 'Promise Data', temperature: 28 };
resolve(data);
} else {
reject(new Error('Failed to fetch data'));
}
}, 1500);
});
};

// Using the promise


fetchDataPromise()
.then(data => {
resultElement.innerHTML = `
Promise resolved after 1.5 seconds: <br>
Name: ${data.name} <br>
Temperature: ${data.temperature}°C
`;
})
.catch(error => {
resultElement.innerHTML = `Promise rejected: ${error.message}`;
})
.finally(() => {
console.log('Promise operation completed');
});
});

// ===== Async/Await =====


document.getElementById('async-demo-btn').addEventListener('click', async () => {
const resultElement = document.getElementById('async-result');
resultElement.innerHTML = 'Processing...';

// Function that returns a promise


const fetchDataAsync = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = true; // Change to false to simulate error

if (success) {
const data = { name: 'Async/Await Data', temperature: 30 };
resolve(data);
} else {
reject(new Error('Failed to fetch data'));
}
}, 1500);
});
};

// Using async/await
try {
const data = await fetchDataAsync();
resultElement.innerHTML = `
Async/Await resolved after 1.5 seconds: <br>
Name: ${data.name} <br>
Temperature: ${data.temperature}°C
`;
} catch (error) {
resultElement.innerHTML = `Async/Await error: ${error.message}`;
}
});

weatherApp.js

// Weather App Implementation using ES6 Features

// Constants
const API_KEY = '349e1822e8739db21980838d35c0354a'; // You need to get your API
key from OpenWeatherMap
const BASE_URL = 'https://api.openweathermap.org/data/2.5';

// DOM Elements
const cityInput = document.getElementById('city-input');
const searchBtn = document.getElementById('search-btn');
const weatherInfo = document.getElementById('weather-info');
const weatherChartCanvas = document.getElementById('weather-chart');

// Chart instance
let weatherChart = null;

// Event Listeners
searchBtn.addEventListener('click', () => {
const city = cityInput.value.trim();
if (city) {
getWeatherData(city);
} else {
alert('Please enter a city name');
}
});

cityInput.addEventListener('keypress', (e) => {


if (e.key === 'Enter') {
searchBtn.click();
}
});

// Weather API Functions using ES6 Features


// Fetch current weather data using async/await
const getWeatherData = async (city) => {
try {
weatherInfo.innerHTML = 'Loading...';

// Using template literals for URL construction


const currentWeatherUrl =
`${BASE_URL}/weather?q=${city}&units=metric&appid=${API_KEY}`;
const forecastUrl =
`${BASE_URL}/forecast?q=${city}&units=metric&appid=${API_KEY}`;

// Using Promise.all to fetch multiple resources in parallel


const [currentResponse, forecastResponse] = await Promise.all([
fetch(currentWeatherUrl),
fetch(forecastUrl)
]);

// Check if responses are ok


if (!currentResponse.ok || !forecastResponse.ok) {
throw new Error('City not found or API error');
}

// Parse JSON responses using arrow functions and await


const currentData = await currentResponse.json();
const forecastData = await forecastResponse.json();

// Display the data


displayCurrentWeather(currentData);
displayWeatherChart(forecastData);

} catch (error) {
weatherInfo.innerHTML = `Error: ${error.message}`;
clearChart();
}
};

// Display current weather information


const displayCurrentWeather = (data) => {
// Destructuring assignment to extract properties
const { name, main, weather, wind, sys } = data;
const { temp, feels_like, humidity, pressure } = main;
const { description, icon } = weather[0];

// Template literals for HTML construction


const html = `
<div class="weather-details">
<h3>${name}, ${sys.country}</h3>
<div class="weather-icon">
<img src="https://openweathermap.org/img/wn/${icon}@2x.png"
alt="${description}">
</div>
<div class="temperature">${Math.round(temp)}°C</div>
<div class="description">${description}</div>
<div class="details">
<p>Feels like: ${Math.round(feels_like)}°C</p>
<p>Humidity: ${humidity}%</p>
<p>Pressure: ${pressure} hPa</p>
<p>Wind: ${wind.speed} m/s</p>
</div>
</div>
`;

weatherInfo.innerHTML = html;
};

// Display weather forecast chart


const displayWeatherChart = (data) => {
// Clear previous chart
clearChart();

// Process forecast data


// Using array methods (map, filter) with arrow functions
const forecastList = data.list;

// Get the next 5 days data at the same time of day


const filteredForecast = forecastList.filter((item, index) => index % 8 ===
0);

// Extract dates and temperatures using destructuring and map


const labels = filteredForecast.map(item => {
const date = new Date(item.dt * 1000);
return date.toLocaleDateString('en-US', { weekday: 'short' });
});

const temperatures = filteredForecast.map(item => item.main.temp);


const minTemps = filteredForecast.map(item => item.main.temp_min);
const maxTemps = filteredForecast.map(item => item.main.temp_max);

// Create chart using Chart.js


weatherChart = new Chart(weatherChartCanvas, {
type: 'line',
data: {
labels: labels,
datasets: [
{
label: 'Temperature (°C)',
data: temperatures,
borderColor: '#3498db',
backgroundColor: 'rgba(52, 152, 219, 0.2)',
tension: 0.3,
fill: true
},
{
label: 'Min Temperature (°C)',
data: minTemps,
borderColor: '#2980b9',
backgroundColor: 'rgba(41, 128, 185, 0.1)',
borderDash: [5, 5],
tension: 0.3,
fill: false
},
{
label: 'Max Temperature (°C)',
data: maxTemps,
borderColor: '#e74c3c',
backgroundColor: 'rgba(231, 76, 60, 0.1)',
borderDash: [5, 5],
tension: 0.3,
fill: false
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: '5-Day Weather Forecast',
font: {
size: 16
}
},
tooltip: {
mode: 'index',
intersect: false
}
},
scales: {
y: {
title: {
display: true,
text: 'Temperature (°C)'
}
}
}
}
});
};

// Clear the chart


const clearChart = () => {
if (weatherChart) {
weatherChart.destroy();
weatherChart = null;
}
};

// Initial instructions
weatherInfo.innerHTML = `
<div class="initial-message">
<p>Enter a city name and click "Search" to get weather information.</p>
<p>You'll need to add your OpenWeatherMap API key in the weatherApp.js
file.</p>
</div>
`;

// Display a message about getting an API key


console.log('Remember to get your API key from https://openweathermap.org/api and
add it to the weatherApp.js file.');
Output:

Open Index.html page with Browser

file:///C:/Users/rames/OneDrive/1.PEC/2-2/LabPrograms/4/index.html
Type Hyderabad Search
Demo
5. Develop a java stand-alone application that connects with the database (Oracle / MySQL)
and perform the CRUD operation on the database tables.

Java Source Code Documentation

InsertData.java
### Description:
This Java file contains the implementation for database operations.

import java.sql.*;
import java.util.Scanner;

public class InsertData {


public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");

try (Connection con =


DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "123456");
Statement s = con.createStatement();
Scanner sc = new Scanner(System.in)) {

System.out.println("Inserting Data into student table:");


System.out.println("________________________________________");

System.out.print("Enter student id: ");


int sid = sc.nextInt();
System.out.print("Enter student name: ");
String sname = sc.next();
System.out.print("Enter student address: ");
String saddr = sc.next();

String insertQuery = "INSERT INTO student VALUES(" + sid + ",'" +


sname + "','" + saddr + "')";
s.executeUpdate(insertQuery);

System.out.println("Data inserted successfully into student


table");
}
} catch (SQLException err) {
System.out.println("ERROR: " + err);
} catch (ClassNotFoundException e) {
System.out.println("MySQL JDBC Driver not found.");
e.printStackTrace();
}
}
}

PS C:\Users\rames\OneDrive\1.PEC\2-2\Lab Programs\5> javac -cp ".;mysql-


connector-j-9.2.0.jar" InsertData.java
PS C:\Users\rames\OneDrive\1.PEC\2-2\Lab Programs\5> java -cp ".;mysql-connector-
j-9.2.0.jar" InsertData
Inserting Data into student table:
________________________________________
Enter student id: 2
Enter student name: Ramesh
Enter student address: Hyderabad
Data inserted successfully into student table

DisplayData.java
### Description:
This Java file contains the implementation for database operations.

import java.sql.*;

public class DisplayData {


public static void main(String[] args) {
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

try (Connection con =


DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "123456");
Statement s = con.createStatement()) {

ResultSet rs = s.executeQuery("SELECT * FROM student");


if (rs != null) {
System.out.println("SID \t STU_NAME \t ADDRESS");
System.out.println("________________________________________");

while (rs.next()) {
System.out.println(rs.getString("s_id") + " \t " +
rs.getString("s_name") + " \t " + rs.getString("s_address"));
System.out.println("________________________________________");
}
}

} catch (SQLException err) {


System.out.println("ERROR: " + err);
}
} catch (ClassNotFoundException e) {
System.out.println("MySQL JDBC Driver not found. Include it in your library
path.");
e.printStackTrace();
}
}
}

PS C:\Users\rames\OneDrive\1.PEC\2-2\Lab Programs\5> javac -cp ".;mysql-


connector-j-9.2.0.jar" DisplayData.java
PS C:\Users\rames\OneDrive\1.PEC\2-2\Lab Programs\5> java -cp ".;mysql-connector-
j-9.2.0.jar" DisplayData
SID STU_NAME ADDRESS
________________________________________
1 rama Hyd
________________________________________
2 Ramesh Hyderabad
________________________________________

updateData.java
### Description:
This Java file contains the implementation for database operations.

import java.sql.*;
import java.util.Scanner;

public class UpdateData {


public static void main(String[] args) {
try (Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "123456");
Statement s = con.createStatement()) { // Changed 'Statements' to
'Statement s'

Scanner sc = new Scanner(System.in);


System.out.println("Update Data in student table:");
System.out.println("________________________________________");

System.out.print("Enter student id: ");


int sid = sc.nextInt();
System.out.print("Enter student name: ");
String sname = sc.next();
System.out.print("Enter student address: ");
String saddr = sc.next();
String updateQuery = "UPDATE student SET s_name='" + sname + "',
s_address='" + saddr + "' WHERE s_id=" + sid;
s.executeUpdate(updateQuery);

System.out.println("Data updated successfully");

} catch (SQLException err) {


System.out.println("ERROR: " + err);
}
}
}

PS C:\Users\rames\OneDrive\1.PEC\2-2\Lab Programs\5> javac -cp ".;mysql-


connector-j-9.2.0.jar" UpdateData.java
PS C:\Users\rames\OneDrive\1.PEC\2-2\Lab Programs\5> java -cp ".;mysql-connector-
j-9.2.0.jar" UpdateData
Update Data in student table:
________________________________________
Enter student id: 1
Enter student name: Ramesh Kore
Enter student address: Data updated successfully

deleteData.java
### Description:
This Java file contains the implementation for database operations.

import java.sql.*;
import java.util.Scanner;

public class DeleteData {


public static void main(String[] args) {
try (Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "123456");
Statement s = con.createStatement()) { // Changed 'Statements' to
'Statement s'

Scanner sc = new Scanner(System.in);


System.out.println("Delete Data from student table:");
System.out.println("________________________________________");

System.out.print("Enter student id: ");


int sid = sc.nextInt();
String deleteQuery = "DELETE FROM student WHERE s_id=" + sid;
s.executeUpdate(deleteQuery);

System.out.println("Data deleted successfully");

} catch (SQLException err) {


System.out.println("ERROR: " + err);
}
}
}
bookstore.xml

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE bookstore[
<!ELEMENT bookstore (book+)>
<!ELEMENT book (title, author, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>
]>
<bookstore>
<book>
<title>Introduction to XML</title>
<author>John Doe</author>
<price>29.99</price>
</book>
<book>
<title>Programming with XML</title>
<author>Jane Smith</author>
<price>39.99</price>
</book>
</bookstore>

bookstore.xsd

<?xml version="1.0" encoding="UTF-8"?>


<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://example.com"
xmlns="http://example.com">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="bookstore" type="bookstoreType"/>
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:complexType name="bookstoreType">
<xs:sequence>
<xs:element name="book" type="bookType" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="bookType">
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:schema>

To Check the Validity :


1. Go to the below link,
https://www.liquid-technologies.com/online-xsd-validator
2. Place the XML code in the XML Validate.
3. Place the XSD code in the XML Schema Data.
4. Then click the validate Button.
5. Then it will show the Document as Valid.
7. Design a controller with servlet that provides the interaction with application developed
in experiment 1 and the database created in experiment 5

OUTPUT:
Session Tracking Mechanisms in JavaScript
Introduction:

Maintaining a user's transactional history is essential for modern web applications. From shopping
carts to user preferences, tracking user activity across multiple requests creates a seamless
experience. Since HTTP is stateless (each request is independent), we need session tracking
mechanisms to maintain state between requests.
In this guide, we'll explore various session tracking mechanisms in JavaScript, including cookies,
localStorage, sessionStorage, and server-side sessions, with practical code examples for each
approach.

Security Considerations and Limitations

Before diving into implementation, it's important to understand the security implications and
limitations of client-side storage:

 Security: Client-side storage (cookies, localStorage, sessionStorage) is inherently less


secure than server-side sessions. Never store sensitive data like passwords or financial
information in client-side storage.

 Size Limits: Cookies have a size limit (typically 4KB), while localStorage and
sessionStorage offer more storage (usually 5-10MB per domain).

 Persistence: Cookies can be configured to expire after a specific time, localStorage


persists until explicitly deleted, and sessionStorage is cleared when the browser session
ends.

 Accessibility: Cookies can be configured with HttpOnly to prevent JavaScript access


(improving security), while localStorage and sessionStorage are always accessible to
JavaScript.
 Transmission: Cookies are automatically sent with every HTTP request to the same
domain, which can increase bandwidth usage. localStorage and sessionStorage data stays
in the browser.

1. Cookie-Based Session Tracking

Cookies are small pieces of data stored on the client's browser that are sent back to the server with
each request.
Cookie Utility Functions:

index.js

// Function to set a cookie


function setCookie(name, value, days) {
let expires = "";
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

// Function to get a cookie value


function getCookie(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
}
return null;
}

// Function to delete a cookie


function eraseCookie(name) {
document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
Visit Counter Example Using Cookies:

index.html

<!DOCTYPE html>
<html>
<head>
<title>Cookie-Based Visit Counter</title>
<script>
// Cookie utility functions (from above)

// Function to handle page load


function handlePageLoad() {
// Check if user has visited before
let visitCount = getCookie('visitCount');

if (visitCount) {
// Returning user - increment counter
visitCount = parseInt(visitCount) + 1;
document.getElementById('message').textContent =
`Welcome back! You've visited this page ${visitCount} times.`;
} else {
// New user - initialize counter
visitCount = 1;
document.getElementById('message').textContent =
"Welcome! This is your first visit.";
}

// Update the cookie (expires in 30 days)


setCookie('visitCount', visitCount, 30);

// Display last visit time if available


const lastVisit = getCookie('lastVisit');
if (lastVisit) {
document.getElementById('lastVisit').textContent =
`Your last visit was: ${new Date(lastVisit).toLocaleString()}`;
}

// Update last visit time


setCookie('lastVisit', new Date().toString(), 30);
}

// Function to reset visit history


function resetHistory() {
eraseCookie('visitCount');
eraseCookie('lastVisit');
alert('Visit history has been reset.');
location.reload();
}
</script>
</head>
<body onload="handlePageLoad()">
<h1>Cookie-Based Visit Counter</h1>
<p id="message"></p>
<p id="lastVisit"></p>
<button onclick="resetHistory()">Reset Visit History</button>
</body>
</html>

Advantages of Cookies:

 Widely supported across browsers


 Can be set to expire after a specific time

 Automatically sent with HTTP requests (useful for server-side authentication)

 Can be made HttpOnly for better security

Limitations of Cookies:

 Limited to about 4KB of data

 Sent with every HTTP request (bandwidth overhead)

 Can be disabled by users

 Subject to CSRF attacks if not properly secured


2. LocalStorage for Session Tracking

localStorage provides persistent storage that remains available even after the browser is closed and
reopened.

LocalStorage Utility Functions:

Index2.js

// Function to store data in localStorage


function setLocalStorage(key, value) {
localStorage.setItem(key, JSON.stringify(value)); // Store as JSON string
}

// Function to retrieve data from localStorage


function getLocalStorage(key) {
const value = localStorage.getItem(key);
return value ? JSON.parse(value) : null; // Parse JSON string
}

// Function to remove data from localStorage


function removeLocalStorage(key) {
localStorage.removeItem(key);
}

Transaction Tracker Example Using LocalStorage:

Index2.html

<!DOCTYPE html>
<html>
<head>
<title>LocalStorage Transaction Tracker</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto;
padding: 20px; }
.transaction-form { background: #f8f9fa; padding: 20px; border-radius:
5px; margin-bottom: 20px; }
.transaction-list { list-style-type: none; padding: 0; }
.transaction-item { display: grid; grid-template-columns: 1fr 100px
150px; gap: 10px; padding: 10px; border-bottom: 1px solid #eee; }
</style>
<script>
// LocalStorage utility functions (from above)

const TransactionTracker = {
init: function() {
// Initialize transaction data if it doesn't exist
if (!localStorage.getItem('transactionData')) {
const initialData = {
count: 0,
transactions: [],
lastVisit: new Date().toISOString()
};
setLocalStorage('transactionData', initialData);
} else {
// Update last visit time
const data = this.getTransactionData();
data.lastVisit = new Date().toISOString();
setLocalStorage('transactionData', data);
}

// Display current data


this.displayTransactions();

// Set up event listeners


document.getElementById('transaction-
form').addEventListener('submit', this.addTransaction.bind(this));
document.getElementById('clear-button').addEventListener('click',
this.clearHistory.bind(this));
},

getTransactionData: function() {
return getLocalStorage('transactionData') || {count: 0, transactions:
[], lastVisit: ''};
},

addTransaction: function(event) {
event.preventDefault();

// Get form values


const description = document.getElementById('description').value;
const amount = parseFloat(document.getElementById('amount').value);

// Get current transaction data


const data = this.getTransactionData();

// Add new transaction


const transaction = {
id: data.count + 1,
description: description,
amount: amount,
date: new Date().toISOString()
};

data.transactions.push(transaction);
data.count++;

// Save updated data


setLocalStorage('transactionData', data);

// Update display
this.displayTransactions();

// Reset form
document.getElementById('transaction-form').reset();
},

displayTransactions: function() {
const historyElement = document.getElementById('transaction-
history');
const statsElement = document.getElementById('transaction-stats');
const data = this.getTransactionData();

// Update stats
statsElement.textContent = `Total transactions: ${data.count}`;

// Clear current list


historyElement.innerHTML = '';

// Display transactions
if (data.transactions.length === 0) {
historyElement.innerHTML = '<li>No transactions recorded
yet.</li>';
} else {
// Sort transactions by date (newest first)
const sortedTransactions = [...data.transactions].sort((a, b) =>
new Date(b.date) - new Date(a.date)
);

sortedTransactions.forEach(transaction => {
const date = new Date(transaction.date).toLocaleString();
const li = document.createElement('li');
li.className = 'transaction-item';
li.innerHTML = `
<span>${transaction.description}</span>
<span>$${transaction.amount.toFixed(2)}</span>
<span>${date}</span>
`;
historyElement.appendChild(li);
});
}
},

clearHistory: function() {
if (confirm('Are you sure you want to clear all transaction
history?')) {
const data = this.getTransactionData();
data.transactions = [];
data.count = 0;
setLocalStorage('transactionData', data);
this.displayTransactions();
}
}
};

// Initialize when DOM is loaded


document.addEventListener('DOMContentLoaded', function() {
TransactionTracker.init();
});
</script>
</head>
<body>
<h1>Transaction Tracker (LocalStorage)</h1>
<p>This example uses localStorage to maintain transaction history.</p>

<div class="transaction-form">
<h2>Add New Transaction</h2>
<form id="transaction-form">
<div>
<label for="description">Description:</label>
<input type="text" id="description" required>
</div>
<div>
<label for="amount">Amount ($):</label>
<input type="number" id="amount" step="0.01" min="0" required>
</div>
<button type="submit">Add Transaction</button>
</form>
</div>

<h2>Transaction History</h2>
<p id="transaction-stats">Total transactions: 0</p>
<button id="clear-button">Clear History</button>
<ul id="transaction-history" class="transaction-list">
<li>No transactions recorded yet.</li>
</ul>
</body>
</html>

Advantages of LocalStorage:

 Larger storage capacity (usually 5-10MB)

 Persists even after the browser is closed

 Not sent with HTTP requests (no bandwidth overhead)


 Simple API (setItem, getItem, removeItem)

Limitations of LocalStorage:

 Limited to string data (requires JSON serialization for objects)

 Synchronous API (can block the main thread)

 No automatic expiration mechanism

 Not shared between different browsers on the same device


3. SessionStorage for Session Tracking

SessionStorage works similarly to localStorage but is limited to the current browser session. Data
is cleared when the session ends (the browser tab is closed).

Index3.html

<!DOCTYPE html>
<html>
<head>
<title>SessionStorage Example</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto;
padding: 20px; }
.session-box { background: #f1f9fe; padding: 15px; border-radius: 5px;
margin-bottom: 20px; }
</style>
<script>
// SessionStorage utility functions
function setSessionStorage(key, value) {
sessionStorage.setItem(key, JSON.stringify(value));
}

function getSessionStorage(key) {
const value = sessionStorage.getItem(key);
return value ? JSON.parse(value) : null;
}

function removeSessionStorage(key) {
sessionStorage.removeItem(key);
}

// Session tracker
const SessionTracker = {
init: function() {
// Initialize session data if it doesn't exist
if (!sessionStorage.getItem('sessionData')) {
const initialData = {
startTime: new Date().toISOString(),
pageViews: 1,
actions: []
};
setSessionStorage('sessionData', initialData);
} else {
// Update page views
const data = this.getSessionData();
data.pageViews++;
setSessionStorage('sessionData', data);
}

// Display session info


this.displaySessionInfo();

// Set up event listeners


document.getElementById('action-form').addEventListener('submit',
this.recordAction.bind(this));
document.getElementById('end-session').addEventListener('click',
this.endSession.bind(this));

// Update session duration every second


setInterval(() => this.displaySessionInfo(), 1000);
},

getSessionData: function() {
return getSessionStorage('sessionData') || {startTime: '', pageViews: 0,
actions: []};
},

displaySessionInfo: function() {
const infoElement = document.getElementById('session-info');
const actionsElement = document.getElementById('action-list');
const data = this.getSessionData();

// Calculate session duration


const startTime = new Date(data.startTime);
const currentTime = new Date();
const durationMs = currentTime - startTime;
const durationMinutes = Math.floor(durationMs / 60000);
const durationSeconds = Math.floor((durationMs % 60000) / 1000);

// Display info
infoElement.innerHTML = `
<p>Session started: <strong>${startTime.toLocaleString()}</strong></p>
<p>Session duration: <strong>${durationMinutes}m
${durationSeconds}s</strong></p>
<p>Page views this session: <strong>${data.pageViews}</strong></p>
<p>Actions recorded: <strong>${data.actions.length}</strong></p>
`;
// Display actions
actionsElement.innerHTML = '';
if (data.actions.length === 0) {
actionsElement.innerHTML = '<li>No actions recorded in this
session.</li>';
} else {
data.actions.forEach(action => {
const time = new Date(action.timestamp).toLocaleTimeString();
const li = document.createElement('li');
li.textContent = `${time}: ${action.description}`;
actionsElement.appendChild(li);
});
}
},

recordAction: function(event) {
event.preventDefault();

// Get action description


const description = document.getElementById('action-description').value;

// Add to session data


const data = this.getSessionData();
data.actions.push({
description: description,
timestamp: new Date().toISOString()
});

// Save updated data


setSessionStorage('sessionData', data);

// Update display
this.displaySessionInfo();

// Reset form
document.getElementById('action-form').reset();
},

endSession: function() {
if (confirm('Are you sure you want to end this session? All session data
will be lost.')) {
sessionStorage.clear();
alert('Session ended. The page will now reload.');
window.location.reload();
}
}
};

// Initialize when DOM is loaded


document.addEventListener('DOMContentLoaded', function() {
SessionTracker.init();
});
</script>
</head>
<body>
<h1>Session Tracker (SessionStorage)</h1>
<p>This example uses sessionStorage to track user activity during the current
browser session.</p>

<div class="session-box">
<h2>Current Session Information</h2>
<div id="session-info">Loading session info...</div>
<button id="end-session">End Session</button>
</div>

<div>
<h2>Record Action</h2>
<form id="action-form">
<div>
<label for="action-description">Action Description:</label>
<input type="text" id="action-description" required>
</div>
<button type="submit">Record Action</button>
</form>
</div>

<h2>Session Activity</h2>
<ul id="action-list">
<li>No actions recorded in this session.</li>
</ul>

<div>
<p><strong>Note:</strong> All data is stored in sessionStorage and will be
lost when you close this browser tab.</p>
</div>
</body>
</html>
To use this example:

1. Create a new directory for your project

2. Initialize a Node.js project: npm init -y

3. Install dependencies: npm install express express-session


4. Save the code above as app.js

5. Run the server: node app.js

6. Visit http://localhost:3000 in your browser

Advantages of Server-Side Sessions:

 More secure for sensitive data

 Can store larger amounts of data

 Not accessible to client-side JavaScript

 Can be used with authentication systems


 Better control over session lifecycle

Limitations of Server-Side Sessions:

 Requires server-side storage (memory, database, etc.)

 Can impact server performance with many concurrent users

 Requires careful implementation to avoid security issues

 More complex to set up than client-side storage


5. AJAX with Server-Side Sessions

To interact with server-side sessions using JavaScript, you can use AJAX requests. Here's a simple
example:

Index4.html

<!DOCTYPE html>
<html>
<head>
<title>AJAX Session Example</title>
<script>
// Function to make AJAX requests
async function makeRequest(url, method = 'GET', data = null) {
const options = {
method,
credentials: 'include', // Important: include cookies in the request
headers: {}
};

if (data) {
options.headers['Content-Type'] = 'application/json';
options.body = JSON.stringify(data);
}

const response = await fetch(url, options);


if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
}

// Function to check session status


async function checkSession() {
try {
const data = await makeRequest('/api/session');
updateUI(data);
} catch (error) {
console.error('Error checking session:', error);
document.getElementById('status').textContent = 'Error: Could not check
session status.';
}
}

// Function to add a transaction


async function addTransaction(event) {
event.preventDefault();

const description = document.getElementById('description').value;


const amount = document.getElementById('amount').value;

try {
const data = await makeRequest('/api/transactions', 'POST', {
description, amount });
updateUI(data);
document.getElementById('transaction-form').reset();
} catch (error) {
console.error('Error adding transaction:', error);
document.getElementById('status').textContent = 'Error: Could not add
transaction.';
}
}

// Function to reset session


async function resetSession() {
try {
await makeRequest('/api/reset', 'POST');
checkSession();
} catch (error) {
console.error('Error resetting session:', error);
document.getElementById('status').textContent = 'Error: Could not reset
session.';
}
}

// Function
create server.js file

server.js

// Step 1: Import required modules


const http = require('http');
const os = require('os');
const path = require('path');
const { EventEmitter } = require('events');

// Step 2: Create an instance of EventEmitter


const eventEmitter = new EventEmitter();

// Step 3: Create a simple HTTP server


const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type':'text/plain' });
res.end('Hello, World!\n');
});

// Step 4: Define server port and hostname


const port = 3000;
const hostname = '127.0.0.1';

// Step 5: Listen for requests on the specified port and hostname


server.listen(port, hostname, () => {
console.log('Server running at http://${hostname}:${port}/');
});

// Step 6: Print OS information


console.log('OS Type:', os.type());
console.log('OS Platform:', os.platform());
console.log('OS Architecture:', os.arch());
console.log('CPU Cores:', os.cpus().length);

// Step 7: Print current working directory


console.log('Current Working Directory:', process.cwd());

// Step 8: Join paths using the path module


const joinedPath = path.join(__dirname, 'public', 'images');
console.log('Joined Path:', joinedPath);

// Step 9: Handle a custom event


eventEmitter.on('customEvent', (data) => {
console.log('Custom Event Triggered:', data);
});

// Step 10: Emit a custom event


eventEmitter.emit('customEvent', { message:'Hello from custom event!' });

OUTPUT:

Lab Programs\9\> node server.js


OS Type: Windows_NT
OS Platform: win32
OS Architecture: x64
CPU Cores: 12
Current Working Directory: D:\2-2\Lab Programs\9\9
Joined Path: D:\2-2\Lab Programs\9\9\public\images
Custom Event Triggered: { message: 'Hello from custom event!' }
Server running at http://${hostname}:${port}/
10. Develop an express web application that can interact with REST
API to perform CRUD operations on student data. (Use Postman)

Solution :

 Firstly we need to create a new folder and open the folder in the command
prompt and enter a command as below:

 npm init -y

 Open that folder in the vscode by entering code.


 Next in the terminal we need to install all the packages we need, so we mainly
use express and sqlite3.
 The Command to install express and sqlite3 is

 npm install express sqlite3

Then create file named as the app.js and db.js

package.js

{
"name": "10",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"express": "^5.1.0",
"sqlite3": "^5.1.7"
}
}
db.js
const sqlite3 = require('sqlite3').verbose();
// Function to initialize the database schema
function initializeDatabase() {
const db = new sqlite3.Database('./mydatabase.db', (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the SQLite database.');
createStudentsTable(db);
}
});

// Close the database connection when the Node process exits


process.on('exit', () => {
db.close((err) => {
if (err) {
console.error(err.message);
} else {
console.log('Disconnected from the SQLite database.');
}
});
});
}
// Function to create the 'students' table if it doesn't exist
function createStudentsTable(db) {
const createTableQuery = `
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER,
grade TEXT
);
`;
db.run(createTableQuery, (err) => {
if (err) {
console.error(err.message);
} else {
console.log('The students table has been created or already
exists.');
}
});
}
module.exports = { initializeDatabase };
app.js
const express = require('express');
const sqlite3 = require('sqlite3');
const{ initializeDatabase } = require('./db');
const app = express();
const port = 3000;

// Initialize the database and create tables


initializeDatabase();

// Connect to SQLite database


const db = new sqlite3.Database('./mydatabase.db', (err) => {
if (err) {
console.log(err.message);
} else {
console.log('Connected to the SQLite database.');
}
});

// Middleware to parse request body as JSON


app.use(express.json());

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


res.send('Welcome to the Student');
});

// Get all Students


app.get('/students', (req, res) => {
db.all('SELECT * FROM students', [], (err, rows) => {
if (err) {
return console.error(err.message);
}
res.json(rows);
});
});

// Get a single student by id


app.get('/students/:id', (req, res) => {
const id = req.params.id;
db.all('SELECT * FROM students WHERE id = ?', [id], (err, row) => {
if (err) {
return console.error(err.message);
}
res.json(row);
});
});

// Create a new student


app.post('/students', (req, res) => {
const{ name, age, grade } = req.body;
db.run('INSERT INTO students (name, age, grade) VALUES (?, ?, ?)', [name,
age, grade], function (err) {
if (err) {
return console.error(err.message);
}
res.status(201).json({ id:this.lastID });
});
});

// Update a student
app.put('/students/:id', (req, res) => {
const id = req.params.id;
const{ name, age, grade } = req.body;
db.run('UPDATE students SET name = ?, age = ?, grade = ? WHERE id = ?',
[name, age, grade, id], function (err) {
if (err) {
return console.error(err.message);
}
res.json({ updatedID:id });
});
});

// Delete a student
app.delete('/students/:id', (req, res) => {
const id = req.params.id;
db.run('DELETE FROM students WHERE id = ?', id, function (err) {
if (err) {
return console.error(err.message);
}
res.json({ deletedID:id });
});
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
OUTPUT
10. Develop an express web application that can interact with REST
API to perform CRUD operations on student data. (Use Postman)

11.For the above application create authorized end points using JWT
(JSON Web Token).

Solution :

 Firstly we need to create a new folder and open the folder in the command
prompt and enter a command as below:

 npm init -y

 Open that folder in the vscode by entering code.


 Next in the terminal we need to install all the packages we need, so we mainly
use express and sqlite3.
 The Command to install express and sqlite3 is

 npm install express sqlite3

Then create file named as the app.js and db.js

package.js

{
"name": "10",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"bcrypt": "^5.1.1",
"dotenv": "^16.5.0",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"sqlite3": "^5.1.7"
}
}

db.js

const sqlite3 = require('sqlite3').verbose();

// Function to initialize the database schema


function initializeDatabase() {
const db = new sqlite3.Database('./mydatabase.db', (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the SQLite database.');
createStudentsTable(db);
createUsersTable(db);
}
});

// Close the database connection when the Node process exits


process.on('exit', () => {
db.close((err) => {
if (err) {
console.error(err.message);
} else {
console.log('Disconnected from the SQLite database.');
}
});
});
}
// Function to create the 'students' table if it doesn't exist
function createStudentsTable(db) {
const createTableQuery = `
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER,
grade TEXT
);
`;

db.run(createTableQuery, (err) => {


if (err) {
console.error(err.message);
} else {
console.log('The students table has been created or alreadyexists.');
}
});
}

// Function to create the 'users' table if it doesn't exist


function createUsersTable(db) {
const createTableQuery = `
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE,
password TEXT,
role TEXT DEFAULT 'user'
);
`;

db.run(createTableQuery, (err) => {


if (err) {
console.error(err.message);
} else {
console.log('The users table has been created or already exists.');
}
});
}

module.exports = { initializeDatabase };

app.js

const express = require('express');


const { initializeDatabase } = require('./db');
require('dotenv').config();
// Import routes
const authRoutes = require('./routes/auth');
const studentRoutes = require('./routes/students');

const app = express();


const port = 3000;

// Initialize the database and create tables


initializeDatabase();

// Middleware to parse request body as JSON


app.use(express.json());

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


res.send('Welcome to the Student API - Use JWT for authentication');
});

// Use routes
app.use('/api/auth', authRoutes);
app.use('/api/students', studentRoutes);

// Error handling middleware


app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ message: 'Something went wrong!' });
});

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

Routes/auth.js

const express = require('express');


const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const sqlite3 = require('sqlite3');
require('dotenv').config();

const router = express.Router();

// Connect to SQLite database


const db = new sqlite3.Database('./mydatabase.db', (err) => {
if (err) {
console.log(err.message);
} else {
console.log('Connected to the SQLite database from auth routes.');
}
});

// Register a new user


router.post('/register', async (req, res) => {
try {
const { username, password, role } = req.body;

// Validate input
if (!username || !password) {
return res.status(400).json({message:'Username password required' });
}

// Check if user already exists


db.get('SELECT * FROM users WHERE username = ?', [username], async (err, user) =>
{
if (err) {
return res.status(500).json({ message: err.message });
}

if (user) {
return res.status(400).json({ message: 'User already exists' });
}

// Hash the password


const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

// Set default role to 'user' if not provided


const userRole = role || 'user';

// Insert the new user


db.run('INSERT INTO users (username, password, role) VALUES (?, ?, ?)',
[username, hashedPassword, userRole],
function(err) {
if (err) {
return res.status(500).json({ message: err.message });
}

// Create and assign a token


const token = jwt.sign(
{ id: this.lastID, username, role: userRole },
process.env.JWT_SECRET,
{ expiresIn: process.env.JWT_EXPIRES_IN }
);

res.status(201).json({
message: 'User registered successfully',
token,
user: { id: this.lastID, username, role: userRole }
});
}
);
});
} catch (error) {
res.status(500).json({ message: error.message });
}
});

// Login user
router.post('/login', (req, res) => {
try {
const { username, password } = req.body;

// Validate input
if (!username || !password) {
return res.status(400).json({message:'Username password required' });
}

// Find user
db.get('SELECT * FROM users WHERE username = ?', [username], async (err,
user) => {
if (err) {
return res.status(500).json({ message: err.message });
}

if (!user) {
return res.status(400).json({message:'Invalid usernamepassword'});
}

// Check password
const validPassword = await bcrypt.compare(password, user.password);
if (!validPassword) {
return res.status(400).json({message:'Invaliduusernamepassword'});
}

// Create and assign a token


const token = jwt.sign(
{ id: user.id, username: user.username, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: process.env.JWT_EXPIRES_IN }
);

res.json({
message: 'Login successful',
token,
user: { id: user.id, username: user.username, role: user.role }
});
});
} catch (error) {
res.status(500).json({ message: error.message });
}
});

module.exports = router;

Routes/students.js

const express = require('express');


const sqlite3 = require('sqlite3');
const { verifyToken, isAdmin } = require('../middleware/auth');

const router = express.Router();

// Connect to SQLite database


const db = new sqlite3.Database('./mydatabase.db', (err) => {
if (err) {
console.log(err.message);
} else {
console.log('Connected to the SQLite database from student routes.');
}
});

// Get all Students (requires authentication)


router.get('/', verifyToken, (req, res) => {
db.all('SELECT * FROM students', [], (err, rows) => {
if (err) {
return res.status(500).json({ message: err.message });
}
res.json(rows);
});
});

// Get a single student by id (requires authentication)


router.get('/:id', verifyToken, (req, res) => {
const id = req.params.id;
db.all('SELECT * FROM students WHERE id = ?', [id], (err, row) => {
if (err) {
return res.status(500).json({ message: err.message });
}
res.json(row);
});
});

// Create a new student (requires admin role)


router.post('/', verifyToken, isAdmin, (req, res) => {
const { name, age, grade } = req.body;

// Validate input
if (!name || !age || !grade) {
return res.status(400).json({message:'Name, age, grade are required'});
}

db.run('INSERT INTO students (name, age, grade) VALUES (?, ?, ?)',


[name, age, grade],
function (err) {
if (err) {
return res.status(500).json({ message: err.message });
}
res.status(201).json({ id: this.lastID });
}
);
});

// Update a student (requires admin role)


router.put('/:id', verifyToken, isAdmin, (req, res) => {
const id = req.params.id;
const { name, age, grade } = req.body;

// Validate input
if (!name || !age || !grade) {
return res.status(400).json({ message:'Name, age, grade are required'});
}

db.run('UPDATE students SET name = ?, age = ?, grade = ? WHERE id = ?',


[name, age, grade, id],
function (err) {
if (err) {
return res.status(500).json({ message: err.message });
}
res.json({ updatedID: id });
}
);
});

// Delete a student (requires admin role)


router.delete('/:id', verifyToken, isAdmin, (req, res) => {
const id = req.params.id;
db.run('DELETE FROM students WHERE id = ?', id, function (err) {
if (err) {
return res.status(500).json({ message: err.message });
}
res.json({ deletedID: id });
});
});

module.exports = router;

middleware/auth.js

const jwt = require('jsonwebtoken');


require('dotenv').config();

// Middleware to verify JWT token


const verifyToken = (req, res, next) => {
// Get the token from the Authorization header
const authHeader = req.headers.authorization;

if (!authHeader || !authHeader.startsWith('Bearer ')) {


return res.status(401).json({ message: 'Access denied. No token
provided.' });
}

const token = authHeader.split(' ')[1];


try {
// Verify the token
const decoded = jwt.verify(token, process.env.JWT_SECRET);

// Add the user info to the request object


req.user = decoded;

next();
} catch (error) {
res.status(401).json({ message: 'Invalid token.' });
}
};

// Middleware to check if user has admin role


const isAdmin = (req, res, next) => {
if (req.user && req.user.role === 'admin') {
next();
} else {
res.status(403).json({ message: 'Access denied. Admin role required.' });
}
};

module.exports = { verifyToken, isAdmin };

OUTPUT

POST http://localhost:3001/api/auth/register

Body:

"username": "admin",

"password": "admin123",
"role": "admin"

}
POST http://localhost:3001/api/auth/login

Body:

"username": "admin",
"password": "admin123"

3. Use the token returned from the login response in your Authorization header.

If you're using a tool like Postman, make sure to:

1. Set the correct URL with port 3000

2. Include the /api/ prefix in the URL

3. Set the Authorization header with your JWT token

4. Set the Content-Type header to application/json


5. Include the required fields in the request body
12. Create a react application for the student management system having registration, login,
contact, about pages and implement routing to navigate through these pages

12> npm create vite@latest student-management-system -- --template react


npx
> create-vite student-management-system react


◆ Select a framework:
│ ● Vanilla
│ ○ Vue
│ ○ React
│ ○ Preact
│ ○ Lit
│ ○ Svelte
│ ○ Solid
│ ○ Qwik
│ ...

Select Vanilla

Select a variant:
│ ○ TypeScript
│ ● JavaScript

Select JavaScript

Scaffolding project in D:\2-2\Lab Programs\12.1\student-management-system...



└ Done. Now run:

cd student-management-system
npm install

12>cd student-management-system
12/cd student-management-system>npm install [email protected]
12/cd student-management-system>npm install [email protected]

**Set up project structure**


student-management-system/
├── public/
│ └── vite.svg
├── src/
│ ├── components/
│ │ └── Navbar.js
│ ├── pages/
│ │ ├── About.js
│ │ ├── Contact.js
│ │ ├── Home.js
│ │ ├── Login.js
│ │ └── Register.js
│ ├── App.js
│ ├── main.js
│ └── style.css
├── index.html
├── package.json
└── package-lock.json
```
**Install dependencies**
12/student-management-system> npm install
12/student-management-system> npm run dev
Package.json
{
"name": "student-management-system",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"devDependencies": {
"vite": "^6.3.1"
},
"dependencies": {
"bootstrap": "^5.3.5",
"react-router-dom": "^7.5.0"
}
}
index.html

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Student Management System</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

// C:\Users\rames\OneDrive\1.PEC\2-2\LabPrograms\12\src\pages\About.js
import React from 'react';

function About() {
return React.createElement('div', { className: 'container mt-5' },
React.createElement('h2', null, 'About Student Management System'),
React.createElement('div', { className: 'card mt-4' },
React.createElement('div', { className: 'card-body' },
React.createElement('h5', { className: 'card-title' }, 'Our Mission'),
React.createElement('p', { className: 'card-text' },
'The Student Management System is designed to streamline the process of
managing student information, ' +
'course registrations, and academic records. Our goal is to provide an
efficient and user-friendly ' +
'platform for both students and administrators.'
)
)
),
React.createElement('div', { className: 'card mt-4' },
React.createElement('div', { className: 'card-body' },
React.createElement('h5', { className: 'card-title' }, 'Features'),
React.createElement('ul', { className: 'list-group list-group-flush' },
React.createElement('li', { className: 'list-group-item' }, 'Student
Registration and Login'),
React.createElement('li', { className: 'list-group-item' }, 'Course
Management'),
React.createElement('li', { className: 'list-group-item' }, 'Grade
Tracking'),
React.createElement('li', { className: 'list-group-item' }, 'Attendance
Monitoring'),
React.createElement('li', { className: 'list-group-item' }, 'Performance
Analytics')
)
)
),

React.createElement('div', { className: 'card mt-4' },


React.createElement('div', { className: 'card-body' },
React.createElement('h5', { className: 'card-title' }, 'Our Team'),
React.createElement('p', { className: 'card-text' },
'Our team consists of dedicated developers and educators who are committed
to improving ' +
'the educational experience through technology. We continuously work to
enhance the system ' +
'based on feedback from users.'
)
)
)
);
}

export default About;

// C:\Users\rames\OneDrive\1.PEC\2-2\LabPrograms\12\src\pages\Register.js
import React, { useState } from 'react';

function Register() {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
confirmPassword: '',
studentId: ''
});

const handleChange = (e) => {


const { name, value } = e.target;
setFormData({
...formData,
[name]: value
});
};

const handleSubmit = (e) => {


e.preventDefault();
// Here you would typically send the data to a server
console.log('Registration data:', formData);
alert('Registration successful!');
// Clear form
setFormData({
name: '',
email: '',
password: '',
confirmPassword: '',
studentId: ''
});
};

return React.createElement('div', { className: 'container mt-5' },


React.createElement('div', { className: 'row justify-content-center' },
React.createElement('div', { className: 'col-md-6' },
React.createElement('div', { className: 'card' },
React.createElement('div', { className: 'card-header' },
React.createElement('h3', { className: 'text-center' }, 'Student
Registration')
),
React.createElement('div', { className: 'card-body' },
React.createElement('form', { onSubmit: handleSubmit },
React.createElement('div', { className: 'mb-3' },
React.createElement('label', { htmlFor: 'name', className: 'form-
label' }, 'Full Name'),
React.createElement('input', {
type: 'text',
className: 'form-control',
id: 'name',
name: 'name',
value: formData.name,
onChange: handleChange,
required: true
})
),
React.createElement('div', { className: 'mb-3' },
React.createElement('label', { htmlFor: 'email', className: 'form-
label' }, 'Email address'),
React.createElement('input', {
type: 'email',
className: 'form-control',
id: 'email',
name: 'email',
value: formData.email,
onChange: handleChange,
required: true
})
),
React.createElement('div', { className: 'mb-3' },
React.createElement('label', { htmlFor: 'studentId', className:
'form-label' }, 'Student ID'),
React.createElement('input', {
type: 'text',
className: 'form-control',
id: 'studentId',
name: 'studentId',
value: formData.studentId,
onChange: handleChange,
required: true
})
),
React.createElement('div', { className: 'mb-3' },
React.createElement('label', { htmlFor: 'password', className: 'form-
label' }, 'Password'),
React.createElement('input', {
type: 'password',
className: 'form-control',
id: 'password',
name: 'password',
value: formData.password,
onChange: handleChange,
required: true
})
),
React.createElement('div', { className: 'mb-3' },
React.createElement('label', { htmlFor: 'confirmPassword', className:
'form-label' }, 'Confirm Password'),
React.createElement('input', {
type: 'password',
className: 'form-control',
id: 'confirmPassword',
name: 'confirmPassword',
value: formData.confirmPassword,
onChange: handleChange,
required: true
})
),
React.createElement('button', { type: 'submit', className: 'btn btn-
primary w-100' }, 'Register')
)
)
)
)
)
);
}

export default Register;


12/student-management-system> npm run dev

Open URL at http://localhost:5173/

In Browser

http://localhost:5173/
http://localhost:5173/register

http://localhost:5173/login
http://localhost:5173/about

http://localhost:5173/contact
Step 1: Create an OpenWeatherMap Account and Generate API Key

 Visit the OpenWeatherMap website (https://openweathermap.org/) and click on "Sign


Up" or "Log In" to create an account or log into your existing account.
 Once logged in, navigate to your account dashboard.
 From the dashboard, locate my API Keys section and click on "Create Key" or "API
Keys" to generate a new API key.
 Provide a name for your API key (e.g., "WeatherApp") and click on the "Generate" or
"Create" button.
 Your API key will be generated and displayed on the screen. Make sure to copy it as we
will need it later.
Locate API key

Step 2: Set up a new React project

 Open your terminal or command prompt.


 Run the following command to create a new React project:

npx create-react-app weather-app

 Once the project is created, navigate into the project directory:

cd weather-app
Step 3: Install required packages

In the project directory, install the necessary packages by executing the following command

npm install axios

We will use the Axios library to make HTTP requests to the OpenWeatherMap API.

Step 4: Create a Weather component

 Inside the "src" directory, create a new file called "Weather.js" and open it in your code
editor.
 Add the following code to define a functional component named Weather:

Weather.js

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


import axios from 'axios';

const Weather = () => {


const [city, setCity] = useState('');
const [weatherData, setWeatherData] = useState(null);

const fetchData = async () => {


try {
const apiKey = '349e1822e8739db21980838d35c0354a'; // Replace with your
OpenWeatherMap API key
const response = await axios.get(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&a
ppid=${apiKey}` // Changed to backticks
);
setWeatherData(response.data);
console.log(response.data); //You can see all the weather data in console
log
} catch (error) {
console.error(error);
}
};
useEffect(() => {
fetchData();
}, []);

const handleInputChange = (e) => {


setCity(e.target.value);
};

const handleSubmit = (e) => {


e.preventDefault();
fetchData();
};

return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Enter city name"
value={city}
onChange={handleInputChange}
/>
<button type="submit">Get Weather</button>
</form>
{weatherData ? (
<>
<h2>{weatherData.name}</h2>
<p>Temperature: {weatherData.main.temp} C</p>
<p>Description: {weatherData.weather[0].description}</p>
<p>Feels like : {weatherData.main.feels_like} C</p>
<p>Humidity : {weatherData.main.humidity}%</p>
<p>Pressure : {weatherData.main.pressure}</p>
<p>Wind Speed : {weatherData.wind.speed}m/s</p>
</>
) : (
<p>Loading weather data...</p>
)}
</div>
);
};

export default Weather;


Replace {YOUR_API_KEY} in the API URL with the API key you generated from
OpenWeatherMap.
Step 5: Connect the Weather component to your app.

 Open the "App.js" file in the "src" directory.


 Replace the existing code with the following code:
App.js

import React from'react';


import Weather from'./Weather';

const App = () => {


return (
<div>
<h1>Weather Forecast App</h1>
<Weather />
</div>
);
};

export default App;

LabPrograms\13\weather-app> npm start


Step 1: Set up a new React project

 Open your terminal or command prompt.


 Run the following command to create a new React project:

npx create-react-app todo-app

 Once the project is created, navigate into the project directory:

cd todo-app

Step 2: Install required packages

In the project directory, install the necessary packages by executing the following command

npm install

We will use the Axios library to make HTTP requests to the OpenWeatherMap API.

Step 3: Create all components


package.json

{
"name": "todo-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
App.css

.App {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f5f5f5;
}

.todo-container {
background-color: white;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 500px;
}

h1 {
text-align: center;
color: #333;
margin-bottom: 2rem;
}

.todo-form {
display: flex;
gap: 1rem;
margin-bottom: 2rem;
}

.todo-input {
flex: 1;
padding: 0.5rem;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 1rem;
}

.todo-button {
padding: 0.5rem 1rem;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
}

.todo-button:hover {
background-color: #45a049;
}

.todo-list {
list-style: none;
padding: 0;
margin: 0;
}

.todo-item {
display: flex;
align-items: center;
gap: 1rem;
padding: 0.5rem;
border-bottom: 1px solid #eee;
}

.todo-item:last-child {
border-bottom: none;
}

.todo-item input[type="checkbox"] {
margin-right: 0.5rem;
}

.todo-item span {
flex: 1;
}

.delete-button {
padding: 0.25rem 0.5rem;
background-color: #ff4444;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}

.delete-button:hover {
background-color: #cc0000; }
App.js

import React, { Component, useState } from 'react';


import './App.css';
import TodoForm from './components/TodoForm';
import TodoList from './components/TodoList';

function App() {
const [todos, setTodos] = useState([]);

const addTodo = (text) => {


if (text.trim() !== '') {
const newTodo = {
id: Date.now(),
text: text,
completed: false
};
setTodos([...todos, newTodo]);
}
};

const toggleTodo = (id) => {


setTodos(
todos.map(todo =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo
)
);
};

const deleteTodo = (id) => {


setTodos(todos.filter(todo => todo.id !== id));
};

return (
<div className="App">
<div className="todo-container">
<h1>Todo List</h1>
<TodoForm onSubmit={addTodo} />
<TodoList
todos={todos}
onToggle={toggleTodo}
onDelete={deleteTodo}
/>
</div>
</div>
);
}

export default App;

index.css

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

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

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

import React from 'react';


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

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

src/omponents/TodoForm.js

import React, { useState } from 'react';

function TodoForm({ onSubmit }) {


const [text, setText] = useState('');

const handleSubmit = (e) => {


e.preventDefault();
onSubmit(text);
setText('');
};

return (
<form onSubmit={handleSubmit} className="todo-form">
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Add a new todo..."
className="todo-input"
/>
<button type="submit" className="todo-button">
Add
</button>
</form>
);
}
export default TodoForm;

src/components/TodoList.js

import React from 'react';

function TodoList({ todos, onToggle, onDelete }) {


return (
<ul className="todo-list">
{todos.map(todo => (
<li key={todo.id} className="todo-item">
<input
type="checkbox"
checked={todo.completed}
onChange={() => onToggle(todo.id)}
/>
<span
style={{
textDecoration: todo.completed ? 'line-through' : 'none'
}}
>
{todo.text}
</span>
<button
onClick={() => onDelete(todo.id)}
className="delete-button"
>
Delete
</button>
</li>
))}
</ul>
);
}

export default TodoList;


todo-app/public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Todo List Application created using React"
/>
<title>Todo List App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

After saving

LabPrograms\14\todo-app> npm start


Uploading a Project to GitHub Using Git
Introduction
Git is a powerful version control system that allows developers to track changes, collaborate, and
manage project history efficiently. This guide provides step-by-step instructions on how to
upload a project to GitHub using Git.

Prerequisites
Before proceeding, ensure you have the following:

 A GitHub account (Sign up at GitHub).


 Git installed on your computer. To check, run git --version in your terminal. If not
installed, download it from git-scm.com.
 A project folder containing the files you wish to upload.

Step 1: Configure Git


Before using Git, configure it with your credentials:

1. Set your username:


2. git config --global user.name "Your Name"
3. Set your email (use the same email associated with your GitHub account):
4. git config --global user.email "[email protected]"
5. Verify the configuration:
6. git config --list

Step 2: Create a New Repository on GitHub


1. Log in to your GitHub account.
2. Click the + icon in the top-right corner and select New repository.
3. Enter a repository name and an optional description.
4. Select the repository’s visibility (Public or Private).
5. Do not initialize the repository with a README, .gitignore, or license.
6. Click Create repository.

Step 3: Initialize Git in Your Project


1. Open a terminal or command prompt.
2. Navigate to your project directory using:
3. cd /path/to/your/project
4. Initialize Git in the directory:
5. git init
Step 3: Add and Commit Files
1. Add all project files to Git tracking:
2. git add .
3. Commit the changes with a descriptive message:
4. git commit -m "Initial commit"

Step 4: Link the Local Repository to GitHub


1. Copy the repository URL from GitHub (e.g.,
https://github.com/yourusername/repository.git ).
2. Add the remote repository:
3. git remote add origin https://github.com/yourusername/repository.git
4. Verify the remote URL:
5. git remote -v

Step 5: Push the Project to GitHub


1. Push the committed changes to GitHub:
2. git branch -M main
3. git push -u origin main
4. You may be prompted to enter your GitHub credentials.

Conclusion
Your project is now successfully uploaded to GitHub. You can view it by navigating to your
repository URL in a web browser. Git allows you to track changes, collaborate, and manage
project history efficiently.

Next Steps
 Clone your repository on another machine: git clone
https://github.com/yourusername/repository.git
 Make and push changes:
 git add .
 git commit -m "Updated feature"
 git push origin main
 Pull the latest changes from GitHub:
 git pull origin main

You might also like