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

FSWD Final Record

Uploaded by

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

FSWD Final Record

Uploaded by

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

Ex.

No:

Date:

Ex. No: 01 Design the following static web pages required for an online book store web site.
1.HOME PAGE: The static home page must contain three frames.2.LOGIN
Date: PAGE 3.CATOLOGUE PAGE: The catalogue page should contain the details of
all the books available in the web site in a table. 4. REGISTRATION PAGE.

AIM:

To design the following static web are required for an online book store web site with
home page, login, registration, catalogue pages.

PROCEDURE:

Step-1: Start the Program.

Step-2: The static home page must contain three frames.Top frame, Left frame, Right
frame.

Step-3: The login page contains the user name and the password of the user to
authenticate.

Step-4: The catalogue page should contain the details of all the books available in the
web site in a table.

Step-5: To create the Website home page.

Step-6: File is saved with html document.

5
IMPLEMENTATION:

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Online Book Store</title>
</head>
<frameset rows="15%,10%,*">
<frameset cols="20%,*">
<frame name="f11" src="logo.html" scrolling="no"></frame>
<frame name="f12" src="title.html" scrolling="no"></frame>
</frameset>
<frameset cols="20%,20%,20%,20%,*">
<frame name="f21" src="home.html"></frame>
<frame name="f22" src="login.html"></frame>
<frame name="f23" src="reg.html"></frame>
<frame name="f24" src="cat.html"></frame>
<frame name="f25" src="cart.html"></frame>
</frameset>
<frameset cols="20%,*">
<frame name="f31" src="branches.html"></frame>
<frame name="f32" src="homepage.html"></frame>
</frameset>
</frameset>
</html>

logo.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<center><img src="images/logo.jpg" width="100" height="100" /></center>
</body>

6
</html>
title.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<h1 align="center">Online Book Store</h1>
</body>
</html>

home.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<a href="homepage.html" target="f32">Home</a>
</body>
</html>

login.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<a href="loginpage.html" target="f32">Login</a>
</body>
</html>

reg.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>

7
</head>
<body>
<a href="regpage.html" target="f32">Registration</a>
</body>
</html>

cat.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<a href="catpage.html" target="f32">Catalogue</a>
</body>
</html>

cart.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<a href="cartpage.html" target="f32">Cart</a>
</body>
</html>

branches.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<ul>
<li>Civil</li>
<li>EEE</li>
<li>Mech</li>
<li>ECE</li>
<li>CSE</li>
<li>MBA</li>

8
<li>MCA</li>
</ul>
</body>
</html>

homepage.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<p align="justify">Welcome to Online Book Store.<br>Here you find all types of books, magazines and
national and international journals.</p>
</body>
</html>

loginpage.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<form>
<table align="center" cellspacing="15px">
<tr>
<td><b>Login</b></td>
<td><input type="text" name="uname" /></td>
</tr>
<tr>
<td><b>Password</b></td>
<td><input type="password" name="upwd" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" />&nbsp; &nbsp;
<input type="reset" />
</td>
</tr>
</table>
</form>
</body>
</html>

regpage.html

<!DOCTYPE html>

9
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form>
<h1 align="center"> REGISTRATION </h1>
<table align="center" cellspacing="10">
<tr>
<td>Name::</td>
<td> <input name="uname" type="text"> </td>
</tr>
<tr>
<td>Password::</td>
<td> <input name="pwd" type="password"> </td>
</tr>
<tr>
<td> E-mail ID:: </td>
<td> <input name="email" type="text"> </td>
</tr>
<tr>
<td> Phone Number:: </td>
<td> <input name="phno" type="text" maxlength="10"> </td>
</tr>
<tr>
<td> Gender:: </td>
<td><input name="gender" type="radio" value="Male">&nbsp;&nbsp;Male &nbsp;&nbsp;&nbsp;&nbsp;

<input name="gender" type="radio" value="Female">&nbsp;&nbsp;Female</td>


</tr>
<tr>
<td> Date of Birth </td>
<td>
<input type="date" name="dob" />
</td>
</tr>
<tr>
<td valign="top">Languages Known::</td>
<td>
<input name="lk" type="checkbox" value="English">&nbsp;English<br>
<input name="lk" type="checkbox" value="Telugu">&nbsp;Telugu<br>
<input name="lk" type="checkbox" value="Hindi">&nbsp;Hindi<br>
<input name="lk" type="checkbox" value="Tamil">&nbsp;Tamil<br>
</td>
</tr>
<tr>
<td>Address</td>
<td><textarea></textarea></td>
</tr>
<tr>
<td colspan="2" align="center"> <input type="submit"
value="Register">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

10
<input type="reset" value="Cancel"> </td>
</tr>
</table>
</form>
</body>
</html>

catpage.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form>
<table cellspacing="10">
<tr>
<td><img src="images/html5.jpg" width="100" height="100"></td>
<td> Title : HTML5 and CSS3 <br>
Author : Sasha Vodnik&nbsp; &nbsp;<br> </td>
<td>Rs. 700 /- </td>
<td><input type="image" src="images/addToCart.jpg" width="150" height="70"></td>
</tr>
<tr>
<td><img src="images/php.jpg" width="100" height="100"></td>
<td> Title : PHP and MYSQL <br>
Author : W. Jason Gilmore&nbsp; &nbsp;<br> </td>
<td>Rs. 650 /- </td>
<td><input type="image" src="images/addToCart.jpg" width="150" height="70"></td>
</tr>
<tr>
<td><img src="images/j2ee.jpg" width="100" height="100"></td>
<td> Title : The Complete Reference JAVA 2 <br>
Author : Herbert Schildt &nbsp; &nbsp;<br> </td>
<td>Rs. 850 /- </td>
<td><input type="image" src="images/addToCart.jpg" width="150" height="70"></td>
</tr>
</table>
</form>
</body>
</html>

cartpage.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>

11
</head>
<body>
<h1 align="center">Shopping Cart</h1>
<form>
<table align="center" cellpadding="20px">
<tr>
<th>Product</th>
<th>Description</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
</tr>
<tr>
<td><img src="images/html5.jpg" width="100" height="100" /></td>

<td>Title : HTML5 and CSS3 <br>Author : Sasha Vodnik</td>


<td>Rs. 700 /-</td>
<td><input type="text" size="2" value="1" readonly /></td>
<td>Rs. 700 /-</td>
</tr>
<tr>
<td><img src="images/php.jpg" width="100" height="100" /></td>
<td>Title : PHP and MYSQL <br>Author : W. Jason Gilmore </td>
<td>Rs. 650 /- </td>
<td><input type="text" size="2" value="1" readonly /></td>
<td>Rs. 650 /- </td>
</tr>
<tr>
<th colspan="2">Promotion Code</td>
<th colspan="3">Cart Totals</td>
</tr>
<tr>
<td colspan="2"><input type="text" placeholder="Coupon code" /> &nbsp; <input type="button"
value="Apply Coupon" /></td>
<th colspan="2">Subtotal</th>
<td>Rs. 1350 /-</td>
</tr>
<tr>
<td colspan="2"></td>
<th colspan="2">Total</th>
<th>Rs. 1350 /-</th>
</tr>
<tr>
<td colspan="5" align="right"><input type="button" value="Proceed to Checkout" /></td>
</tr>
</table>
</form>
</body>
</html>

PaymentGateway.html

<!DOCTYPE html>

12
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Payment Gateway</title>
</head>
<body>
<h1 align="center">Credit Card Payment Gateway</h1>
<hr>
<form>
<table align="center" cellpadding="20px">
<tr>
<td colspan="2" align="center"><h2>Payment Details</h2></td>
</tr>
<tr>
<td colspan="2">
<b>CARD NUMBER</b><br>
<input type="text" placeholder="Valid Card Number" size="52" />
</td>
</tr>
<tr>
<td><b>Expire Date</b><br><input type="text" placeholder="MM/YY" /></td>

<td><b>CV Code</b><br><input type="text" placeholder="CVV" /></td>


</tr>
<tr>
<td colspan="2">
<b>CARD OWNER</b><br>
<input type="text" placeholder="Card Owner Name" size="52" />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="button" value="Confirm Payment">
</td>
</tr>
</table>
</form>
</body>
</html>

13
OUTPUT:

HOME PAGE:

14
LOGIN PAGE:

REGISTRATION FORM:

CATALOGUE:

15
CART:

16
RESULT:

Thus the home page, login page, catalogue page for the online book store are created
successfully and the output is verified.

Ex. No: 02 Write JavaScript to validate the following fields of the Registration page. 1.First
Name (Name should contains alphabets and the length should not be less than 6
Date: characters). 2. Password (Password should not be less than 6 characters length).
3. E-mail id (should not contain any invalid and must follow the standard
pattern [email protected]) 4. Mobile Number (Phone number should contain
10 digits only). 5. Last Name and Address (should not be Empty)

AIM:

To write JavaScript to validate the following fields of the Registration page. 1.First Name
(Name should contains alphabets and the length should not be less than 6 characters). 2.
Password (Password should not be less than 6 characters length). 3. E-mail id (should not contain
any invalid and must follow the standard pattern [email protected]) 4. Mobile Number (Phone
number should contain 10 digits only). 5. Last Name and Address (should not be Empty)

PROCEDURE:

STEP 1: Start the Program.


STEP 2: First to create a HTML webpage on index.html file.
STEP 3: Next create the file index.js using javascript file.
STEP 4: Simultaneously we have to create the cascading file.
STEP 5: And last to run the HTML page in your browser.
STEP 6: Stop the Program.

17
PROGRAM:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>REGISTRATION PAGE</h1>
<form name="registrationForm" onsubmit="return validateForm()">
<label for="firstName">First Name:</label><br>
<input type="text" id="firstName" name="firstName"><br>

<label for="lastName">Last Name:</label>


<input type="text" id="lastName" name="lastName"><br>

<label for="address">Address:</label>
<input type="text" id="address" name="address"><br>

18
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>

<label for="mobile">Mobile Number:</label>


<input type="tel" id="mobile" name="mobile"><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>

<input type="submit" value="Submit">


</form>
</body>
<script src="index.js"></script>
</html>

Index.js:

function validateForm() {
var firstName = document.forms["registrationForm"]["firstName"].value;
var lastName = document.forms["registrationForm"]["lastName"].value;
var address = document.forms["registrationForm"]["address"].value;
var email = document.forms["registrationForm"]["email"].value;
var mobile = document.forms["registrationForm"]["mobile"].value;
var password = document.forms["registrationForm"]["password"].value;

// Validate first name


var firstNameRegex = /^[a-zA-Z]{6,}$/;
if (!firstNameRegex.test(firstName)) {
alert(
"First name must contain alphabets and be at least 6 characters long."
);
return false;
}

// Validate last name


if (lastName == "") {
alert("Last name must be filled out.");
return false;
}

// Validate address
if (address == "") {
alert("Address must be filled out.");
return false;
}

// Validate email
var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

19
if (!emailRegex.test(email)) {
alert("Invalid email address.");
return false;
}

// Validate mobile number


var mobileRegex = /^\d{10}$/;
if (!mobileRegex.test(mobile)) {
alert("Mobile number must contain 10 digits.");
return false;
}

// Validate password
var passwordRegex = /^[a-zA-Z0-9]{6,}$/;
if (!passwordRegex.test(password)) {
alert(
"Password must be at least 6 characters long and contain only alphanumeric characters."
);
return false;
}

// If all fields are valid, submit the form


return true;
}

