0% found this document useful (0 votes)
4 views

FSD Practical Notes1

The document outlines various exercises related to web development, including creating forms with JavaScript validation, fetching data using the Fetch API, and setting up Node.js servers for serving static files and handling form submissions. Each exercise includes an aim, algorithm, and source code for implementation. The exercises cover both basic and advanced topics, such as using Express and MongoDB for data management.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

FSD Practical Notes1

The document outlines various exercises related to web development, including creating forms with JavaScript validation, fetching data using the Fetch API, and setting up Node.js servers for serving static files and handling form submissions. Each exercise includes an aim, algorithm, and source code for implementation. The exercises cover both basic and advanced topics, such as using Express and MongoDB for data management.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

lOMoARcPSD|52205331

Student COPY FWSD - Lab Materials

Full Stack Web development (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Vishal Solanki ([email protected])
lOMoARcPSD|52205331

Ex.No: 01 CREATE A FORM AND VALIDATE THE


CONTENTS OF THE FORM USING JAVASCRIPT
Date:

Aim:
To create a form and validate the contents of the form using JavaScript.

Algorithm:
Step 1: Create "index.html" with basic HTML structure.
Step 2: Add form elements (name, register number, city dropdown).
Step 3: JavaScript function should check if all form fields are filled out.
Step 4: Redirect to "success.html" on successful form submission.
Step 5: Create "success.html" with a success message.
Step 6: End the Program.

Source Code:
A) index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
</head>
<body>
<h1>Student Form</h1>
<form id="studentForm" onsubmit="return validateForm()"
action="success.html">
<b>Name: </b><input type="text" id="name" name="name"
placeholder="Enter Your
Name"><br>
<b>Register Number: </b><input type="text" id="reg" name="reg"
placeholder="Enter Your
Register Number"><br>
<b>City: </b><select id="city" name="city">
<option value="" selected disabled>Select City</option>
<option value="India">India</option>

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

<option value="Russia">Russia</option>
<option value="London">London</option>
<option value="Poland">Poland</option>
<option value="Ukraine">Ukraine</option>
</select><br>
<input type="submit" value="Submit">
</form>

<!-- JAVASCRIPT -->


<script>
function validateForm() {
var name = document.getElementById("name").value;var
reg = document.getElementById("reg").value;
var city = document.getElementById("city").value;if
(!name.trim() || !reg.trim() || !city) {
alert("All fields must be filled out");
return false;
}
return true;
}
</script>
</body>
</html>

B) success.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Success</title>
</head>
<body>
<h1>Done! Successfully submitted</h1>
</body>
</html>

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

Ex.No: 02 GET DATA USING FETCH API FROM AN OPEN-


SOURCE ENDPOINT AND DISPLAY THE
Date: CONTENTS IN THE FORM OF A CARD.

Aim:
To Get data using Fetch API from an open-source endpoint and display thecontents in the
form of a card

Algorithm:
Step 1: Start the program.
Step 2: Open the HTML file (index.html) in a web browser.
Step 3: Render the HTML content.
Step 4: Define the basic HTML5 structure.
Step 5: Include a link to the CSS file (styles.css).
Step 6: Create a <div> element with the id "userDetails" and class "card".
Step 7: Define CSS rules to style elements.
Step 8: Style elements with the class "card" to create a card-like appearance.
Step 9: Style <img> elements to define their size and shape.
Step 10: Define a constant variable api_url to store the API endpoint URL
(https://jsonplaceholder.typicode.com/users).
Step 11: Create an asynchronous function fetchAndDisplayUserDetails()to
fetch and display user details.
Step 12: Prompt the user to enter a user ID.
Step 13: Fetch user data from the API endpoint (api_url).
Step 14: Convert the response to JSON format.
Step 15: Find the user with the specified ID in the fetched data.
Step 16: Update the HTML content of the "userDetails" element to displaythe
user details.
Step 17: Handle errors that may occur during fetching and displaying user
details.
Step 18: Call the fetchAndDisplayUserDetails() function to fetch and
display user details when the page loads.
Step 19: Stop the program.

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

Source Code:
A) index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Information</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div id="userDetails" class="card"></div>
<script src="script.js"></script>
</body>
</html>

B) styles.css
.card {
border: 1px solid #ccc;
border-radius: 5px;
padding: 20px; margin:
10px;
width: 300px;
}

img {
width: 100px; height:
100px; border-
radius: 50%;
margin-bottom: 10px;
}

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

C) script.js
const api_url = "https://jsonplaceholder.typicode.com/users";

async function fetchAndDisplayUserDetails() {try


{
const userId = parseInt(prompt("Enter the User ID: "));
const response = await fetch(api_url);
const users = await response.json();
const user = users.find(user => user.id === userId);

const userDetails = document.getElementById("userDetails");if


(user) {
userDetails.innerHTML = `
<h2>User Details</h2>
<div>
<img src="person_icon.png" alt="Person Icon">
<p><strong>Employee ID:</strong> ${user.id}</p>
<p><strong>Name:</strong> ${user.name}</p>
<p><strong>Username:</strong> ${user.username}</p>
<p><strong>Email:</strong> ${user.email}</p>
</div>
`;
} else {
userDetails.innerHTML = "<p>User not found</p>";
}
} catch (error) {
console.error("Error fetching and displaying user details:", error);
}
}

