FSD Practical Notes1
FSD Practical Notes1
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>
<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>
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>
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.
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;
}
C) script.js
const api_url = "https://jsonplaceholder.typicode.com/users";
fetchAndDisplayUserDetails();
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>
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');
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();
// Routing
app.get('/', function(request, response, next) {
response.render('index', { layout: false });
});
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>
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");
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");
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;
MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser:true
}, (err, client) => {
if (err) throw err;
database = client.db('student'); app.listen(3000,
() => { console.log('connection connected');
});});
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>
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>
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
B) server.js
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>
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
B) counter-app/src/App.js
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;
}
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.
Source Code:
A) todo-app/src/App.js
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('');
}
};
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,
{
"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.
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:
Source Code:
B) dbConnection.js
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;
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;}
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
G) views/register.ejs
H) views/home.ejs
I) index.js
req.session.userId = rows[0].id;
return res.redirect('/');
}
res.render('login', { error: 'Invalid email or password' });
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Aim:
To create and deploy a virtual machine using a virtual box that can be
accessed from the host computer using SSH.
Algorithm:
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.
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.
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.
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.
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.
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.
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:
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
app.listen(port, () => {
console.log(`Ping server listening at http://localhost:${port}`);
});
B) nodejs-ping-server/Dockerfile
# Install dependencies
RUN npm install