Style.css:

form {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 50px;
border-radius: 20px;
background: rgba(255, 255, 255, 0.06);
border: 1px solid rgba(94, 28, 28, 0.3);
}

h1 {
color: #4caf50;
align-items: center;
justify-content: center;
display: flex;
}

label {
font-weight: bold;
margin-bottom: 10px;
text-transform: uppercase;
}

input[type="text"],
input[type="email"],

20
input[type="tel"],
input[type="password"] {
padding: 10px;
margin-bottom: 20px;
border-radius: 5px;
box-shadow: 0 0 5px rgba(224, 0, 0, 0.1);
}

input[type="submit"] {
background-color: #4caf50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}

input[type="submit"]:hover {
background-color: #3e8e41;
}

OUTPUT:

21
RESULT:
Thus the above program has been executed successfully and the output is verified
Ex. No: 03

Date: Write a javascript to create a Employee Enrollment form and validate the
contents of the form

AIM:
To create an Employee Enrollment form and validate the contents using javascript,

PROCEDURE:

Step 1: Start the program

Step 2: Create an HTML file index.html.

Step 3: Next create a CSS file using style.css.

Step 4: Next validate the content of the form using JavaScript and execute the form.

Step 5: Stop the program

22
IMPLEMENTATION:
index.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Registration Form</title>

<link rel="stylesheet" href="style.css">

</head>

<body>

23
<form name="RegForm" method="post">

<div class="container">

<h1>Registration Form</h1>

<p id="error"></p>

<p>Name: <br> <input type="text" placeholder="Full Name" size="65" name="Name" ></p>

<p>Address: <br> <input type="text" size="65" name="Address"></p>

<p>Email Id: <br> <input type="email" placeholder="[email protected]" size="65" name="EMail"></p>

<p>Phone No: <br> <input type="tel" placeholder="9876543210" size="65" name="PhoneNo"></p>

<p>Password: <br> <input type="password" size="65" name="Password"></p>

<p>

SELECT YOUR COURSE

<br>

<select type="text" value="" name="Subject">

<option>Select Any one</option>

<option>BBA</option>

<option>BCA</option>

<option>MBA</option>

<option>MCA</option>

</select>

</p>

<div class="But">

<button class="sub" type="submit" value="Send" name="submit">submit</button>

<button class="rst" type="reset" value="Reset" name="reset">reset</button>

</div>

</div>

</form>

<script src="./index.js"></script>

</body>

</html>

index.js:

var regform = document.getElementsByName("RegForm")[0];

var name = document.getElementsByName("Name")[0];

24
var address = document.getElementsByName("Address")[0];

var email = document.getElementsByName("EMail")[0];

var phoneno = document.getElementsByName("PhoneNo")[0];

var passwd = document.getElementsByName("Password")[0];

var error = document.getElementById("error");

phoneno.addEventListener("input", (e) => {

var value = e.target.value;

var lastCharacter = value.at(-1);

if(!/\d/.test(lastCharacter)){

phoneno.value = value.slice(0, value.length - 1);

});

regform.addEventListener("submit", (e) => {

e.preventDefault();

errorElement.innerText = "";

var error = validateForm();

if (error) {

errorElement.innerText = error;

return;

console.log("Form Submitter!");

});

function validateForm(){

let error = "";

25
if(!address.value || address.value.length < 5){

address.focus();

error = "invalid address";

return error;

if(!email.value || isValidEmail(email.value)){

email.focus();

error = "Invalid Email";

return error;

if(!passwd.value || passwd.value.length<8){

passwd.focus();

error = "Invalid Password";

return error;

if(!phoneno.value || phoneno.value.lenght < 10){

phoneno.focus();

error = "Invalid PhoneNo";

return error;

return error;

function isValidEmail(email){

var emailRegex = new RegExp(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g);

return emailRegex.test(email);

style.css:

*{

26
font-family: sans-serif;

box-sizing: border-box;

margin: 0;

padding: 0;

body{

height: 100vh;

display: flex;

align-items: center;

justify-content: center;

background-color: #3a5;

#error{

color: red;

font: bold;

padding: 15px;

input{

padding: 5px

h1{

color: black;

text-align: center;

text-transform: uppercase;

padding-bottom: 15px;

p{

27
color: black;

font-weight: bolder;

padding-bottom: 15px;

letter-spacing: 2px;

.container{

position: relative;

background-color: #eaffd6;

border-radius: 10px;

padding: 20px;

.But{

display: flex;

align-items: center;

justify-content: space-around;

padding-top: 10px;

select option{

font-family: sans-serif;

button{

font-size: large;

font-family: sans-serif;

text-transform: uppercase;

padding: 2px 3px;

background-color: black;

color: white;

border-radius: 5px;

28
letter-spacing: 2px;

cursor: pointer;

OUTPUT:

29
RESULT:

Thus the above program is executed successfully and verified.

30
Ex. No: 04

Date: Get data using Fetch API from an open-source endpoint and display the contents
in the form of a card.

AIM:

To write a program for to get data using fetch API from an opensource endpoint and
display the content in the form of a card.

PROCEDURE:

Step 1: Start the program

Step 2: First to create a HTML webpage on fetch.html

Step 3: Create css file and name it as style.css

Step 4: Create javascript file and name it is as script.js

Step 5: Next to validate on fetching ADT while using in JavaScript.

Step 6: And last to run on HTML page in your web browser.

Step 7: Stop the program

31
IMPLEMENTATION:

Html file : fetch.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>fetch</title>
<link rel="stylesheet" type="text/css"
href="C:\Users\WELCOME\OneDrive\Desktop\workshop\ex1\style.css">
</head>
<body>
<div class="results">
<div id="cat_result" class="result">
<p>Random Cat Placeholder</p>
</div>
<div id="dog_result" class="result">
<p>Random Dog Placeholder</p>
</div>
</div>
<div class="buttons">
<button id="cat_btn">Get Cat</button>
<button id="dog_btn">Get Dog</button>
</div>
<script src=" C:\Users\WELCOME\OneDrive\Desktop\workshop\ex1\script.js "></script>
</body>
</html>

Css file: style.css

@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');
body {
background-image: linear-gradient( 180deg, rgba(247,247,247,1) 23.8%, rgba(252,221,221,1)
92% );
font-family: 'Open Sans', sans-serif;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
height: 100vh;
margin: 0;
}
.results {
display: flex;
align-items: center;
justify-content: center;
}

32
.result {
background-color: #fff;
display: flex;
align-items: center;
justify-content: center;
margin: 10px;
height: 400px;
width: 300px;
}
.result img {
object-fit: cover;
height: 100%;
width: 100%;
}
.buttons {
display: flex;
align-items: center;
justify-content: center;
}
button {
background-color: darksalmon;
border: 0;
border-radius: 4px;
color: #fff;
font-size: 18px;
padding: 10px;
margin: 10px;
width: 300px;
}
button:active {
transform: scale(0.98);
}
button:focus {
outline: none
}

Javascript file: script.js

const cat_btn = document.getElementById('cat_btn');


const dog_btn = document.getElementById('dog_btn');
const cat_result = document.getElementById('cat_result');
const dog_result = document.getElementById('dog_result');
cat_btn.addEventListener('click', getRandomCat);
dog_btn.addEventListener('click', getRandomDog);
function getRandomCat() {
fetch('https://aws.random.cat/meow')
.then(res => res.json())
.then(data => {
cat_result.innerHTML = `<img src=${data.file} alt="cat" />`
});
}
function getRandomDog() {

33
fetch('https://random.dog/woof.json')
.then(res => res.json())
.then(data => {
if(data.url.includes('.mp4')) {
getRandomDog();
}
else {
dog_result.innerHTML = `<img src=${data.url} alt="dog" />`;
}
});
}

34
OUTPUT:

RESULT:

35
The Program has been executed successfully and also verified.

Ex. No: 05

Date: Create a web page using basic css tag. Demonstrate inline, internal and external
style sheets using advanced css

AIM:
To design a web page using basic css tag and demonstrate inline, internal and external style
sheets using advanced css.

PROCEDURE:

Step 1: Start the Program

Step 2: Create a HTML file with name index.html

Step 3: And then create a CSS with a name of style.css

Step 4: In html file we created navigation bar, search bar, header and footer using html
tags
Step 5: Using class and id we design the web page using advance css

Step 6: Stop the Program

36
IMPLEMENTATION:

index.html
<!DOCTYPE html>
<html>
<head>
<title>
Online Courses
</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<nav class="navbar background">
<ul class="nav-list">
<div class="logo">
<img src="anna-univ-logo.png" width="1px" height="50px">
</div>
<li><a href="#web">Web Technology</a></li>
<li><a href="#program">C Programming</a></li>
<li><a href="#course">Courses</a></li>
</ul>

<div class="rightNav">
<input type="text" name="search" id="search">
<button class="btn btn-sm">Search</button>
</div>
</nav>

<section class="firstsection">
<div class="box-main">
<div class="firstHalf">
<h1 class="text-big" id="web">
Web Technology
</h1>
<br>

<p class="text-small">
HTML stands for HyperText Markup Language. It is used to design
web pages using a markup language. HTML is the combination of Hypertext and Markup language. Hypertext
defines the link between the Markup language. Hypertext defines

37
the link between the web a markup language is used to define the text document within tag which defines the
structure of web pages. HTML is a markup language that is used by the browser to manipulate text, images, and
other content to display it in the requiredformat.
</p>
</div>
</div>
</section>

<section class="secondsection">
<div class="box-main">
<div class="secondHalf">
<h1 class="text-big" id="program">
C Programming
</h1>
<p class="text-small">
C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming
language to write operating system. The main features of C language include low-level access to memory, simple set
of keywords, and clean style, these features make C language suitable for system programming like operating
system or compiler development.
</p>
</div>
</div>
</section>
<section class="section">
<div class="paras">
<h1 class="sectionTag text-big">Java</h1>
<p class="sectionSubTag text-small">
Java has been one of the most popular programming language for many years.
Java is Object Oriented. However it is not considered as pure object oriented as it provides support for primitive data
types (like int, char, etc) The Java codes are first compiled into bytecode (machine independent code). Then the byte
code is run on Java Virtual Machine .
</p>
</div>
<div class="thumbnail">
<img src="img.png" alt="laptop image">
</div>
</section>
<footer class="background">
<p class="text-footer">
Copyright ©-All rights are reserved
</p>
</footer>
</body>
</html>

38
OUTPUT:

39
RESULT:

The program has been executed successfully and also verified.

Ex. No: 06
Design a Web page using Advanced HTML Forms tags, input-date, time,
Date: number, email, HTML header and footer, spell check and address area.

AIM:
To Design a Web page using Advanced HTML Forms tags, input-date, time, number,
email, HTML header and footer, spell check and address area.

PROCEDURE:

Step 1: Start the process

Step 2: Open Visual Studios and enter the program.

Step 3: Create a webpage to obtain required inputs.

Step 4: enter suitable HTML tags .

Step 5: run the web page

Step 6: stop the process.

40
PROGRAM:

<!DOCTYPE html>
<html>
<head>
<title>Advanced HTML Form</title>
<style>
/* Add your CSS styles here */
header, footer {
background-color: #f2f2f2;
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<header>
<h1>Advanced HTML Form</h1>
</header>

<form>
<label for="date">Date:</label>
<input type="date" id="date" name="date" required><br>

<label for="time">Time:</label>
<input type="time" id="time" name="time" required><br>

<label for="number">Number:</label>
<input type="number" id="number" name="number" min="1" max="10" required><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<label for="editable-area">Editable Area:</label>
<textarea id="editable-area" name="editable-area" rows="4" cols="50" contenteditable></textarea><br>
<input type="submit" value="Submit">
</form>
<footer>
<p>&copy; 2023 My Website. All rights reserved.</p>
</footer>
</body>

41
</html>

OUTPUT:

42
RESULT:

Thus the above program is executed successfully and also verified.

Ex. No: 07

Date: Develop and Demonstrate JavaScript with Popup boxes

AIM:
To develop and demonstrate JavaScript with POP-UP boxes and functions for the given
problems.

PROCEDURE:

Step 1: Start the process

Step 2: Open Visual Studios and enter the program.

Step 3: display Date function using onClick()

Step 4: Obtain a number using prompt and find the factorial of the number

Step 5: Obtain a number using prompt and get the multiplication table for the number
alert.

Step 6: Obtain two numbers using prompt and continue and obtain the sum of two
numbers using alert.

Step 7: end the process.

43
PROGRAM:

1. DISPLAY DATE:

<!DOCTYPE html>
<html>
<head>
<title>Display Date</title>
</head>
<body>
<button onclick="displayDate()">Display Date</button>
<input type="text" id="dateInput">

<script>
function displayDate() {
var currentDate = new Date();
var dateInput = document.getElementById("dateInput");
dateInput.value = currentDate.toDateString();
}
</script>
</body>
</html>

2. FACTORIAL :

<!DOCTYPE html>
<html>
<head>
<title>Factorial</title>
</head>
<body>
<button onclick="calculateFactorial()">Calculate Factorial</button>

<script>
function calculateFactorial() {

44
var number = prompt("Enter a number:");
var factorial = 1;

for (var i = 1; i <= number; i++) {


factorial *= i;
}

alert("Factorial of " + number + " is: " + factorial);


}
</script>
</body>
</html>

3.MULTIPLICATION TABLE :

<!DOCTYPE html>
<html>
<head>
<title>Multiplication Table</title>
</head>
<body>
<button onclick="generateMultiplicationTable()">Generate Multiplication Table</button>

<script>
function generateMultiplicationTable() {
var number = prompt("Enter a number:");
var table = "";

for (var i = 1; i <= 10; i++) {


var result = number * i;
table += number + " x " + i + " = " + result + "\n";
}

alert("Multiplication Table:\n\n" + table);


}
</script>
</body>
</html>

4. SUM OF TWO NUMBERS :

<!DOCTYPE html>
<html>
<head>
<title>Sum of Numbers</title>
</head>
<body>
<button onclick="calculateSum()">Calculate Sum</button>

<script>
function calculateSum() {
var number = prompt("Enter a number:");
var sum = Number(number);

45
var confirmAdd = confirm("Do you want to add another number?");

while (confirmAdd) {
var nextNumber = prompt("Enter another number:");
sum += Number(nextNumber);
confirmAdd = confirm("Do you want to add another number?");
}

alert("Sum of the numbers is: " + sum);


}
</script>
</body>
</html>

OUTPUT:

1.

2.

3.

46
4)

47
48
RESULT:

Thus, the above program code has been executed successfully.

Ex. No: 08 Build an online MCQ quiz app. The questions and options should be fetched
based on the chosen topic from a NodeJS server. The questions can be stored in a
Date: JSON file in the backend. Once the user has answered the questions, the
frontend must send the chosen options to the backend and the backend must
identify the right answers and send the score back to the front end. The frontend
must display the score in a separate neatly designed page.

AIM:
To Build an online MCQ quiz app. The questions and options should be fetched based on
the chosen topic from a NodeJS server. The questions can be stored in a JSON file in the
backend. Once the user has answered the questions, the frontend must send the chosen options to
the backend and the backend must identify the right answers and send the score back to the front
end. The frontend must display the score in a separate neatly designed page.

PROCEDURE:

Step 1: Open Visual Studio Code with the selected project directory.

Step 2: Create server.js file and initialize npm project by using “npm init” command.

Step 3: Install required packages.

Step 4: Initialize express server and listen on port 3000.

Step 5: create server.js in project directory.

Step 6: create questions.json in project directory

Step 7: create index.html in views folder

Step 8: create style.css in css folder in public folder

Step 9: create script.js in js folder in public folder

49
Step 10: run the program as npm run dev

Step 11: Enter the url http://localhost:3000/ in your browser.

REQUIRED PACKAGES:

 Express
 nodemon

IMPLEMENTATION:

Package.json:
{
"name": "mcq-quiz",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"nodemon": "^2.0.22"
}
}

Server.js
const express = require('express');
const app = express();
const port = 3000;

// Serve static files from the 'public' directory


app.use(express.static(__dirname + '/public'));

// Parse JSON requests


app.use(express.json());

const questions = require('./questions.json');

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


res.sendFile(__dirname + "/views/index.html");
});

50
app.get("/api/topics", (req, res) => {
const topics = Object.keys(questions);
res.status(200).json({topics});
});

// Endpoint to fetch questions and options for a specific topic


app.get('/api/questions/:topic', (req, res) => {
const topic = req.params.topic;
if (questions.hasOwnProperty(topic)) {
res.json(questions[topic]);
} else {
res.status(404).json({ error: 'Topic not found' });
}
});

// Endpoint to calculate the score based on user answers


app.post("/api/questions/:topic/submit", (req, res) => {
const topic = req.params.topic;
const { answers } = req.body;
const result = [];

const quests = questions[topic].questions;


let totalScore = 0;

for (let quest of quests) {


if (quest.options.indexOf(answers[quest.question]) + 1 !== quest.correctAnswer) {
result.push({ question: quest.question, correctAnswer: quest.correctAnswer, status: "wrong", score: 0});
} else {
result.push({ question: quest.question, correctAnswer: quest.correctAnswer, status: "correct", score: 10});
totalScore += 10;
}
}

return res.status(200).json({
result,
totalScore
});
})

// Start the server


app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});

Questions.json
{
"DSA" : {
"questions": [
{

51
"question": "This set of Data Structure Multiple Choice Questions & Answers (MCQs) focuses on “Binary
Trees using Array”.",
"options": ["2", "any number of children", "0 or 1 or 2", "0 or 1"],
"correctAnswer":3
},
{
"question": "What is/are the disadvantages of implementing tree using normal arrays?",
"options": ["difficulty in knowing children nodes of a node", "difficult in finding the parent of a node",
"have to know the maximum number of nodes possible before creation of trees", "difficult to implement"],
"correctAnswer":3
},
{
"question": "What must be the ideal size of array if the height of tree is ‘l’?",
"options": ["2l-1", "l-1", "l", "2l"],
"correctAnswer":1
}
]
},
"Python" : {
"questions": [
{
"question": "This set of Data Structure Multiple Choice Questions & Answers (MCQs) focuses on “Binary
Trees using Array”.",
"options": ["2", "any number of children", "0 or 1 or 2", "0 or 1"],
"correctAnswer":3
},
{
"question": "What is/are the disadvantages of implementing tree using normal arrays?",
"options": ["difficulty in knowing children nodes of a node", "difficult in finding the parent of a node",
"have to know the maximum number of nodes possible before creation of trees", "difficult to implement"],
"correctAnswer":3
},
{
"question": "What must be the ideal size of array if the height of tree is ‘l’?",
"options": ["2l-1", "l-1", "l", "2l"],
"correctAnswer":1
}
]
}
}

Views->index.html

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/styles.css">
<title>MCQ Quiz App</title>
<style>
/* Add your custom styles here */
</style>
</head>
<body>

52
<h1>MCQ Quiz App</h1>
<label for="topic">Choose a topic:</label>
<select id="topic">
<!-- Add more topic options as needed -->
</select>
<button id="start-quiz">Start Quiz</button>
<div id="quiz-container" style="display: none;">
<h2>Questions:</h2>
</div>
<div id="resultContainer">
<h2 id="result"></h2>
</div>

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

Public->css->styles.css

*{
font-family: sans-serif;
}

body {
padding-left: 3rem;
padding-right: 3rem;
background-color: whitesmoke;
}

h1 {
text-align: center;
}

.error {
color: red;
}

.success {
color: green;
}

.card {
background-color: white;
border-radius: 10px;
padding: 2rem;
margin-bottom: 10px;
}

.card-title {
margin-bottom: 10px;
}

#options {

53
margin-top: 10px;
}

#options > div {


margin-bottom: 5px;
}

#quiz-container {
margin-top: 10px;
}

.btn-primary {
border-radius: 10px;
height: 40px;
width: 100px;
background-color: dodgerblue;
border: none;
color: white;
cursor: pointer;
font-size: medium;
}

.btn-secondary {
border-radius: 10px;
height: 40px;
width: 100px;
background-color: gray;
color: white;
margin-left: 5px;
border: none;
cursor: pointer;
}

Public->js->script.js

const startQuiz = document.getElementById("start-quiz");


const topicInput = document.getElementById("topic");
const quizContainer = document.getElementById("quiz-container");
const resultElement = document.getElementById("result");

const answers = {};

let topic = "";

document.addEventListener("DOMContentLoaded", async () => {


resultElement.innerText = "";
const topics = await fetchTopics();
topic = topics[0];
displayTopics(topics);
});

topicInput.addEventListener("change", (e) => {


topic = e.target.value;

54
});

startQuiz.addEventListener("click", async () => {


const questions = await fetchQuestions(topic);
displayQuestions(questions);
});

async function fetchTopics() {


try {
const res = await fetch("http://localhost:3000/api/topics");
const { topics } = await res.json();
return topics;
} catch (err) {
console.log(err);
}
}

async function fetchQuestions(topic) {


try {
const res = await fetch(`http://localhost:3000/api/questions/${topic}`)
const { questions } = await res.json();
return questions;
} catch (err) {
console.log(err);
}
}

function displayTopics(topics) {
topics.forEach(topic => {
const option = document.createElement("option");
option.innerText = topic;
topicInput.appendChild(option);
});
}

function displayQuestions(questions) {
quizContainer.innerHTML = "";

questions.forEach(({question, options}, index) => {


const questionContainer = document.createElement("div");
questionContainer.classList.add("card");

const b = document.createElement("b");
b.innerText = `${index + 1}. ${question}`;
b.classList.add("card-title");

const optionsContainer = document.createElement("div");


optionsContainer.id = "options";

options.forEach((option, index) => {


const field = document.createElement("div");
const input = document.createElement("input");
const label = document.createElement("label");

55
input.type = "radio";
input.id = option;
input.value = option;
input.name = question;
input.addEventListener("change", handleInputChange);

label.innerText = `${index + 1}) ${option}`;


label.htmlFor = option;

field.id=question;
field.appendChild(input);
field.appendChild(label);

optionsContainer.appendChild(field);
});

questionContainer.appendChild(b);
questionContainer.appendChild(optionsContainer);
quizContainer.appendChild(questionContainer);
});

const button = document.createElement("button");


button.classList.add("btn-primary");
button.innerText = "Submit";
button.addEventListener("click", handleSubmit);

quizContainer.appendChild(button);
quizContainer.style.display = "block";
}

async function handleSubmit(e) {


try {
const res = await fetch(`http://localhost:3000/api/questions/${topic}/submit`, {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({answers}),
});

const {result, totalScore} = await res.json();

displayResult(result, totalScore);
} catch (err) {
console.log(err);
}
}

function handleInputChange(e) {
const { name, value } = e.target;
answers[name] = value;

56
console.log(answers);
}

function displayResult(result, totalScore) {


result.forEach(result => {
const field = document.getElementById(result.question).parentElement;
field.innerHTML = "";
const p = document.createElement("p");

if (result.status === "wrong") {


p.classList.add("error");
} else {
p.classList.add("success");
}

p.innerText = `Correct Answer is option ${result.correctAnswer}, Score: ${result.score}`;


field.appendChild(p);
});

const button = document.createElement("button");


button.classList.add("btn-secondary");
button.innerText = "Restart";
button.addEventListener("click", handleRestart);
quizContainer.appendChild(button);

resultElement.innerText = `Total Score ${totalScore}`;


}

async function handleRestart() {


resultElement.innerText = "";
const questions = await fetchQuestions(topic);
displayQuestions(questions);
}

57
OUTPUT:

58
RESULT:
Thus the above program is executed successfully and also verified.

Ex. No: 09

Date: Change a Content of webpage using AJAX. Perform Different Operations using
JQUERY Selectors.

AIM:

To Change a Content of webpage using AJAX. Perform Different Operations using


JQUERY Selectors.

PROCEDURE:

STEP 1: Start the Program

STEP 2: Create a html webpage with the file name as index.html

STEP 3: Create a javascript file with the file name as script.js

STEP 4: Insert url in url side as from jsonplaceholder.

STEP 5: Run the program.

59
IMPLEMENTATION:

index.html

<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
/>
<title>Blog Post</title>
<meta charset="UTF-8" />
</head>

<body>
<div id="app">
<div class="navbar navbar-dark bg-dark p-3 mb-3">
<h1 class="navbar-brand">Blog Posts</h1>
</div>
<div class="container" id="container"></div>
</div>

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

scripts.js

$(document).ready(function () {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
method: "GET",

60
success: function (posts) {
let result = ``;
posts.forEach(function (post, index) {
result += `<div class="card mb-3">
<div class="card-header">
<h1>${index + 1}. ${post.title}</h1>
</div>
<div class="card-body">
<p>${post.body}</p>
</div>
</div>`;
});

$("#container").html(result);
}
});
});
OUTPUT:

61
RESULT:
The program has been executed successfully and output has been obtained.

Ex. No: 10

Date: Create a NodeJS server that serves static HTML and CSS files to the user
without using Express

Aim:

To write a program for create a Nodejs server that server static HTML and CSS file to
the user without using express.

Procedure:

Step 1: Start the program

Step 2: Create a HTML file and name it as Index.html

Step 3: Next created HTML page to design in CSS and that age connect with
Nodejs server.

Step 4: Create a javascript file and name it is as Server.js

Step 5: Next run the program in your web browser on the local host

Step 6: Stop the program

62
IMPLEMENTATION:

index.html

<!DOCTYPE html>
<html>
<body>
<h1>This is MCA page</h1>
<h1>TIME TABLE</h1>
<table border="5" cellspacing ="0" align="center">
<!--<caption>Timetable</caption>-->
<tr>
<td align="center" height="50"
width="100"><br>
<b>Day/Period</b></br>
</td>
<td align="center" height="50"
width="100"><br>
<b>I<br>9:30-10:20</b>
</td>
<td align="center" height="50"
width="100"><br>
<b>II<br>10:20-11:10</b>
</td>
<td align="center" height="50"
width="100"><br>
<b>III<br>11:10-12:00</b>
</td>
<td align="center" height="50"
width="100"><br>
<b>12:00-12:40</b>
</td>
<td align="center" height="50"

63
width="100"><br>
<b>IV<br>12:40-01:30</b>
</td>
<td align="center" height="50"
width="100"><br>
<b>V<br>01:30-02:20</b>
</td>
<td align="center" height="50"
width="100"><br>
<b>VI<br>02:20-03:10</b>
</td>
<td align="center" height="50"
width="100"><br>
<b>VII<br>03:10-04:00</b>
</td>
</tr>
<tr>
<td align="center" height="50">
<b>MONDAY</b></td>
<td align="center" height="50">ENG</td>
<td align="center" height="50">MAT</td>
<td align="center" height="50">CHE</td>
<td rowspan="6" align="center" height="50">
<h2>L<br>U<br>N<br>C<br>H</h2>
</td>
<td colspan="3" align="center"
height="50">LAB</td>
<td align="center" height="50">PHY</td>
</tr>
<tr>
<td align="center" height="50">
<b>TUESDAY</b>
</td>
<td colspan="3" align="center"
height="50">LAB
</td>
<td align="center" height="50">ENG</td>
<td align="center" height="50">CHE</td>
<td align="center" height="50">MAT</td>
<td align="center" height="50">SPORTS</td>
</tr>
<tr>
<td align="center" height="50">
<b>WEDNESDAY</b>
</td>
<td align="center" height="50">MAT</td>
<td align="center" height="50">PHY</td>
<td align="center" height="50">ENG</td>
<td align="center" height="50">CHE</td>
<td colspan="3" align="center"
height="50">LIBRARY
</td>
</tr>

64
<tr>
<td align="center" height="50">
<b>Thursday</b>
</td>
<td align="center" height="50">Phy</td>
<td align="center" height="50">Eng</td>
<td align="center" height="50">Che</td>
<td colspan="3" align="center"
height="50">LAB
</td>
<td align="center" height="50">Mat</td>
</tr>
<tr>
<td align="center" height="50">
<b>Friday</b>
</td>
<td colspan="3" align="center"
height="50">LAB
</td>
<td align="center" height="50">Mat</td>
<td align="center" height="50">Che</td>
<td align="center" height="50">Eng</td>
<td align="center" height="50">Phy</td>
</tr>
<tr>
<td align="center" height="50">
<b>Saturday</b>
</td>
<td align="center" height="50">Eng</td>
<td align="center" height="50">Che</td>
<td align="center" height="50">Mat</td>
<td colspan="3" align="center"
height="50">SEMINAR
</td>
<td align="center" height="50">SPORTS</td>
</tr>
</table>
</body>
</html>

Server.js

var http = require('http');


const fs = require("fs");

var server = http.createServer(function (req, res) {


if (req.url == '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile("./Index.html", (err, data) => {
res.write(data);
res.end();
});

65
} else if (req.url == "/student") {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is student Page.</p></body></html>');
res.end();
} else if (req.url == "/admin") {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is admin Page.</p></body></html>');
res.end();
} else
res.end('Invalid Request!');
});

server.listen(4000);
console.log('Node.js web server at port 4000 is running..')

OUTPUT:

66
RESULT:

The Program has been executed successfully and also verified

Ex. No: 11 Create a NodeJS server using Express that stores data from a form as a JSON
file and displays it in another page. The redirect page should be prepared using
Date: Handlebars.

Aim:
To write a program to create a NodeJS server using Express that stores data from a form
as a JSON file and displays it in another page. The redirect page should be prepared
using Handlebars.

Procedure:

Step1: Start the program

Step2: First install the npm init

Step3: Next to install npm install express -save

Step4: And next to install npm install express -handlebars -save

Step5: Stop the program

67
Implementation:
Installing the following packages:
npm init
npm install express –save
npm install express-handlebars –save

index.js
const express = require('express');
const app = express();
const port = 3000;
const {engine}= require('express-handlebars');
app.set('view engine', 'hbs');
app.engine('hbs', engine({
layoutsDir: __dirname + '/views/layouts',
extname: 'hbs',
defaultLayout: 'planB',
partialsDir: __dirname + '/views/partials/'
}));
app.use(express.static('public'))
fakeApi = () => {
return [
{
name: 'Katarina',
lane: 'midlaner'
},
{
name: 'Jayce',
lane: 'toplaner'
},
{

68
name: 'Heimerdinger',
lane: 'toplaner'
},
{
name: 'Zed',
lane: 'midlaner'
},
{
name: 'Azir',
lane: 'midlaner'
}
];
}
app.get('/', (req, res) => {
res.render('main', {layout: 'index', suggestedChamps: fakeApi(), listExists: true});
});
app.listen(port, () => console.log(`App listening to port ${port}`));
create a folder by the name of “public” in which we create a style.css file

style.css
li {
font-size: 2rem;
width: 300px;
margin: 4px;
padding: 4px;
list-style: none
}
.midlaner {background-color: #ffea00}
.toplaner {background-color: #eeeeee}

create a folder containing the files needed for Handlebars to work,


create a folders “views” in which we create a file called “main.hbs” and
2 subfolders with the respective names “partials” and “layouts”.
Inside the folder partials create a file “hatedChamps.hbs” and “lovedChamps.hbs” and
Inside the folder layouts create a file “index.hbs” and “planB.hbs”.

main.hbs
{{> lovedChamps}}
{{> hatedChamps}}
<ul>
{{#if listExists}}
{{#each suggestedChamps}}
<li class={{this.lane}}>{{this.name}}</li>
{{/each}}
{{/if}}
</ul>

hatedChamps.hbs
<h2>Lists of my most hated League champions</h2>
<ul>
<li class="midlaner">Yasuo</li>
<li class="midlaner">Zoe</li>

69
<li class="toplaner">Mundo</li>
<li class="toplaner">Darius</li>
<li class="midlaner">Fizz</li>
</ul>

lovedChamps.hbs
<h2>Lists of my most loved League champions</h2>
<ul>
<li class="midlaner">Leblanc</li>
<li class="midlaner">Lux</li>
<li class="toplaner">Teemo</li>
<li class="midlaner">Kassadin</li>
<li class="toplaner">Jarvan IV</li>
</ul

index.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Best Website</title>
<meta name="HandheldFriendly" content="True" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<link rel="stylesheet" type="text/css" href="./style.css" />
</head>
<body>
{{{body}}}
</body>
</html>

planB.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Best Website</title>
<meta name="HandheldFriendly" content="True" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<link rel="stylesheet" type="text/css" href="./style.css" />
</head>
<body>
{{{body}}}
<h1>HAHAHAHAHAHAHH</h1>
</body> </html>

70
OUTPUT:

71
RESULT:

The Program has been executed successfully and also verified

Ex. No: 12 Create a NodeJS server using Express (i) To creates, reads, updates and deletes
student details and stores them in MongoDB database.(ii)The information about
Date: the user should be obtained from a HTML form.

Aim:

To write a program to create a NodeJS server using Express that creates, reads, updates
and delete students details and stores them in MongoDB database. The information should be
obtained from a HTML.

Procedure:

Step1: Start the program

Step2: Next to create npm init

Step3: Next to install express --save

Step4: And next to install npm install mongodb --save

Step5: And there last npm install -body parser --save

Step6: Stop the program.

72
Implementation:

Installing the following packages:


npm init
npm install express –save
npm install mongoose –save
npm install body-parser –save

index.js
var express = require("express");
var app = express();
var port = 3000;
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var mongoose = require("mongoose");
mongoose.Promise = global.Promise; mongoose.connect("mongodb://127.0.0.1:27017/ex5");
var studentsSchema = new mongoose.Schema({
fname: String,
lname: String,
rollno: Number
});
var User = mongoose.model("User", studentsSchema);
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});

73
app.post("/addname", (req, res) => {
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("database saved");
})
.catch(err => {
res.status(400).send("Unable to save to database");
});
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});

index.html
<!DOCTYPE html>
<html>
<head>
<title>Student Database</title>
</head>
<body>
<h1>Student Database</h1>
<form method=”post” action=”/addname”>
<label for=”fname”>First name:</label><br><br>
<input type=”text” id=”fname” name=”fname” placeholder=”name”><br><br>
<label for=”lname”>Last name:</label><br><br>
<input type=”text” id=”lname” name=”lname” placeholder=”name”><br><br>
<label for=”rollno”>Roll no:</label><br><br>
<input type=”text” id=”rollno” name=”rollno” placeholder=”rollno”><br><br>
<input type=”submit” value=”submit”>
<input type=”reset”>
</form>
</body>
</html>

74
75
76
OUTPUT:

Up

UPDATE:

77
>use ex5;
>'switched to db ex5'
>db.users.updateOne({'fname':'jayabarani'},{$set:{'lname':'palanivel'}})

Delete
>db.users.remove({‘fname’:’jayabarani’})

78
79
RESULT:
The Program has been executed successfully and also verified

Ex. No: 13

Date: Develop API with Express Framework for online Gas Booking Management
System.

AIM:

To Develop API with Express Framework for online Gas Booking Management System.

PROCEDURE:

Step 1: Open Visual Studio Code with the selected project directory.

Step 2: Create server.js file and initialize npm project by using “npm init” command.

Step 3: Install required packages.

Step 4: Initialize express server and listen on port 3000.

Step 5: create a bookingControllers.js in controllers -> bookingControllers.js

80
Step 6: Create booking.js in models->booking.js

Step 7: Download thunder client extension in visual studio code

Step 8: run the program as node server.js

Step 9: Enter the url http://localhost:3000/bookings in thunder client change the get
method to post method and click send.

Required npm Packages:


1. express
2. mongoose
3. body-parser

IMPLEMENTATION:

Package.json:

{
"name": "gas-booking",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.2",
"express": "^4.18.2",
"mongoose": "^7.3.0"
}
}

81
server.js

const express = require("express");


const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const app = express();


const port = 3000;

// Configure body-parser middleware


app.use(bodyParser.json());

// Connect to MongoDB
mongoose
.connect("mongodb://localhost/gas_booking", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to MongoDB");
})
.catch((err) => {
console.error("Error connecting to MongoDB:", err);
});

// Set up routes and middleware here

const bookingController = require("./controllers/bookingController");

// Create a new booking


app.post("/bookings", bookingController.createBooking);

// Start the server


app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});

controllers -> bookingController.js

const Booking = require("../models/booking");

// Controller for creating a new booking


exports.createBooking = (req, res) => {
const { customerName, address, phoneNumber, gasType } = req.body;

const newBooking = new Booking({


customerName,
address,
phoneNumber,
gasType,
});

82
newBooking
.save()
.then((booking) => {
res.json(booking);
})
.catch((err) => {
res.status(500).json({ error: "Error creating booking" });
});
};

models -> booking.js

const mongoose = require("mongoose");

const bookingSchema = new mongoose.Schema({


customerName: {
type: String,
required: true,
},
address: {
type: String,
required: true,
},
phoneNumber: {
type: String,
required: true,
},
gasType: {
type: String,
required: true,
},
createdAt: {
type: Date,
default: Date.now,
},
});

const Booking = mongoose.model("Booking", bookingSchema);

module.exports = Booking;

83
OUTPUT:

84
RESULT:

Thus the above program is executed successfully and also verified.

Ex. No: 14 Build a blog website where you can add blog posts through a simple admin panel
and the users can view the blog posts. The contents of the blog posts can be

85
Date: stored in either MongoDB. The home page should contain the titles of the blog
post and the full post can be viewed by clicking the title. Frontend can be built
either using React or through template engines served by the NodeJS server.

AIM:

To Build a blog website where you can add blog posts through a simple admin panel and
the users can view the blog posts. The contents of the blog posts can be stored in either
MongoDB. The home page should contain the titles of the blog post and the full post can be
viewed by clicking the title. Frontend can be built either using React or through template engines
served by the NodeJS server.

PROCEDURE:

Step 1: Open the visual studio code with the selected project directory.

Step 2: Create a server.js and initialize the npm project by using “ npm init” command

Step 3: Install required packages.

Step 4: Initialize express server and listen on port 3000.

Step 5: Create index.ejs and post.ejs files in views folder.

Step 6: Create styles.css file in css folder in public folder.

Step 7: Run the program using npm start in terminal.

REQUIRED PACKAGES:

1. express
2. mongoose
3. ejs

86
IMPLEMENTATION:

Package.json:
{
"name": "blog3",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.2",
"mongoose": "^7.3.0"
}
}

server.js

const express = require('express');


const mongoose = require('mongoose');

const app = express();


const port = 3000;

app.set("view engine", "ejs");


app.use(express.static(__dirname + "/public"));

// Connect to MongoDB
mongoose.connect('mongodb://127.0.0.1:27017/blog');
const db = mongoose.connection;

db.on('error', console.error.bind(console, 'MongoDB connection error:'));


db.once('open', () => {
console.log('Connected to MongoDB');
});

// Set up routes and middleware here

// Define the Mongoose model


const BlogPost = mongoose.model('BlogPost', new mongoose.Schema({
title: String,
content: String,
}));

// Define the routes


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

87
const posts = await BlogPost.find({ });
res.render("index", { posts });
} catch (err) {
console.log(err);
}

});