fetchAndDisplayUserDetails();

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

Ex.No: 03 CREATE A NODEJS SERVER THAT SERVES STATIC


HTMLAND CSS FILES TO THE USER WITHOUT USING
Date:
EXPRESS

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

Algorithm:
Step 1: Start the Program
Step 2: Open a text editor and create a new file named index.html.
Step 3: Create a new file named styles.css
Step 4: Create a new file named server.js
Step 5: Save all three files in the same directory.
Step 6: Open a terminal or command prompt in the directory where yousaved
the files.
Step 7: Type node server.js to start the server.
Step 8: Press Enter to run the command.
Step 9: Open a web browser and navigate to http://localhost:3000/
to viewthe page.

Step 10: To stop the server, switch back to the terminal or command
prompt window and press Ctrl + C on your keyboard.
Step 11: Stop the Program.

Source Code:
A) index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Full Stack Web Development</title>
</head>
<body>
<h1>Full Stack Web Development</h1>
<p>- Computer Applications</p>
</body>
</html>

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

B) style.css
body {
background-color: green;
color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh; margin:
0;
}

C) server.js
const http = require('http');
const fs = require('fs');

const port = 3000;

const server = http.createServer((req, res) => {if


(req.url === '/') {
fs.readFile('index.html', (err, data) => {if
(err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
} else if (req.url.match(/\.(html|css)$/)) {
const filePath = req.url.slice(1);
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
res.writeHead(200, { 'Content-Type': filePath.endsWith('.css') ?
'text/css' : 'text/html' });
res.end(data);
}
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });

res.end('404 Not Found');}});

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

res.writeHead(404, { 'Content-Type': 'text/plain' });


res.end('404 Not Found');
}
});
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

Ex.No: 04 CREATE A NODEJS SERVER USING EXPRESS THAT STORES


DATA FROM A FORM AS A JSON FILE AND DISPLAYS IT IN
Date: ANOTHER PAGE. THE REDIRECT PAGESHOULD BE PREPARED
USING HANDLEBARS

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

Algorithm:
Step 1: Start the Program
Step 2: Create a directory named "New folder" on your desktop.
Step 3: Inside "New folder", create a file named "index.js".
Step 4: Inside "New folder", create a folder named "views".
Step 5: Inside the "views" folder, create a file named "index.handlebars".
Step 6: Open a terminal or command prompt.
Step 7: Navigate to your project directory ("New folder").
Step 8: Run "npm install express express-handlebars body-parser" to installnecessary
packages.
Step 9: Run the command "node index.js" to start the Node.js server.
Step 10: Open a web browser and enter "http://localhost:3000/" in the
address bar.
Step 11: Return to the terminal where the server is running.
Step 12: Press “Ctrl + C” to stop the server.
Step 13: Stop the Program

Source Code:
A) New folder/views/index.js
const express = require('express');
const expbs = require('express-handlebars');
const bodyParser = require('body-parser');
const path = require('path'); // Import path module
const app = express();

// Use body-parser middleware with extended option


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

// Set the views directory


app.set('views', path.join( dirname, 'views'));

app.engine('handlebars', expbs.engine({ defaultLayout: false }));


app.set('view engine', 'handlebars');

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

// Routing
app.get('/', function(request, response, next) {
response.render('index', { layout: false });
});

app.post('/', function(request, response, next) {


response.send(request.body);
});

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

B) New folder/views/index.handlebars
<h1>Student Form</h1>
<form action="/" method="post">
<table style="font-size: 20px;">
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" id="name" name="name"
placeholder="Your name.."></td>
</tr>
<tr>
<td><label for="reg">Register Number:</label></td>
<td><input type="text" id="reg" name="registerNumber"
placeholder="Your number"></td>
</tr>
<tr>
<td><label for="city">City:</label></td>
<td><input type="text" id="city" name="city" placeholder="Your
City"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"></td>
</tr>
</table>
</form>

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

CREATE A NODEJS SERVER USING EXPRESS THAT


Ex.No: 05 CREATES, READS, UPDATES AND DELETES STUDENTS
DETAILS AND STORES THEM IN MONGODB DATABASE.THE
INFORMATION ABOUT THE USER SHOULD BE OBTAINED
Date: FROM A HTML FORM.

Aim:
To create a NodeJS server using Express that creates, reads, updates and deletes
students details and stores them in MongoDB database. The information about the
user should beobtained from a HTML form.