app.get('/post/:id', async (req, res) => {


const postId = req.params.id;
try {
const post = await BlogPost.findById({_id: postId});
res.render("post", { post });
} catch (err) {
console.log(err);
}
});

// Start the server


app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});

views->index.ejs

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/css/styles.css">
<title>Blog</title>
</head>
<body>
<div class="container">
<h1>Welcome to the Blog</h1>
<% posts.forEach((post) => { %>
<div class="card">
<h2 class="card-header"><%= post.title %></h2>
<div class="card-body"><%= post.content.slice(0, 100) + "...." %><a href="/post/<%= post._id %>">read
more</a></div>
</div>
<% }); %>
</div>
</body>
</html>

views->post.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= post.title %></title>
</head>
<body>

88
<h1><%= post.title %></h1>
<p><%= post.content %></p>
</body>
</html>

public->css->styles.css
*{
font-family: sans-serif;
box-sizing: border-box;
}

body {
background-color: whitesmoke;
}

h1 {
text-align: center;
}

.container {
padding: 20px;
}

.card {
background-color: white;
border-radius: 5px;
padding: 1rem;
}

.card-header {
margin: 0;
border-bottom: 1px solid gray;
}

.card-body {
padding-top: 10px;
}

89
OUTPUT:

RESULT:

90
Thus the above program is executed successfully and also verified.

Ex. No: 15

Date: REST API with Node.js and Express to Manage Books

Aim:

To Build a REST API with Node.js and Express to manage books

Procedure:

Step 1: Open Visual Studio Code with the selected project directory.

Step 2: Create server.js file and initialize npm project by using “npm init” command.

Step 3: Install required packages.

Step 4: Initialize express server and listen on port 3000.

Step 5: Define Book schema using mongoose.

Step 6: Set up routes and route handlers for following methods GET, POST, PUT,
DELETE.

Step 7: Start the development server by running “npm run dev” command.

Step 8: Use REST client program like postman to verify the output.

Required npm Packages:


4. express
5. mongoose
6. nodemon

91
IMPLEMENTATION:

Package.json

{
"name": "books-api",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js",
"dev": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"mongoose": "^7.2.2"
},
"devDependencies": {
"nodemon": "^2.0.22"
}
}

Server.js

const express = require("express");


const mongoose = require("mongoose");

const app = express();

app.use(express.json());

const bookSchema = new mongoose.Schema({


title: {
type: String,
trim: true
},
description: {
type: String
},
author: {
type: String,
required: true
},

92
publication: {
type: String,
required: true
},
price: {
type: String,
required: true
},
publishedOn: {
type: Date,
default: Date.now
}
});