Algorithm:
Step 1: Start the Program.
Step 2: Open MongoDB Compass and click on the "Connect" button.
Step 3: In the "Connection" tab, enter the following connection string in theServer
field “mongodb://localhost:27017/student”
Step 4: Click on the "Connect" button.
Step 5: MongoDB Compass will connect to the MongoDB server.
Step 6: In the left-hand sidebar, you will see the “student” database and the
“Studetails” collection.
Step 7: To start the server, open a terminal or command prompt, navigate to the
directory where the project is located, and run the command “node
index.js”.
Step 8: The server will start and you will see the message "server listeningat port
3000" in the terminal or command prompt.
Step 9: To stop the server, press Ctrl + C in the terminal or command prompt.
Step 10: To check the databases in MongoDB Compass, select the student
database in the left-hand sidebar and you will see the students
collection.
Step 11: To stop the MongoDB Compass connection, click on the "Connect"
button in the top left corner to open the connection menu, and then click
on the "Disconnect" button to close the connection.
Step 12: End the Program

Source Code:
A) index.js
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const path = require("path"); // Import the 'path' module

mongoose.connect("mongodb://localhost:27017/student");

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

const app = express();


app.use(bodyParser.json());
app.use(express.static("public")); // Serve static files from the 'public'
directory
app.use(bodyParser.urlencoded({ extended: true }));
const studentSchema = new mongoose.Schema({
name: String,
Reg_number: String,
Address: String, City:
String
});

const Student = mongoose.model("Student", studentSchema);