const Book = mongoose.model("book", bookSchema);

async function connectDB() {


const { connection } = await mongoose.connect("mongodb://127.0.0.1:27017/books");
console.log(`Successfully connected to Database ${connection.host}`);
}

app.get("/books", async (req, res) => {


try {
const books = await Book.find({});

res.status(200).json({
books
});
} catch (err) {
res.status(500).json({
message: "Internal Server error"
});
}
});
app.post("/book", async (req, res) => {
const body = req.body;
const book = new Book(body);
try {
await book.save();
res.status(201).json({
message: `Successfully saved book with the title ${book.title}`
});
} catch (err) {
console.log(err);
res.status(500).json({
message: "Internal Server error"
});
}
});
app
.route("/book/:id")
.put(async (req, res) => {
const { id } = req.params;

93
try {
const book = await Book.findByIdAndUpdate(id, req.body);
return res.status(200).json({
message: "Successfully updated the book!"
});
} catch (err) {
res.status(500).json({
message: "Internal Server error"
});
}
})
.delete(async (req, res) => {
const { id } = req.params;
try {
const bookQuery = await Book.findByIdAndDelete(id);
return res.status(200).json({
message: `Successfully deleted book with title ${bookQuery.title}`
});
} catch (err) {
res.status(500).json({
message: "Internal Server error"
});
}
});

app.listen(3000, () => {
console.log("Server started on port 3000");
connectDB();
});

94
OUTPUT:

95
96
RESULT:

The program has been executed successfully and output has been obtained.

Ex. No: 16 Create a simple Sign up and Login mechanism and authenticate the user using
cookies. The user information can be stored in either MongoDB or MySQL and
Date: the server should be built using NodeJS and Express Framework

AIM:

To write a program to Create a simple Sign up and Login mechanism and authenticate the
user using cookies. The user information can be stored in either MongoDB or MySQL and the
server should be built using NodeJS and Express Framework

PROCEDURE:

Step1: Start the program

Step2: create the folder and install required packages

Step3: create index, registration and login.html files

97
Step4: create javaScript file named app.js

Step5: run the program in localhost

Step6: Stop the program

IMPLEMENTATION:

JAVASCRIPT FILE: app.js

const express = require('express');


const http = require('http');
const bcrypt = require('bcrypt');
const path = require("path");
const bodyParser = require('body-parser');
const users = require('./data').userDB;
const app = express();
const server = http.createServer(app);
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname,'./public')));
app.get('/',(req,res) => {
res.sendFile(path.join(__dirname,'./public/index.html'));
});
app.post('/register', async (req, res) => {

98
try{
let foundUser = users.find((data) => req.body.email === data.email);
if (!foundUser) {
let hashPassword = await bcrypt.hash(req.body.password, 10);
let newUser = {
id: Date.now(),
username: req.body.username,
email: req.body.email,
password: hashPassword,
};
users.push(newUser);
console.log('User list', users);
res.send("<div align ='center'><h2>Registration successful</h2></div><br><br><div
align='center'><a href='./login.html'>login</a></div><br><br><div align='center'><a
href='./registration.html'>Register another user</a></div>");
} else {
res.send("<div align ='center'><h2>Email already used</h2></div><br><br><div
align='center'><a href='./registration.html'>Register again</a></div>");
}
} catch{
res.send("Internal server error");
}
});
app.post('/login', async (req, res) => {
try{
let foundUser = users.find((data) => req.body.email === data.email);
if (foundUser) {
let submittedPass = req.body.password;
let storedPass = foundUser.password;
const passwordMatch = await bcrypt.compare(submittedPass, storedPass);
if (passwordMatch) {
let usrname = foundUser.username;
res.send(`<div align ='center'><h2>login successful</h2></div><br><br><br><div align
='center'><h3>Hello ${usrname}</h3></div><br><br><div align='center'><a
href='./login.html'>logout</a></div>`);
} else {
res.send("<div align ='center'><h2>Invalid email or password</h2></div><br><br><div align
='center'><a href='./login.html'>login again</a></div>");
}
}
else {
let fakePass = `$2b$$10$ifgfgfgfgfgfgfggfgfgfggggfgfgfga`;
await bcrypt.compare(req.body.password, fakePass);
res.send("<div align ='center'><h2>Invalid email or password</h2></div><br><br><div
align='center'><a href='./login.html'>login again<a><div>");
}
} catch{
res.send("Internal server error");
}
});
server.listen(3000, function(){
console.log("server is listening on port: 3000");
});

99
HTML FILE: login.html

<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title> My Form </title>
<style>
#mylink{
font-size: 25px;
}
</style>
</head>
<body align='center'>
<header>
<h1>Login</h1>
</header>
<form action="/login" method="POST">
<fieldset>
<label>Email ID</label>
<input type ="email" id = 'email' name="email" placeholder="[email protected]" required>
<br><br>
<label>Password</label>
<input type="password" id = "password" name="password" required>
<br><br>
<button type ="reset">Reset</button>
<button type ="submit">Submit</button>
</fieldset>
</form>
<br><br>
<a id="mylink" href="./registration.html">register</a>
</body>
</html>

registration.html

<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title> My Form </title>
<style>
#mylink{
font-size: 25px;
}
</style>
</head>
<body align='center'>
<header>
<h1>Register</h1>
</header>
<form action="/register" method="POST">

100
<fieldset>
<label>Username</label>
<input type ="text" id = 'username' name="username" placeholder="maverick" required>
<br><br>
<label>Email ID</label>
<input type ="email" id = 'email' name="email" placeholder="[email protected]" required>
<br><br>
<label>Password</label>
<input type="password" id = "password" name="password" required>
<br><br>
<button type ="reset">Reset</button>
<button type ="submit">Submit</button>
</fieldset>
</form>
<br><br>
<a id="mylink" href="./login.html">login</a>
</body>
</html>

OUTPUT:

101
102
RESULT:
Thus the above program is executed successfully and also verified.

Ex. No: 17 Build a simple calculator app with React. The user should be able to add
numbers and Operations to the app by clicking on buttons, just like you would
Date: do in a mobile phone. The moment the operation and the two operations are
defined, the answer should be displayed.

AIM:

To Build a simple calculator app with React. The user should be able to add numbers and
Operations to the app by clicking on buttons, just like you would do in a mobile phone. The
moment the operation and the two operations are defined, the answer should be displayed.

PROCEDURE:

103
Step 1: Open Visual Studio Code with the selected project directory.

Step 2: Create server.js file and initialize npm project by using “npm init” command.

Step 3: Install required packages.

Step 4: Initialize express server and listen on port 3000.

Step 5: create calculator using react

Step 6: run the program in the terminal using npm start

Step 7: Open browser and type the url http://localhost:3000

REQUIRED PACKAGES:

1. Parcel
2. React
3. React-dom

IMPLEMENTATION:

package.json:

{
"name": "calculator",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "parcel public/index.html"

104
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"parcel": "^2.9.2",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"process": "^0.11.10"
}
}

public->index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.15.4/css/all.css"

integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm"
crossorigin="anonymous"
/>
<title>Calculator</title>
</head>
<body>
<div id="root"></div>
<script src="../src/index.js" type="module"></script>
</body>
</html>

src->App.jsx

import { useState } from "react";


import Display from "./Components/Display";
import { renderButton } from "./utils/renderButton";
import { compute, isNumber, isOperator } from "./utils";
import { BUTTONS } from "./Constants";

const App = () => {


const [currentOperand, setCurrentOperand] = useState("0");
const [previousOperand, setPreviousOperand] = useState("");
const [operator, setOperator] = useState("");

const handleClick = ({ value, text }) => {


if (value === "delete") {

105
setCurrentOperand(prev => (prev.length <= 1 ? "0" : prev.slice(0, prev.length - 1)));
}

if (value === "CE") {


setCurrentOperand("0");
}

if (value === "C") {


setCurrentOperand("0");
setOperator("");
setPreviousOperand("");
}

if (isNumber(value)) {
setCurrentOperand(prev => (prev === "0" ? text : prev + text));
}

if (isOperator(value)) {
if (value !== "^2" && value !== "^3") {
setOperator(text);
setPreviousOperand(`${currentOperand} ${text}`);
setCurrentOperand("0");
}

if (previousOperand !== "") {


const result = compute(previousOperand, currentOperand, operator);
if (value === "=") {
setPreviousOperand("");
return setCurrentOperand(result);
}
setPreviousOperand(`${result} ${text}`);
}

if (value === "^2") {


setPreviousOperand("");
setCurrentOperand(prev => {
console.log(prev);
if (!prev) return "";
const num = parseFloat(prev);
console.log(num);
return Math.pow(num, 2);
});
setPreviousOperand(`${currentOperand}^2`);
}

if (value === "^3") {


setPreviousOperand("");
setCurrentOperand(prev => {
if (!prev) return "";
const num = parseFloat(prev);
return Math.pow(num, 3);
});
setPreviousOperand(`${currentOperand}^3`);

106
}

if (value === "1/x") {


setPreviousOperand("");
setCurrentOperand(prev => {
if (!prev) return "";
const num = parseFloat(prev);
console.log(num);
return 1 / num;
});
setPreviousOperand(`1/${currentOperand}`);
}
}

if (value === ".") {


if (currentOperand.includes(".")) return;
setCurrentOperand(prev => prev + text);
}
};

return (
<div className="calculator">
<Display sub={previousOperand} main={currentOperand} />
<div className="btn-container">
{BUTTONS.map(button => renderButton(button, handleClick))}
</div>
</div>
);
};

export default App;

src->index.css:

@import url("https://fonts.googleapis.com/css2?family=Poppins&display=swap");

:root {
--btn-height: 60px;
--btn-width: 80px;
--default-color: gray;
--btn-default-color: #f9f9f9;
--btn-default-hover: #eeeded;
--btn-primary-color: #0067c0;
--btn-primary-hover: rgb(61, 125, 243);
--btn-white-color: #ffffff;
--btn-white-hover: rgb(255, 247, 253);
--calculator-background-color: #f3f3f3;
}

*{
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}

107
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background-color: rgb(121, 118, 118);
overflow: hidden;
}

.calculator {
background-color: var(--calculator-background-color);
padding: 8px;
border-radius: 5px;
}

.btn {
border: none;
height: var(--btn-height);
width: var(--btn-width);
padding: 10px;
font-size: 18px;
border-radius: 5px;
cursor: pointer;
transition: 0.2s;
}

.btn-default {
background-color: var(--btn-default-color);
}

.btn-default:hover {
background-color: var(--btn-default-hover);
}

.btn-primary {
background-color: var(--btn-primary-color);
color: white;
transition: 0.2s;
}

.btn-primary:hover {
background-color: var(--btn-primary-hover);
}

.btn-white {
background-color: white;
transition: 0.2s;
}

.btn-white:hover {
background-color: var(--btn-white-hover);
}

108
.btn-container {
display: grid;
align-items: center;
grid-template-columns: repeat(4, var(--btn-width));
gap: 4px;
}

.rotate-45 {
transform: rotate(45deg);
}

.operator {
font-size: 24px;
}

.display {
min-height: 100px;
padding: 10px;
text-align: right;
}

.sub-display {
padding: 5px;
min-height: 35px;
font-size: 16px;
color: var(--default-color);
}

.main-display {
font-size: 45px;
padding: 5px;
min-height: 80px;
}

src->index.js

import React from "react";


import { createRoot } from "react-dom/client";
import App from "./App";
import "./index.css";

const root = createRoot(document.getElementById("root"));

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

src->script.js

class Calculator {

109
constructor(prevOperandTextElement, currentOperandTextElement) {
this.prevOperandTextElement = prevOperandTextElement;
this.currentOperandTextElement = currentOperandTextElement;
this.clear();
}

clear() {
this.previousOperand = "";
this.currentOperand = "0";
this.operation = undefined;
}

chooseOperation(operation) {
if (this.currentOperand === "0") return;

if (this.previousOperand !== "") {


this.compute();
}

if (operation === "=") return;

this.operation = operation;
this.previousOperand = this.currentOperand;
this.currentOperand = "0";
}

clearCurrentOperand() {
this.currentOperand = "0";
}

delete() {
if (this.currentOperand.length === 1) {
this.currentOperand = "0";
} else {
this.currentOperand = this.currentOperand.slice(0, -1);
}
}

compute() {
let result = 0;
let previousOperand = parseFloat(this.previousOperand);
let currentOperand = parseFloat(this.currentOperand);

switch (this.operation) {
case "+":
result = previousOperand + currentOperand;
break;
case "-":
result = previousOperand - currentOperand;
break;
case "*":
result = previousOperand * currentOperand;
break;

110
case "/":
result = previousOperand / currentOperand;
break;
case "^2":
result = Math.pow(currentOperand, 2);
break;
case "^3":
result = Math.pow(currentOperand, 3);
break;
default:
result = 0;
}

this.currentOperand = result;
this.operation = undefined;
this.previousOperand = "";
}

apppendNumber(number) {
if (number === "." && this.currentOperand.includes(".")) return;
if (this.currentOperand.length === 8) return;

if (this.currentOperand === "0") {


if (number === ".") {
this.currentOperand = this.currentOperand + number.toString();
} else {
this.currentOperand = number.toString();
}
} else {
this.currentOperand = this.currentOperand.toString() + number.toString();
}
}

getOperationSymobol() {
const operation = this.operation;

if (operation === undefined) {


return "";
}

if (operation === "/") {


return "÷";
}

if (operation === "*") {


return "×";
}

return operation;
}

updateDisplay() {
this.currentOperandTextElement.innerText = this.currentOperand;

111
this.prevOperandTextElement.innerText = `${this.previousOperand} ${this.getOperationSymobol()}`;
}
}