app.post("/sign_up", (req, res) => {
const { name, reg, add, city } = req.body;
const newStudent = new Student({ name,
Reg_number: reg,
Address: add, City:
city,
});
New Student.save()
.then(student => {
console.log("Record inserted Successfully");
res.redirect("/view.html");
})
.catch(err => {
console.error("Error inserting record:", err); res.status(500).send("Error
inserting record");});
});app.get("/add_student", (req, res) => {
res.sendFile(path.join( dirname, "public", "index.html"));
});app.get("/api/students", (req, res) => {

Student.find({})
.then(students => {
res.send(students);
})
.catch(err => {
console.error("Error retrieving students:", err);
res.status(500).send("Error retrieving students");
});app.delete("/api/student/:id", (req, res) => {const id = req.params.id;
Student.find By Id And Delete(id)
app. delete("/api/database", (req, res) => {
mongoose. connection.Database()
.then(() => {
console.log
res.send("Database deleted successfully");

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

app.listen(3000, () => {
console.log("server listening at port 3000");
});
app.put("/api/student/:id", (req, res) => {
const id = req.params.id;
const { name, reg, add, city } = req.body;
Student.findByIdAndUpdate(id, { name, Reg_number: reg, Address: add,city },
.then(updatedStudent => {if
(!updatedStudent) {
return res.status(404).send("Student not found");}
res.send("Student updated successfully");})
.catch(err => {
console.error("Error updating student:", err);
res.status(500).send("Error updating student");});});

B) mongodb.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();

app.use(express.json());

let database;

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


res.send('Welcome to Mongodb API');
});

MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser:true
}, (err, client) => {
if (err) throw err;
database = client.db('student'); app.listen(3000,
() => { console.log('connection connected');
});});

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


database.collection('Studetails').find({}).toArray((err, result) => {if
(err) throw err;
res.send(result);
});
}

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

C) public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Data</title>
</head>
<body>
<h1>Please fill data in the form below:</h1>
<form method="POST" action="/sign_up">
<table>
<tr>
<td><label>Name:</label></td>
<td><input type="text" name="name" required></td>
</tr>
<tr>
<td><label>Reg number:</label></td>
<td><input type="text" name="reg" required></td>
</tr>
<tr>
<td><label>Address:</label></td>
<td><input type="text" name="add" required></td>
</tr>
<tr>
<td><label>City:</label></td>
<td><input type="text" name="city" required></td>
</tr>
<tr>
<td>
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>
</body>
</html>

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

D) public/view.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>View Student Records</title>
</head>
<body>
<h1>Student Records</h1>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Reg number</th>
<th>Address</th>
<th>City</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="studentRecords">
<!-- Student records will be dynamically inserted here -->
</tbody>
</table>
<button onclick="location.href='/add_student'">Add Student</button>
<!—JAVASCRIPT-->
<script>
fetch('/api/students')
.then(response => response.json())
.then(students => {
const studentRecords =
document.getElementById('studentRecords');
students.forEach(student => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${student.name}</td>
<td>${student.Reg_number}</td>
<td>${student.Address}</td>
<td>${student.City}</td>

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

<td><button onclick="editStudent('${student._id}', '${student.name}',


'${student.Reg_number}', '${student.Address}',
'${student.City}')">Edit</button></td>
<td><button
onclick="deleteStudent('${student._id}')">Delete</button></td`;
studentRecords.appendChild(row);});
.catch(error => console.error('Error fetching student records:', error));
editStudent(id, name, reg, add, city) {
const newName = prompt("Enter new name", name);
const newReg = prompt("Enter new registration number", reg);
const newAdd = prompt("Enter new address", add);
const newCity = prompt("Enter new city", city);
if (newName && newReg && newAdd && newCity) {fetch(`/api/student/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'},
body: JSON.stringify({
name: newName, reg:
newReg,
add: newAdd,
city: newCity}})
.then(response => response.text())
.then(message => {
alert(message);
location.reload(); // Refresh page after editing})
.catch(error => console.error('Error editing student:', error));}
}function deleteStudent(id) {
if (confirm("Are you sure you want to delete this student?")) {
fetch(`/api/student/${id}`, {method: 'DELETE'
})
.then(response => response.text())
.then(message => {
alert(message);
location.reload(); // Refresh page after deletion
})
.catch(error => console.error('Error deleting student:', error));
}
}
</script>
</body>
</html>

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

CREATE A NODEJS SERVER THAT CREATES, READS,


Ex.No: 06
UPDATESAND DELETES EVENT DETAILS AND
STORES THEM IN A MYSQLDATABASE. THE
Date: INFORMATION ABOUT THE USER SHOULD BE
OBTAINED FROM A HTML FORM.

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

Algorithm:
Step 1: Run “npm install express mysql body-parser” in your command
prompt.
Step 2: Set up an instance of Express and define routes and middleware in
“server.js”.
Step 3: Connect to MySQL database named “events_db”.
Step 4: Create route to serve “index.html” for the homepage (/ route).
Step 5: Handle form submission to add events (/addEvent route).
Step 6: Create route to display events (/events route).
Step 7: Implement editing functionality for the most recent event (/editroute).
Step 8: Define route to update event details (/updateEvent route).
Step 9: Implement deletion of most recent event (/delete route).
Step 10: Start the Express server listening on “http://localhost:3000”.
Step 11: Design HTML form (index.html) for event submission.
Step 12: Set up MySQL database (events_db) and events table.
Step 13: Start the server and test the application's functionality.
Step 14: Terminate the server by closing the command prompt or using“Ctrl +
C”.
Step 15: To erase the database, run the SQL command
“DROP DATABASE events_db”;

Source Code:
A) Create a MySQL database named events_db and a table named
events

CREATE DATABASE events_db;


USE events_db;
CREATE TABLE events (
id INT AUTO_INCREMENT PRIMARY KEY,
participantName VARCHAR(255),
eventName VARCHAR(255),
eventDate DATE,
eventPlace VARCHAR(255)
);

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

B) server.js

const express = require('express');


const mysql = require('mysql');
const bodyParser = require('body-parser');

const app = express();


const port = 3000;

const connection = mysql.createConnection({


host: 'localhost',
user: 'root',
password: '', database:
'events_db'
});

connection.connect((err) => { if (err) throw err; console.log('Connected to


MySQL database'); });

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

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

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


const { participantName, eventName, eventDate, eventPlace } =
req.body;
connection.query('INSERT INTO events (participantName, eventName,
eventDate, eventPlace) VALUES (?, ?, ?, ?)', [participantName, eventName,
eventDate, eventPlace], (err, result) => {
if (err) throw err;
console.log('Event added to the database');
res.redirect('/events');});});
app.get('/events', (req, res) => {
connection.query('SELECT * FROM events', (err, rows) => {if
(err) throw err;
res.send(`<h1>Success! Your Events Recorded</h1><button
onclick="location.href='/edit'">Edit</button><button
onclick="location.href='/add'">Add</button><button
onclick="location.href='/delete'">Delete</button><ul>${eventsList}</ul>});
});
app.get('/edit', (req, res) => {
connection.query('SELECT * FROM events ORDER BY id DESC LIMIT1',
(err, rows) => {
if (!event) res.send('No event found');else
<h1>Edit Event</h1>
<form action="/updateEvent" method="post">
<input type="hidden" name="eventId" value="${event.id}">

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

<label for="participantName">Participant Name:</label><br>


<input type="text" id="participantName" name="participantName"
value="${event.participantName}"><br>
<label for="eventName">Event Name:</label><br>
<input type="text" id="eventName" name="eventName"
value="${event.eventName}"><br>
<label for="eventDate">Event Date:</label><br>
<input type="date" id="eventDate" name="eventDate"
value="${event.eventDate}"><br>
<label for="eventPlace">Event Place:</label><br>
<input type="text" id="eventPlace" name="eventPlace"
value="${event.eventPlace}"><br><br>
<input type="submit" value="Update">
</form>`);});
app.post('/updateEvent', (req, res) => {
const { eventId, participantName, eventName, eventDate, eventPlace }
= req.body;
if (!eventDate) return res.status(400).send('Event date cannot be
empty');
connection.query('UPDATE events SET participantName=?,
eventName=?, eventDate=?, eventPlace=? WHERE id=?',
[participantName, eventName, eventDate, eventPlace, eventId], (err,
result) => {
if (err) throw err;
console.log('Event updated in the database');
res.redirect('/events');});});
app.get('/add', (req, res) => res.sendFile( dirname + '/index.html'));

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


connection.query('DELETE FROM events ORDER BY id DESC LIMIT1',
(err, result) => {
if (err) throw err;
console.log('Recent event deleted from the database');
res.redirect('/events');});});

C) index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Event Form</title>
</head>
<body>

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

<form action="/addEvent" method="post">


<label for="participantName">Participant Name:</label><br>
<input type="text" id="participantName"
name="participantName"><br>
<label for="eventName">Event Name:</label><br>
<input type="text" id="eventName" name="eventName"><br>
<label for="eventDate">Event Date:</label><br>
<input type="date" id="eventDate" name="eventDate"><br>
<label for="eventPlace">Event Place:</label><br>
<input type="text" id="eventPlace" name="eventPlace"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Output:
Open MySQL 8.0 Command Line Client and enter the password.

Create the table from the above program.

Open Command Prompt and execute 'node server.js'


within.specified directory.

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

Ex.No: 07
CREATE A COUNTER USING REACTJS
Date:

Aim:
To create a counter using ReactJS.

Algorithm:
Step 1: Set your working directory and create a new React project using“npx
create-react-app counter-app”.
Step 2: Navigate into the newly created project directory with“cd
counter-app”.
Step 3: Write the code for the counter component in “Counter.js”, including state
management for count value, and functions for incrementing,
decrementing, and resetting the count.
Step 4: Create a CSS file named “Counter.css” for styling.
Step 5: Import the CSS file into “Counter.js”.
Step 6: Import the “Counter” component in “App.js”.
Step 7: Start the development server with “npm start”.
Step 8: Test your counter component by interacting with the buttons to increment,
decrement, and reset the count.
Step 9: Once you're done testing, stop the development server by clicking “Ctrl +
C” in the terminal/command prompt where the server isrunning.
Step 10: Stop the Program.

Source Code:
A) Counter.js

import React, { useState } from 'react';


import './Counter.css';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () =>
setCount(prevCount => prevCount + 1);};

const decrement = () => {


setCount(prevCount => prevCount - 1);};
const reset = () => {
setCount(0);};
return (
<div className="counter">
<h2>COUNTER</h2>
<div className="count">{count}</div>
<div className="buttons">
<button onClick={decrement}>-</button>
<button onClick={reset} className="reset-button">Reset</button> );

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

B) counter-app/src/App.js

import React from 'react';


import './App.css';
import Counter from './Counter';

function App() {
return (
<div className="App">
<Counter />
</div>);}
export default App;

C) counter-app/src/Counter.css
.counter {
text-align: center;
margin-top: 50px;
}

.count {
font-size: 24px;
margin-bottom: 20px;
}

.buttons button { font-


size: 18px; margin:
0 10px; padding:
5px 10px;cursor:
pointer;
}

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

CREATE A TODO APPLICATION USING REACTJS.


Ex.No: 08 STORE THE DATA TO A JSON FILE USING A SIMPLE
NODEJS SERVER AND RETRIEVE THE INFORMATION
Date:
FROM THE SAME DURING PAGE RELOADS.

Aim:
To Create a Todo application using ReactJS. Store the data to a JSON fileusing
a simple NodeJS server and retrieve the information from the same during page reloads.

Algorithm:
Step 1: Start the Program
Step 2: Open the command prompt on your computer.
Step 3: Run the command “npx create-react-app todo-app” to create a newReact
application named “todo-app”.
Step 4: After the project is created, navigate to the root directory of your “todo-app”
project using the “cd” command.
Step 5: Replace the content of "src/App.js" for the Todo application.
Step 6: Move the "db.json" file to the "public" directory of your "todo-app"project.
Step 7: Open another command prompt window.
Step 8: Navigate to the root directory of your "todo-app" project using the "cd"
command.
Step 9: Run the "json-server" command to start the JSON Server. Use the
following command -> "json-server --watch public/db.json --port 3001".
Step 10: Press Enter to execute the command. JSON Server will start
watching the "db.json" file and serve it on port 3001.
Step 11: Leave the command prompt running with JSON Server.
Step 12: Start your React application by running the command "npm start".
Step 13: Your React application will start, and you can access it in your web browser
at the specified address "http://localhost:3000".
Step 14: Use the Todo application in the browser to add, complete, and clear tasks.
The changes will be reflected in the JSON file served by JSONServer.
Step 15: Once you're done with your work, go back to the command prompt where
JSON Server is running.
Step 16: Press "Ctrl + C" to stop "JSON Server".
Step 17: Similarly, go back to the command prompt where the React application is
running.
Step 18: Press "Ctrl + C" to stop the "React application".
Step 19: You have now stopped both servers, and you can close the commandprompt.
Step 20: Stop the Program.

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

Source Code:
A) todo-app/src/App.js

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


import axios from 'axios';