const numberButtons = document.querySelectorAll(".number");


const operatorButtons = document.querySelectorAll(".operator");
const clearAllButton = document.querySelector("#clear-all");
const clearCurrentOperandButton = document.querySelector("#clear-current-operand");
const deleteButton = document.querySelector("#delete");

const subDisplay = document.querySelector(".sub-display");


const mainDispaly = document.querySelector(".main-display");

const calculator = new Calculator(subDisplay, mainDispaly);


calculator.updateDisplay();

numberButtons.forEach(numberButton => {
numberButton.addEventListener("click", e => {
const number = e.target.innerText;
calculator.apppendNumber(number);
calculator.updateDisplay();
});
});

operatorButtons.forEach(operatorButton => {
operatorButton.addEventListener("click", e => {
const operator = e.target.value;
calculator.chooseOperation(operator);
calculator.updateDisplay();
});
});

clearAllButton.addEventListener("click", () => {
calculator.clear();
calculator.updateDisplay();
});

clearCurrentOperandButton.addEventListener("click", () => {
calculator.clearCurrentOperand();
calculator.updateDisplay();
});

deleteButton.addEventListener("click", () => {
calculator.delete();
calculator.updateDisplay();
});

src->components->Button.jsx:

import React from "react";

112
const Button = ({ value, color = "default", children, onClick }) => {
return (
<button
className={`btn btn-${color}`}
onClick={e => onClick({ value: e.target.value, text: e.target.innerText })}
value={value ? value : ""}
>
{children}
</button>
);
};

export default Button;

src->Components->Display.jsx

import React from "react";

const Display = ({ sub, main }) => {


return (
<div className="display">
<div className="sub-display">{sub}</div>
<div className="main-display">{main}</div>
</div>
);
};

export default Display;

src->Constants->index.js:

export const BUTTONS = [


"%",
"CE",
"C",
"delete",

"1/x",
"^2",
"^3",
"/",

"7",
"8",
"9",
"*",

"4",
"5",
"6",
"-",

113
"1",
"2",
"3",
"+",

"+/-",
"0",
".",
"="
];

src->utils->index.js:

export const isNumber = s => {


if (s.charCodeAt(0) >= 48 && s.charCodeAt(0) <= 57) return true;
return false;
};

export const isOperator = s => {


const operators = ["1/x", "/", "^2", "^3", "+", "=", "-", "*", "-"];
return operators.includes(s);
};

export const compute = (prev, curr, operator) => {


switch (operator) {
case "+":
return parseFloat(prev) + parseFloat(curr);
case "-":
return parseFloat(prev) - parseFloat(curr);
case "×":
return parseFloat(prev) * parseFloat(curr);
case "÷":
return parseFloat(prev) / parseFloat(curr);
}
};

src->utils->renderButton.js:

import Button from "../Components/Button";

export const renderButton = (button, handleClick) => {


if (button.startsWith("^"))
return (
<Button key={button} value={button} onClick={handleClick}>
𝑥<sup>{button[1]}</sup>
</Button>
);
if (button === "/")
return (
<Button key={button} onClick={handleClick} value={button}>
÷

114
</Button>
);
if (button === "*")
return (
<Button key={button} onClick={handleClick} value={button}>
×
</Button>
);
if (button === "delete")
return (
<Button key={button} onClick={handleClick} value={button}>
<i className="fas fa-backspace"></i>
</Button>
);
if (button.length <= 1 && button.charCodeAt(0) >= 48 && button.charCodeAt(0) <= 57) {
return (
<Button key={button} onClick={handleClick} color="white" value={button}>
{button}
</Button>
);
}

if (button === "=")


return (
<Button key={button} onClick={handleClick} color="primary" value={button}>
{button}
</Button>
);
return (
<Button key={button} onClick={handleClick} value={button}>
{button}
</Button>
);
};

OUTPUT:

115
RESULT:
Thus the above program is executed successfully and also verified.

116
Ex. No: 18 Create a NodeJS server that creates, reads, updates and deletes event
details and stores them in a MySQL database. The information about the user
Date: should be obtained from a HTML form

AIM:
To write a program to create a NodeJS server that creates, reads, updates and deletes
event details and store them in a MySQL database. The information about the user should be
obtained from a HTML form.

PROCEDURE:

Step1: Start the program

Step2: And npm install MySQL --save to install it

Step3: Next to npm install express --save to install it on express server

Step4: And the body parser and nodemon install to the following commands
npm install body parser –save
npm install nodemon –save

Step5: Stop the program

117
IMPLEMENTATION:

Installing the following packages:


npm init
npm install mysql –save
npm install express –save
npm install body-parser –save
npm install nodemon –save

vscode => index.js

const express = require('express');


const bodyparser = require('body-parser');
const mysql = require('mysql');
const app = express();
app.use(bodyparser.json());

var mysqlConnection = mysql.createConnection({


host: "localhost",
user: "root",
password: "00000",
database: 'db_college',
multipleStatements: true
});

mysqlConnection.connect(function(err) {
if (err) throw err;
console.log("Database Connected!");
});
app.listen(8080, function(){
console.log(`Listening on port 8080..`)
});
app.get('/students' , (req, res) => {
mysqlConnection.query('SELECT * FROM students', (err, rows, fields) => {
if (!err)
res.send(rows);
else
console.log(err);
});
} );

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


mysqlConnection.query('SELECT * FROM students WHERE student_id = ?',[req.params.id], (err, rows,
fields) => {
if (!err)
res.send(rows);
else
console.log(err);
})
});

118
//Router to INSERT/POST a Student's detail

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


let student = req.body;
mysqlConnection.query('INSERT INTO

`db_college`.`students`(`student_name`,`student_email`,`age`) VALUES (?,?,?);',

[student.student_name, student.student_email, student.age], (err, rows, fields) => {


if (!err)
res.send('Student Details Inserted Successfully');
else
console.log(err);
})
});

//Router to UPDATE/POST a Student's detail


app.put('/students/:id', (req, res) => {
let student = req.body;
let student_id = req.params.id;
mysqlConnection.query('UPDATE `students` SET `student_name`=?,`student_email`=?,`age`=? where
`student_id`=?', [student.student_name,student.student_email, student.age, student_id], function (err, rows,
fields) {
if (!err)
res.send('Student Details Updated Successfully');
else
console.log(err);
})
});

//Router to DELETE a Student's detail

app.delete('/students/:id', (req, res) => {

mysqlConnection.query('DELETE FROM students WHERE student_id = ?', [req.params.id], (err, rows,


fields) => {
if (!err)
res.send('Student Record deleted successfully.');

else
console.log(err);
})
});

119
OUTPUT:

MYSQL Workbench

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '00000'; flush


privileges

120
Create database db_college;

CREATE TABLE `db_college`.`students` (


`student_id` INT NOT NULL AUTO_INCREMENT ,
`student_name` VARCHAR(100) NOT NULL ,
`student_email` VARCHAR(100) NOT NULL ,
`age` INT NOT NULL,
PRIMARY KEY (`student_id`)

121
);

INSERT INTO `db_college`.`students` (`student_name`,`student_email`,`age`) VALUES


('ganga','[email protected]',22);

use db_college;
select * from students;

122
Open up a browser and navigate to the url: http://localhost:8080/students

Postman

123
GET students

POST – Create

POST – Update

124
DELETE

125
RESULT:

The Program has been executed successfully and also verified.


Ex. No: 19

Date: Develop and demonstrate the connection between MongoDB and


NodeJS.

AIM:

To Develop and demonstrate the connection between MongoDB and NodeJS.

PROCEDURE:

Step 1: Open visual studio code with the selected project directory.

Step 2: Create index.html file for webpage

Step 3: Create app.js file and initialize npm project by using “npm init” command.

Step 4: Install required packages.

Step 5: Initialize express server and listen on port 3000.

Step 6: run the program as npm start

126
Step 7: Enter the url http://localhost:3000/ in browser.

IMPLEMENTATION:

package.json

{
"name": "mongo2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"mongodb": "^5.6.0"
}
}

index.html

<!DOCTYPE html>
<html>

127
<head>
<title>Add User</title>
</head>
<body>
<h1>Add User</h1>
<form action="/users" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required>

<label for="age">Age:</label>
<input type="number" id="age" name="age" required>

<button type="submit">Submit</button>
</form>
</body>
</html>
app.js

const express = require('express');


const { MongoClient } = require('mongodb');
const assert = require('assert');

const app = express();


const port = 3000;

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'mydatabase';

// Middleware to parse request body


app.use(express.urlencoded({ extended: true }));

// Serve the HTML form


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

// Handle user insertion


app.post('/users', (req, res) => {
const user = {
name: req.body.name,
email: req.body.email,
age: parseInt(req.body.age),
};

// Create a new MongoClient


const client = new MongoClient(url, { useUnifiedTopology: true });

128
// Use connect method to connect to the server
client.connect((err) => {
assert.strictEqual(null, err);
console.log('Connected successfully to server');

const db = client.db(dbName);

// Insert the user into the "users" collection


db.collection('users').insertOne(user, (err, result) => {
assert.strictEqual(err, null);
console.log('User inserted:', user);
res.send('User inserted successfully');
});

client.close();
});
});

// Start the server


app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});

OUTPUT:

129
RESULT:
Thus the above program is executed successfully and also verified.

Ex. No: 20 Create a Todo application using ReactJS. Store the data to a JSON file using a
simple NodeJS server and retrieve the information from the same during page
Date: reloads

Aim:

To write a program to create a Todo application using ReactJS store the data to a JSON
file using a simple NodeJS server and retrieve the information from the same during
page reloads.

Procedure:

Step1: Start the program

Step2: Next to install ReactJS app

Step3: To move a program to store package on React src files

Step4: Next to connect the NodeJS server

130
Step5: Stop the program

IMPLEMENTATION:

npx create-react-app todo


npm install react-icons –s
npm i [email protected]
install ES7+ React/Redux/React-Native snippets in vs code
vs code => src =>App.js

//import logo from './logo.svg';


import './App.css';
import Todo from './components/todo';

function App() {
return (
<div className='container border border-primary rounded mt-5' >
<Todo/>
</div>
);
}
export default App;

index.js

131
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.css'

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

reportWebVitals();

App.css

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

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


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

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

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

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

132
to {
transform: rotate(360deg);
}
}

.container {
background-color:lightseagreen;
}

In src Create New subfolder components


Src => components => todo.js

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