function App() {
const [tasks, setTasks] = useState([]);
const [newTask, setNewTask] = useState('');

useEffect(() => {
const fetchTasks = async () => {
try{
const response = await axios.get('http://localhost:3001/tasks');
setTasks(response.data);
} catch (error) {
console.error('Error fetching tasks:', error);}
};
fetchTasks();
}, []);
const toggleTaskCompletion = async (id) =>
{const updatedTasks = tasks.map(task =>
task.id === id ? { ...task, completed: !task.completed } : task);
setTasks(updatedTasks);
await axios.put(`http://localhost:3001/tasks/${id}`, updatedTasks.find(task =>task.id
=== id));};
const clearCompletedTasks = async () => {
const completedTasks = tasks.filter(task => task.completed);
setTasks(tasks.filter(task => !task.completed));
await Promise.all(completedTasks.map(task =>
axios.delete(`http://localhost:3001/tasks/${task.id}`)));
};
const handleAddTask = async () => {if ({
const newTaskObj = {
id: tasks.length > 0 ? tasks[tasks.length - 1].id + 1 : 1,
task: newTask,
completed: false
};
setTasks([...tasks, newTaskObj]);
await axios.post('http://localhost:3001/tasks', newTaskObj);
setNewTask('');
}
};

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

return (
<div>
<h1>Todo List</h1>
<div>
<input
type="text"
value={newTask}
onChange={(e) => setNewTask(e.target.value)}
placeholder="Enter task"
/>
<button onClick={handleAddTask}>Add Task</button>
</div>
<button onClick={clearCompletedTasks}>Clear Completed Tasks</button>
<ul>
{tasks.map(task => (
<li key={task.id} style={{ textDecoration: task.completed ? 'line-through' :
'none' }}>
<input
type="checkbox"
checked={task.completed}
onChange={() => toggleTaskCompletion(task.id)}
/>
{task.task}
</li>
))}
</ul>
</div>
);
}
export default App;

B) todo-app/public/db.json

{
"tasks": [
{
"id": 1,

"task": "Do Jogging",


"completed": false
},
{
"id": 2,
"task": "Complete Class Notes",
"completed": false
},

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

{
"id": 3,
"task": "Call Mom",
"completed": false},{
"id": 4,
"task": "Prepare Exam to Study",
"completed": false},
{
"id": 5,
"task": "Feed Cat",
"completed": false
},
{
"id": 6,
"task": "Fill the Water Tank",
"completed": false
},
{
"id": 7,
"task": "Do Laundry",
"completed": false
},
{
"id": 8,
"task": "Wash Clothes",
"completed": false
}
]
}

Note: Starting with the "JSON Server" followed by launching the "React Application"
ensures that the “db.json” files are visible in the ReactJS Application Server for task
modifications. If only the "React Application" is initiated without the "JSON Server" the
“db.json” files will not appear on the ReactJS Application Server.

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

CREATE A SIMPLE SIGN UP AND LOGIN MECHANISM


Ex.No: 09 AND AUTHENTICATE THE USER USING COOKIES. THE
USER INFORMATION CAN BE STORED IN EITHER
Date:
MONGODB OR MYSQL AND THE SERVER SHOULD BE
BUILT USING NODEJS AND EXPRESS FRAMEWORK.

Aim:

To create a simple sign up and login mechanism and authenticate the userusing
cookies. the user information can be stored in either mongodb or mysql and the server
should be built using nodejs and express framework.

Algorithm:

Step 1: Start the Program


Step 2: Install required dependencies by running “npm install express express-session
bcryptjs mysql2 ejs”.
Step 3: Create the project structure with directories for “public, views”, and
necessary files (index.js and dbConnection.js).
Step 4: Set up the CSS file (styles.css) in the “public” directory for styling.
Step 5: Create EJS templates for the header, footer, login, register, and homepages in
the “views” directory.
Step 6: Implement database connection logic in “dbConnection.js” usingMySQL.
Step 7: Set up the Express application in “index.js” including middleware for parsing
requests, serving static files, and session management.
Step 8: Define helper middleware functions “redirectIfAuthenticated” and
“redirectIfNotAuthenticated” to control access to login and register routes.
Step 9: Create route handlers for the login (/login), register (/register), home (/),
and logout (/logout) endpoints.
Step 10: Implement logic for user registration, login, session management, and
logout in the route handlers.
Step 11: Render appropriate views with error or success messages based on
user actions.
Step 12: Start the Express server using “app.listen()” to listen for incoming
requests on port 3000.
Step 13: Test the application by visiting “http://localhost:3000” in your web
browser.
Step 14: Once you're done testing, stop the development server by clicking “Ctrl
+ C” in the terminal/command prompt where the server is running.
Step 15: Stop the Program.

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

Source Code:

A) Create a MySQL database named ex9 and a table named users

CREATE DATABASE IF NOT EXISTS ex9;


use ex9;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);

B) dbConnection.js

const mysql = require('mysql2/promise');


const dbConnection = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'ex9'
});
module.exports = dbConnection;

C) public/styles.css

body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh; margin:
0;
}

.container {
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h1 {
margin-bottom: 20px;

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

font-size: 24px;
}

label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}

input {
width: 90%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 3px;
}

button { width:
100%;
padding: 10px; background-
color: #007bff;color: white;
border: none;
border-radius: 3px;
cursor: pointer;
}

button:hover {
background-color: #0056b3;
}

.error { color:
red;
margin-bottom: 10px;
}

.success { color:
green;
margin-bottom: 10px;
padding: 10px;
border: 1px solid green;
background-color: #d4edda;
border-radius: 3px;}
a {color: #007bff;
text-decoration: none;}
a:hover {text-decoration: underline;}
.link {
margin-top: 10px;
text-align: center;}

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

D) views/header.ejs

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= title %></title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>

E) views/footer.js

</body>
</html>

F) views/login.ejs

<%- include('header', { title: 'Login' }) %>


<div class="container">
<h1>Login</h1>
<form action="/login" method="POST">
<label for="email">Email</label>
<input type="email" name="email" id="email" required>
<label for="password">Password</label>
<input type="password" name="password" id="password" required>
<% if (error) { %>
<div class="error"><%= error %></div>
<% } %>
<button type="submit">Login</button>

<div class="link"><a href="/register">Register</a></div>


</form>
</div>
<%- include('footer') %>

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

G) views/register.ejs

<%- include('header', { title: 'Register' }) %>


<div class="container">
<h1>Register</h1>
<form action="/register" method="POST">
<label for="name">Name</label>
<input type="text" name="name" id="name" required>
<label for="email">Email</label>
<input type="email" name="email" id="email" required>
<label for="password">Password</label>
<input type="password" name="password" id="password" required>
<% if (error) { %>
<div class="error"><%= error %></div>
<% } %>
<% if (success) { %>
<div class="success"><%= success %></div>
<% } %>
<button type="submit">Register</button>
<div class="link"><a href="/login">Login</a></div>
</form>
</div>
<%- include('footer') %>

H) views/home.ejs

<%- include('header', { title: 'Home' }) %>


<div class="container">
<div class="profile">
<div class="img">👤</div>
<h2><%= user.name %></h2>
<span><%= user.email %></span><br>
<a href="/logout">Logout</a>
</div>
</div>
<%- include('footer') %>

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

I) index.js

const express = require('express');


const session = require('express-session');
const bcrypt = require('bcryptjs');
const path = require('path');
const db = require('./dbConnection');

const app = express();


app.set('views', path.join( dirname, 'views'));
app.set('view engine', 'ejs');

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


app.use(express.static(path.join( dirname, 'public')));
app.use(session({
secret: 'my_secret', resave:
false, saveUninitialized:
true,
cookie: { maxAge: 3600 * 1000 } // 1 hour
}));

const redirectIfAuthenticated = (req, res, next) => {if


(req.session.userId) {
return res.redirect('/');
}
next();
};

const redirectIfNotAuthenticated = (req, res, next) => {if


(!req.session.userId) {
return res.redirect('/login');
}
next();
};

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


res.render('login', { error: null });
});

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


const { email, password } = req.body;
const [rows] = await db.execute('SELECT * FROM users WHERE email =
?', [email]);
if (rows.length === 1 && await bcrypt.compare(password,rows[0].password))
{

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

req.session.userId = rows[0].id;
return res.redirect('/');
}
res.render('login', { error: 'Invalid email or password' });
});

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


res.render('register', { error: null, success: null });
});

app.post('/register', redirectIfAuthenticated, async (req, res) => {


const { name, email, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);try {
await db.execute('INSERT INTO users (name, email, password) VALUES(?, ?,
?)', [name, email, hashedPassword]);
res.render('register', { error: null, success: 'You have successfully
registered.' });
} catch (err) {
res.render('register', { error: 'Email is already in use', success: null });
}
});

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


const [rows] = await db.execute('SELECT * FROM users WHERE id = ?',
[req.session.userId]);
if (rows.length === 1) {
res.render('home', { user: rows[0] });
} else {
res.redirect('/logout');
}
});

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


req.session.destroy(() => {
res.redirect('/login');
});
});

app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

Ex.No: 10 CREATE AND DEPLOY A VIRTUAL MACHINE USING A


VIRTUAL BOX THAT CAN BE ACCESSED FROM THE
Date: HOST COMPUTER USING SSH.

Aim:
To create and deploy a virtual machine using a virtual box that can be
accessed from the host computer using SSH.

Algorithm:

Prepare your computer for virtualization. Install Hypervisor (virtualization tool).Import a


virtual machine. Start the virtual machine. Using the virtual machine. Shutdown the
virtual machine.

VIRTUALIZATION: The underlying technology that allows a virtual operating system to be


run as an application on your computer’s operating system.

HYPERVISOR: The virtualization application (such as VirtualBox or VMware) running on


your host computer that allows it to run a guest virtual operating system.

HOST: The computer on which you are running the hypervisor application.

GUEST: A virtual operating system running within the hypervisor on your host computer.
The virtual operating system term is synonymous with other terms such as Virtual
\Machine,VM and instance.

Step 1: Prepare your computer for Virtualization:

Enable Processor Virtualization: Ensure Virtualization is enabled on yourcomputer.


See the Virtualization Error (VT-d/VT-x or AMD-V) for troubleshooting
support.

Review File Sync Services for tools like OneDrive, Nextcloud, DropBoxSync,
iCloud, etc.
If you are using a data synchronization service, make sure it DOES NOT(or at
least not frequently)
synchronize the folder in which your hypervisor imports and installs theVirtual
Machines.

File sync services can cause a dramatic fall-off in performance for your entire
system as these services try to synchronize these massive files that are getting
updated constantly while you are using the Virtual Machines.

Sufficient Disk Space: Virtual Machines require a significant amount of Disk space
(10 GB or more each is typical). Ensure you have sufficient space on your
computer.Admin Privileges: Installing a hypervisor on a host in most cases
requires admin privileges.

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

Sufficient Disk Space: Virtual Machines require a significant amount of Disk space
(10 GB or more each is typical). Ensure you have sufficient space on your
computer.
Admin Privileges: Installing a hypervisor on a host in most cases requires admin
privileges.

Step 2: Install Hypervisor (Virtualization Tool):

Installing a hypervisor on your host is usually quite simple. In most cases, the install
program will ask only a couple of questions, such as where to install the hypervisor
software.

Step 3: Import a Virtual Machine:

The first step is to download the Virtual Machine for your course from our Course
Virtual Machines page. This will download an .ova file. The .ova fileis actually a
compressed (zipped) tarball of a Virtual Machine exportedfrom Virtual Box.

Once the Virtual Machine has been imported, it will normally show up in theguest
list within your hypervisor tool.

Step 4: Start the Virtual Machine:


To start up a Virtual Machine guest in most hypervisors, you simply click onthe
desired guest and click the Start button (often double-clicking the guesticon will
work as well)

Step 5: Using the Virtual Machine:


Sharing files between the guest and host: To learn about different ways of sharing
files, check out this guide.
Run a command with sudo (root) privileges: Open a terminal and type any
command with sudo in front to run that command as root.

Example: sudo apt-get install vim – will install the vim text editor packageon an
Ubuntu Linux Virtual Machine.

Find the IP address of your guest: Open a terminal and type ifconfig | more
– The | more (pronounced “pipe more”) will “pipe” the output of the ifconfig
command to the more command, which will show the results one page at atime,
so it doesn’t scroll by before you see it all.

If you have a Host-Only Network IP address, you will see an IP of 192.168.56.101


(or something similar). Check the Trouble-Shooting section below for more
information about the Host-Only Network.

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

Step 6: Shut down the Virtual Machine:

When you are done using a guest Virtual Machine, regardless ofhypervisor,
you need to shut it down properly. This can be done in three ways:

1. Press the shutdown button found on the desktop, taskbar, or task


menu of the guest operating system.
2. Open a terminal and type the command: sudo shutdown -h now
3. In the guest window, click Machine (menu) -> ACPI Shut down –This
will simulate the power button being pressed.

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

Ex.No: 11 CREATE A DOCKER CONTAINER THAT WILL DEPLOY


A NODEJS PING SERVER USING THE NODEJS IMAGE
Date:

Aim:
To create a Docker container that will deploy a NodeJS ping server usingthe
NodeJS image.

Algorithm:
Step 1: Start a Program
Step 2: Create a project directory named “nodejs-ping-server”.
Step 3: Initialize a new Node.js project inside the “nodejs-ping-server”
directory using npm by executing “npm init –y”.
Step 4: Install the Express framework as a dependency using npm by
executing “npm install express”.
Step 5: Create a file named “server.js” in the project directory and add thecode
for the ping server.
Step 6: Create a text file named “Dockerfile” in the project directory.
Step 7: Build the Docker image using the Dockerfile by executing “dockerbuild
-t nodejs-ping-server”.
Step 8: Run the Docker container from the built image by executing
“docker run -p 3000:3000 --name my-ping-server -d nodejs-ping-server"
Step 9: Access the ping server using a web browser or curl by executing“curl
http://localhost:3000/ping"
Step 10: Stop the Docker container by executing
“docker stop my-ping-server"
Step 11: Remove the Docker container by executing
“docker rm my-ping-server"
Step 12: Stop the Program

Source Code:
A) nodejs-ping-server/server.js

const express = require('express');


const app = express();
const port = 3000;

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


res.send('Hello from Node Js');
});

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

Downloaded by Vishal Solanki ([email protected])


lOMoARcPSD|52205331

B) nodejs-ping-server/Dockerfile

# Use the official Node.js image from the Docker Hub


FROM node:14

# Create and change to the app directory


WORKDIR /usr/src/app

# Copy package.json and package-lock.json


COPY package*.json ./

# Install dependencies
RUN npm install

# Copy the rest of the application code


COPY . .

# Expose the port the app runs on


EXPOSE 3000

# Command to run the app


CMD ["node", "server.js"]

Downloaded by Vishal Solanki ([email protected])

You might also like