export default function Todo() {


const [task, setTask] = useState("");
const [tasks, setTasks] = useState([]);
useEffect(()=>{
if(localStorage.getItem("localTasks")){
const storedList = JSON.parse(localStorage.getItem("localTasks"));
setTasks(storedList);
}
},[])

const addTask = (e) => {


if (task) {
const newTask = { id: new Date().getTime().toString(), title: task };
setTasks([...tasks, newTask]);
localStorage.setItem("localTasks", JSON.stringify([...tasks, newTask]));
setTask("");
}
};

const handleDelete = (task)=>{


const deleted = tasks.filter((t)=>t.id !== task.id);
setTasks(deleted);
localStorage.setItem("localTasks", JSON.stringify(deleted))
}

const handleClear=()=>{
setTasks([]);
localStorage.removeItem("localTasks");
}
return (
<div className="container row">
<h1 className="mt-3 text-white">To-Do App</h1>
<div className="col-8">
<input
name="task"
type="text"
value={task}
placeholder="Write your task..."

133
className="form-control"
onChange={(e) => setTask(e.target.value)}
/>
</div>
<div className="col-4">
<button
className="btn btn-primary form-control material-icons"
onClick={addTask}
>
add
</button>
</div> <div className="badge">b
You have
{!tasks.length
? " no tasks"
: tasks.length === 1
? " 1 task"
: tasks.length > 1
? ` ${tasks.length} tasks`
: null}
</div>
{tasks.map((task) => (
<React.Fragment key={task.id}>
<div className="col-11">
<span className = "form-control bg-white btn mt-2"
style={{textAlign: "left", fontWeight: "bold"}}>
{task.title}
</span>
</div>

<div className="col-1">
<button
className =" mt-2 btn btn-warning material-icons"
onClick ={()=> handleDelete(task)}
>delete</button>
</div>
</React.Fragment>
))}
{!tasks.length ? null:(
<div>
<button className= "btn btn-secondary mt-4 mb-4" onClick={()=>handleClear()}>
Clear
</button>
</div>
)}
</div>
);
}

134
OUTPUT:

135
RESULT:

The Program has been executed successfully and also verified.

Ex. No: 21

Date: Create a counter using ReactJS

AIM:

To write a program to create a counter using ReactJs.

PROCEDURE:

Step1: Start the program

Step2: First to install on create on us code command on npm create -


react --app counter
a
Step3: After creating you project folder move to it using the following command:

136
cd counter

Step4: Next to start the server on command $ npm start

Step5: Stop the program.

IMPLEMENTATION:

Create a React application using the following command:


npx create-react-app counter
After creating your project folder ( i.e. counter), move to it using the following command:
cd counter

vscode => App.js:

import React, { useState } from "react";


import "./App.css";
const App = () => {
const [counter, setCounter] = useState(0)
const handleClick1 = () => {
setCounter(counter + 1)
}
const handleClick2 = () => {

137
setCounter(counter - 1)
}
return (
<div style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
fontSize: '300%',
position: 'absolute',
width: '100%',
height: '100%',
top: '-15%',
}}>

Counter App

<div style={{
fontSize: '120%',
position: 'relative',
top: '10vh',
}}>
{counter}
</div>
<div className="buttons">
<button style={{
fontSize: '60%',
position: 'relative',
top: '20vh',
marginRight: '5px',
backgroundColor: 'green',
borderRadius: '8%',
color: 'white',
}}
onClick={handleClick1}>Increment</button>
<button style={{
fontSize: '60%',
position: 'relative',
top: '20vh',
marginLeft: '5px',
backgroundColor: 'red',
borderRadius: '8%',
color: 'white',
}}
onClick={handleClick2}>Decrement</button>
</div>
</div>
)
}
export default App

Start the development server using the following command:


npm start

138
OUTPUT:

139
RESULT:
Thus the above program is executed successfully and also verified.

140
Ex. No: 22

Date: Create and deploy a virtual machine using a virtual box that can be accessed
from the host computer using SSH

Aim:

To write a program to Create and deploy a virtual machine using a virtual box that can
be accessed from the host computer using SSH.

Procedure:

Step1: Start the program

Step2: install the oracle virtual machine

Step3: open the virtual machine and install ubuntu OS into VM

Step4: Then open terminal the using port and call SSH

Step5: Stop the program

COMMANDS:

 sudo apt-get update


 sudo apt-get install openssh-client openssh-server
 sudo service ssh start
 ssh [email protected] -p 22

141
OUTPUT:

142
143
RESULT:
Thus the above program is executed successfully and also verified.

144
Ex. No: 23

Date: Create a docker container that will deploy a NodeJS ping server using the
NodeJS image

Aim:

To write a program to Create a docker container that will deploy a NodeJS ping server
using the NodeJS image.

Procedure:

Step 1: Open VS Code with the selected project directory.

Step 2: Initialize the project using “npm init” command.

Step 3: Install required packages.

Step 4: Create “Dockerfile” in project directory.

Step 5: Write the image building logic inside “Dockerfile”.

Step 6: Initialize the express server and listen on port 3000

Step 7: Create routes and route handler for HTTP method GET and POST

Step 8: Send html file as response for root route (i.e) “/”, Which has a form that will
make a POST request to the “/” route.

Step 9: Build image using “docker build -t ping-server:latest” command

Step 10: After successful build create a container using that image.

Step 11: To create a container use “docker run -p 3000:300 ping-server:latest”


command.

Step 12: Now the development server will started and the website can be viewed at
http://localhost:3000/.

145
Required Packages and Tools:
1) Docker Desktop
2) express (npm install express)

Source Code:

File: package.json
{
"name": "ping-server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"ping": "^0.4.4"
}
}

File: Dockerfile
FROM node:alpine
WORKDIR /app
COPY ./ ./
RUN npm install
CMD ["npm", "start"]

File: Server.js
const express = require("express");
const path = require("path");

const app = express();

const port = 3000;

app.use(express.urlencoded({ extended: false }));

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


try {
renderHTML(res, "index");
} catch (err) {
console.log(err);
}
});

146
app.post("/", async (req, res) => {
const { name, age } = req.body;

res.send(`
<div>
<h1>Thank you for submitting the details</h1>
<strong>Name: </strong><span>${name}</span>
<br />
<strong>Age: </strong><span>${age}</span>
</div>
`);
});

app.listen(port, () => {
console.log(`Server started on port ${port}`);
});

function renderHTML(res, name) {


res.sendFile(path.join(__dirname, "views", `${name}.html`));
}

File:views/index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Running Nodejs from Docker Image</title>
</head>
<body>
<form action="/" method="POST">
<h4>Please enter the details</h4>
<div>
<label for="name-input">Enter your name: </label>
<input type="text" name="name" />
</div>
<div>
<label for="age-input">Enter your age: </label>
<input type="number" name="age" />
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>

To build Docker Image:


docker build -t ping-server:latest

147
To run container from docker image:

docker run -p 3000:3000 ping-server:latest

OUTPUT:

148
149
RESULT:

Thus the above program is executed successfully and also verified

Ex. No: 24

Date: Deploy a simple Guestbook application using docker

AIM:
To deploy a simple guestbook application using docker.

PROCEDURE:

Step 1: Open VS Code with the selected project directory.

Step 2: Initialize the project using “npm init” command.

Step 3: Install required packages.

Step 4: Create “Dockerfile” in project directory.

Step 5: Write the image building logic inside “Dockerfile”.

Step 6: Initialize the express server and listen on port 3000

Step 7: Create routes and route handler for HTTP method GET and POST

Step 8: Send html file as response for root route (i.e) “/”, Which has a form that will
make a POST request to the “/” route.

150
Step 9: Build image using “docker build -t ping-server:latest” command

Step 10: After successful build create a container using that image.

Step 11: To create a container use “docker run -p 3000:300 ping-server:latest”


command.

Step 12: Now the development server will started and the website can be viewed at
http://localhost:3000/.

REQUIRED PACKAGES:

1. Express
2. Express-handlebars
3. Mongoose
4. Nodemon

IMPLEMENTATION:

package.json

{
"name": "guest-book",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"express-handlebars": "^7.0.7",
"mongoose": "^7.3.0"
},
"devDependencies": {
"nodemon": "^2.0.22"
}
}

server.js

const express = require("express");

151
const mongoose = require("mongoose");
const { engine } = require("express-handlebars");

const Review = require("./models/Review");

const app = express();

const connectDB = async () => {


try {
const { connection } = await mongoose.connect("mongodb://127.0.0.1:27017/guestbook");
console.log(`Successfully connected to DB(${connection.host})`);
} catch (err) {
console.log(err.message);
}
};

app.use(express.urlencoded({ extended: false }));


app.set("view engine", "hbs");
app.engine(
"hbs",
engine({
layoutsDir: __dirname + "/views/layouts",
defaultLayout: "index",
extname: "hbs"
})
);

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


try {
const reviews = await Review.find({}).lean();

res.render("main", {
reviews
});
} catch (err) {
console.log(err.message);
}
});

app
.route("/add-review")
.get((req, res) => {
res.render("add");
})
.post(async (req, res) => {
const newReview = new Review(req.body);
try {
await newReview.save();
res.redirect("/");
} catch (err) {
console.log(err);
}
});

152
app.listen(3000, () => {
console.log("Server started on port 3000");
connectDB();
});
models->Review.js

const mongoose = require("mongoose");

const reviewSchema = new mongoose.Schema(


{
name: {
type: String,
trim: true
},
email: {
type: String,
trim: true
},
body: {
type: String,
trim: true,
required: true
}
},
{ timestamps: true }
);

module.exports = mongoose.model("review", reviewSchema);

views->add.hbs

<div class="card">
<div class="card-body">
<h2 class="text-center mb-3">Share what you feel with us.</h2>
<form method="POST" action="/add-review">
<div class="form-group mb-1">
<label for="">Name</label>
<input type="text" name="name" class="form-control" placeholder="Your Name" />
</div>
<div class="form-group mb-1">
<label for="">Email</label>
<input
type="email"
name="email"
class="form-control"
placeholder="Your email will be safe with us"
/>
</div>
<div class="form-group">
<label for="">Review</label>
<textarea

153
class="form-control"
rows="4"
placeholder="Write what you feel"
name="body"
></textarea>
</div>
<div class="mt-3 float-end">
<a href="/" class="btn btn-secondary">Cancel</a>
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
</div>
</div>

views->main.hbs

<div class="row">
{{#if reviews}}
{{#each reviews}}
<div class="col-lg-6 col-md-12 mb-2">
<div class="card">
<div class="card-body">{{this.body}}</div>
<div class="card-footer">By: {{this.name}}</div>
</div>
</div>
{{/each}}
{{else}}
<div class="col-lg-12 col-md-12">
<h2 class="text-secondary text-center">No reviews added yet.</h2>
</div>
{{/if}}
</div>

views->layouts->index.hbs

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM"
crossorigin="anonymous">
<title>Guestbook</title>
</head>
<body>
{{> header}}
<div class="container mt-3">
{{{body}}}
</div>
</body>
</html>

154
views->partials->header.hbs

<header class="navbar navbar-dark text-light bg-dark">


<div class="container d-flex align-items-center justify-content-between">
<h1 class="brand">Guestbook</h1>
<a href="/add-review" class="btn btn-primary">Share your Feedback</a>
</div>
</header>

OUTPUT:

155
RESULT:
Thus the above program is executed successfully and also verified.

156

You might also like