KEMBAR78
FSWD Lab | PDF | Directory (Computing) | Client–Server Model
0% found this document useful (0 votes)
8 views176 pages

FSWD Lab

The document is a laboratory record notebook for the Full Stack Web Development Laboratory (IT3511) at the University College of Engineering, Tindivanam for the academic year 2024-2025. It includes a certification section, an index of experiments such as creating a portfolio using React.js, managing a TO-DO list with a MERN stack, and developing various web applications. Each experiment outlines the aim, algorithm, and program code necessary for implementation.

Uploaded by

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

FSWD Lab

The document is a laboratory record notebook for the Full Stack Web Development Laboratory (IT3511) at the University College of Engineering, Tindivanam for the academic year 2024-2025. It includes a certification section, an index of experiments such as creating a portfolio using React.js, managing a TO-DO list with a MERN stack, and developing various web applications. Each experiment outlines the aim, algorithm, and program code necessary for implementation.

Uploaded by

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

UNIVERSITY COLLEGE OF ENGINEERING

TINDIVANAM
(A Constituent College of Anna University, Chennai)

B.TECH FIFTH SEMESTER


RECORD FOR

FULL STACK WEB DEVELOPMENT LABORATORY (IT3511)

DEPARTMENT OF INFORMATION TECHNOLOGY

LABORATORY RECORD NOTE BOOK


2024-2025

Page | 1
University College of Engineering, Tindivanam
UNIVERSITY COLLEGE OF ENGINEERING
TINDIVANAM
(A Constituent College of Anna University, Chennai)

DEPARTMENT OF INFORMATION TECHNOLOGY


LABORATORY RECORD NOTE BOOK
2024-2025
This is to certify that is a bonafide record of the work done by
Mr. /Ms. Register Number
Of IIIrd Year B.Tech, Department of Information Technology in the Full Stack
Web Development Laboratory (IT3511) in the V Semester.

University Examination held on ………………………………………….

Staff In-Charge Head of the Department

Internal Examiner External Examiner

Page | 2
University College of Engineering, Tindivanam
INDEX
S.No. Date Experiment Page No Signature

1 Design a Portfolio using React Js

Create a web application to manage the


2 TO-DO list of users, where users can
login and manage their to-do items.

3 Micro Blogging Application

Create a food delivery website where


4 users can order food from a particular
restaurant listed in the website.

5 Develop a classifieds web application to


buy and sell used products

Develop a leave management system


for an organization where users can
6 apply different types of leaves such as
casual leave and medical leave. They
can also view the available no. of days.

Develop a simple dashboard for the


project management where the
statuses of various tasks are available.
7 New tasks can be added and the status
of existing tasks can be changed among
Pending, In Progress or Completed.

Develop an online survey application


8 where a collection of questions is
available and users are asked to answer
any random 5 questions.
Ex No: 1
Design a Portfolio using React Js
Date:

Aim:
To create a portfolio website for job interview using reactjs.

Algorithm:
Step 1: download and Install node js LTS
Step 2: Now, we create an application called portfolio1 in the directory path d:/reactprojects
folder. Therefore, go to D:/reactprojects folder and type cmd to open the command prompt in
this path. Then, in the command line, give the following command.
npx create-react-app portfolio1
It installs node_modules packages in the path D:/reactprojects and creates a folder
portfolio1.

Step 3: Now, open the folder D:/reactprojects folder in MS Visual Code editor. It is to see the
files in the package and to easily manage them. We can do it manually or give the following
command in the command prompt (code .)
Here, code refers to Visual Studio Code. Dot refers to open the current folder with all its
file to manage them.

Step 4: Right-click package.json and click Open in Integrate terminal option. It opens the
command terminus at the end of the MS Visual Studio Code editor as follows.

Step 5: enter the command “npm start” in the terminal. It renders the index.html page
contents in the web browser.

Step 6: We have to update the contents in the index.html page. Whatever, we want to add to
the index.html page. We have to do it in this <div id=”root”>in the index.html page. In turn, the
element id=root is indirectly referenced in the index.js file in the src folder.

Step 7: In this index.js java script file, we have imported the root element into root variable
Now, we have to understand that, the tag <App /> refers to an object referring to the App.js file
in the src folder. The reference can be seen in the index.js file as
Import App from ‘./App’;
This means, import App.js code into the variable App. Therefore, whatever we want to keep as
contents, have to be updated in the App.js file.

Step 8: In Order to create a portfolio on our own first we need to separate into three different
files which represent the header, middle and footer of the portfolio.
Output:
Step 9: The header of the portfolio is named as App which contains the name and picture, The
names and picture are done in separate division using <div> tag. Three <div> tag is used here for
the name, picture and outline respectively inside the function App().The middle content of the
portfolio is named as home where the education, skills and contact details are added.Here, we
used four <div> tag for education, skills and contact respectively. A div tag is used to group and
outline the whole content of the middle of the portfolio.
Step 10: In index.js import the function with its file name to as (import function name from file
name) to invocate the portfolio functions (header, middle and footer) with respective to the file
name. Inside the root .render function mention the function name of the header, middle and
footer to display into the website.

Program:
In command prompt use this to create a react module for the project.

npx create-react-app portfolio2


code .
In the vs code,

App.js:
function App() {
return (
<div style = {{border:'1px solid grey', width:'100%', height:'290px'}}>
<div id='left' style={{float:'left', border:'0px solid red', width:'50%',
height:'100%'}}>
<h2> <b> <i> I am Virat Kohli. </i> </b> </h2>
</div>
<div id='right' style={{float:'left', border:'0px solid red', width:'48%',
height:'100%'}}>
<img src = {img1} style={{width:'100%', height:'100%'}}/>
</div>
</div>
);
}

Home.js:
function Home() {
return (
<div style={{border:'1px solid grey', width:'100%', height:'300px'}}>
<div style={{float:'left', width:'33%', height:'300px', border:'1px solid grey'}}>
<h2> Education </h2> <br/>
<ul>
<li>B.Tech (IT)</li>
<li>ME (CSE)</li>
<li>Ph.D. (I&C)</li>
</ul>
</div>
<div style={{float:'left', width:'33%', height:'300px', border:'1px solid grey'}}>
<h2> Skills </h2>
<ul>
<li>C, C++, Java </li>
<li>Oracle, MS SQL</li>
<li>Data Structures, Web Development, Network Security </li>
</ul>
</div>
<div style={{float:'left', width:'33%', height:'300px', border:'1px solid grey'}}>
<h2> Contact </h2>
<ul>
<li>Mob: +91 9876543210</li>
<li>Email: softengineermiltonatgmail.com</li>
</ul>
</div>

</div>
);
}

export default Home;

Footer.js:
function Footer() {
return (
<div style={{textAlign:'right', border:'1px solid grey', width:'100%', height:'25px'}}>
Developed by .............
</div>
);
}

export default Footer;

Result:
Thus the given portfolio application has been successfully developed and the results are verified.
Ex No: 2 Create a web application to manage the TO-DO list
of users, where users can login and manage their
Date: to-do items.

Aim:
To create a website using MERN stack where a user can manage his to
do list for work schedule.

Algorithm:
Required packages: express, cors, body-parser, mongoose packages, axios

Setup MongoDB:

Step 1: Create a database called todoDB


Step 2: Create a collection called items where the to-do detail are stored.
The structure of collection has name, description fields as follows.

Setup Express JS server:

Step 1: import the packages express, cors, body-parser, mongoose

Step 2: create express object and listen to the http client connection at port no. 5000

Step 3: Using mongoose package, establish connection to the todoDB in the MongoDB
database.

Step 4: Setup the schema to perform the CRUD operations as follows.


name: String,
Output:

Login page:

Mainpage.js:
description: String,

Step 5: Write the following APIs in this express server code.


To get the details from the todoDB
app.get('/', async (req, res)=>{…}

To insert a new to-do details into the todoDB


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

To update an existing to-do entry in the todoDB


app.put('/', async (req, res)=>{…}
To delete an existing to-do from the todoDB
app.post('/', async (req, res)=>{…}

Setup React JS Client:


1. Install axios package
2. Create a Login.js file to show the two options.
(i) Login to the to-do page
3. Create another file named Mainpage.js to do the insert, update, view and delete
operation in the todoDB database.
4. Setup App.js file to set up the routes to these two files.

Program:
Server side:
Server.js
const express = require('express'); // step 1: include the server module to the server-side script.
app = express(); // step 2: creating the app as server object

// step 3: make the server object use the objects of cors and body-parser module. It is for
sending the JSON message.
const cors = require('cors');
const bodyParser = require('body-parser');

app.use(cors());
app.use(bodyParser.json());

// MongoDB connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/todoDB', { useNewUrlParser: true,
useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));

// Define a schema and model


const itemSchema = new mongoose.Schema({
name: String,
description: String,
});

const Item = mongoose.model('Item', itemSchema);

app.listen(5000, ()=>{
console.log('Server is waiting for connections from the client');
});
// step 4: write the get method to respond to the client.
app.get('/', async (req, res)=>{
try{
const jsobj1 = await Item.find();
res.json(jsobj1);
}catch(err){
res.send('error in the get method of server-side code')
}
});

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


const item = new Item({
name: req.body.name,
description: req.body.description,

});
try{
const jsobj1 = await item.save();
res.status(201).json(jsobj1);
}catch(err){
res.send('error in the post method of server-side code')
}
});

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


try{
console.log(`received id is:: ${req.body.id}`);
const item = await Item.findById(req.body.id);
console.log('item found in the db' + item);
if(item){
item.name = req.body.name;
item.description = req.body.description;
const updatedItem = await item.save();
res.statuscode(201).json(updatedItem);
}
else{
res.status(404).json({message: 'Item not found'});
}
}catch(err){
res.status(400).json({message: err.message});
}
});

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


try{
console.log(`received id is:: ${req.params.id}`);
const item = await Item.findById(req.params.id);
console.log('item found in the db' + item);
if(item){
const deletedItem = await item.deleteOne();
res.statuscode(201).json(deletedItem);
}
else{
res.status(404).json({message: 'Item not found'});
}
}catch(err){
res.status(400).json({message: err.message});
}
});
Client side:

Loginpage.js
import { useNavigate } from "react-router-dom";

const Login = ()=>{


const navigate = useNavigate();
function handleSubmit() {
window.alert('hi');
navigate('/Mainpage');
}
return(
<div>
<form onSubmit={handleSubmit}>
<button type='submit'> Login </button>
</form>
</div>
);
}

export default Login;

Mainpage.js
import axios from 'axios';
import React, {useState} from 'react';
const Mainpage = ()=>{
const [items, setItems] = useState([])
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [id, setID] = useState('');

const getItems = async ()=>{


window.alert('get_items buttion is clicked');
try{
var res = await axios.get('http://localhost:5000/');
setItems(res.data);
}catch(err){
window.alert('An error has occured'+ err);
}
}

const insertItems = async ()=>{


window.alert('insert items button is clicked '+ name + ' hello');
const newItem = {name, description}
try{
const response = await axios.post('http://localhost:5000/', newItem);
}catch(err){
window.alert('An error in put function : '+ err);
}
}

const updateItems = async()=>{


window.alert('update items method is called');
const newItem = {id, name, description};
try{
// const const_req = "http://localhost:5000/name=preethi&description=home_maker";
// const response = await axios.put(const_req);
const response = await axios.put('http://localhost:5000/', newItem);
window.alert('response from server is: ' + response);
}catch(err){
window.alert('An err in the update function : ' + err);
}
}

const deleteItems = async()=>{


window.alert('delete items method is called');
const newItem = {id};
window.alert('delete items method is called'+id+' hello ');
try{
const response = await axios.delete(`http://localhost:5000/${id}`);
window.alert('response from server is: ' + response);
}catch(err){
window.alert('An err in the delete function : ' + err);
}
}

return(
<div>
<h1> Hi! </h1>
<h2> I am in the main page </h2>
<h3> contents </h3>
<h4>{JSON.stringify(items)}</h4>

<button onClick={getItems}>get_details</button>
<div>
<button onClick={insertItems}>insert</button>
<input type='text' id='inserttext' placeholder='name'
onChange={(e)=>setName(e.target.value)} />
<input type='text' id='insert_desc' placeholder='new description'
onChange={(e)=>setDescription(e.target.value)}/>
</div>
<div>
<button onClick={updateItems}> update </button>
<input type="text" id="updatetext" placeholder='name'
onChange={(e)=>setName(e.target.value)}/>
<input type="text" id="update_desc" placeholder = 'new description'
onChange={(e)=>setDescription(e.target.value)}/>
<input type="text" id="update_id" placeholder = 'mention the id'
onChange={(e)=>setID(e.target.value)}/>
</div>
<div>
<button onClick={deleteItems}> delete </button>
<input type="text" id="delete_id" placeholder = 'mention the id'
onChange={(e)=>setID(e.target.value)}/>
</div>
<ul>{items.map(item=>(<li key={item._id}>name: {item.name} - Description:
{item.description}</li>))}</ul>
</div>
);
}

export default Mainpage;

Result:
Thus the to-do maintenance application website using express.js and the react.js
has successfully been completed and the results are verified.
Ex No: 3
Micro Blogging Application
Date:

Aim:
To create a simple micro blogging application (like twitter) that allows people to
post their content which can be viewed by people who follow them

Algorithm:
 Initialize the project with React frontend and Node.js backend, setting up MongoDB for
data storage.
 Define MongoDB collections: users for user profiles, including followers, and posts for
storing user-generated posts.
 Create the Express server, connect it to MongoDB, and set up basic routes.
 Implement user login or creation endpoint to add new users if they don’t already exist.
 Develop a create post endpoint to allow users to submit new posts to the posts
collection.
 Implement a fetch posts endpoint, allowing optional filtering by username to retrieve
posts by specific users.
 Design the frontend components for login, post creation, displaying posts, and handling
follow actions.
 Add a follower feature allowing users to follow each other and update the followers list
in the users collection.
 Use useEffect in React to fetch posts whenever the selected follower changes, calling
the fetch posts endpoint with filtering.
 Add a dropdown menu to select and display posts from specific followed users and all
posts by default

Program:

App.js
import React, { useState, useEffect } from 'react';
const App = () => {
const [username, setUsername] = useState('');
const [userId, setUserId] = useState(null);
const [content, setContent] = useState('');
const [posts, setPosts] = useState([]);
Output:
const [showLogin, setShowLogin] = useState(true);
const [selectedFollower, setSelectedFollower] = useState('');
const [following, setFollowing] = useState([]);
console.log('userId:', userId);
const fetchPosts = async () => {
try {
const response = await fetch('http://localhost:3001/posts');
if (response.status === 500) {
console.error('Failed to retrieve posts');
return
} else {
const data = await response.json();
setPosts(data)
}
} catch (error){
console.error('Error fetching posts:', error);
}
};
useEffect(() => {
fetchPosts();
}, []);
const handleUser = async () => {
try {
const response = await fetch('http://localhost:3001/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username }),
});
const data = await response.json();
setUserId(data._id);
setShowLogin(false);
} catch (error) {
console.error('Error creating or fetching user:', error);
}
};
const handlePost = async () => {
if (userId && content) {
try {
await fetch('http://localhost:3001/post', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username: username, content }),
});
setContent('');
fetchPosts();
} catch (error) {
console.error('Error creating post:', error);
}
}
};
const handleFollow = async (userIdToFollow) => {
try {
const response = await fetch("http://localhost:3001/follow", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
followerusername: username,
userNameToFollow: userIdToFollow,
}),
});
if (response.ok) {
await fetchFollowing();
console.log("User followed successfully");
} else {
console.error("Failed to follow user");
}
} catch (error) {
console.error("Error following user:", error);
}
};
async function fetchFollowing() {
try {
const response = await fetch(`http://localhost:3001/following?userName=${username}`);
const data = await response.json();
setFollowing(data.following); // Assume backend sends an array of usernames
} catch (error) {
console.error('Error fetching following list:', error);
}
}
function handleFilterChange(event) {
setSelectedFollower(event.target.value);
}
useEffect(() => {
async function fetchFilteredPost() {
try {
const response = await fetch(`http://localhost:3001/posts/${username}`);
const data = await response.json();
setPosts(data);
} catch (error) {
console.error('Error fetching filtered posts:', error);
}
}
fetchFilteredPost();
}, [selectedFollower]);
useEffect(() => {
fetchFollowing()
}, [username]);
return (
<div className="min-h-screen bg-gray-100 flex flex-col items-center p-6">
<h2 className="text-3xl font-bold text-blue-600 mb-4">Microblogging App</h2>
{showLogin && (
<div className="w-full max-w-md bg-white shadow-md rounded-lg p-6 mb-6">
<input
type="text"
placeholder="Enter username"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full p-2 border border-gray-300 rounded mt-2 focus:outline-none
focus:ring-2 focus:ring-blue-500"
/>
<button
onClick={handleUser}
className="w-full mt-4 bg-blue-500 text-white py-2 rounded hover:bg-blue-600
transition"
>
Enter
</button>
</div>
)}

{userId && (
<div className="w-full max-w-md bg-white shadow-md rounded-lg p-6 mb-6">
<h3 className="text-lg font-semibold text-gray-700 mb-2">Post Content</h3>
<textarea
placeholder="What's on your mind?"
value={content}
onChange={(e) => setContent(e.target.value)}
className="w-full p-2 border border-gray-300 rounded h-24 focus:outline-none
focus:ring-2 focus:ring-blue-500"
/>
<button
onClick={handlePost}
className="w-full mt-4 bg-green-500 text-white py-2 rounded hover:bg-green-600
transition"
>
Post
</button>
</div>
)}
<div className="w-full max-w-lg bg-white shadow-md rounded-lg p-6 mb-4">
<h3 className="text-lg font-semibold text-gray-700 mb-4">Filter by Following</h3>
<select
value={selectedFollower}
onChange={handleFilterChange}
className="w-full p-2 border border-gray-300 rounded focus:outline-none focus:ring-2
focus:ring-blue-500 mb-4"
>
<option value="">All Posts</option>
{following?.map((follower, index) => (
<option key={index} value={follower}>
{follower}
</option>
))}
</select>
</div>

<div className="w-full max-w-lg bg-white shadow-md rounded-lg p-6">


<h3 className="text-lg font-semibold text-gray-700 mb-4">All Posts</h3>
<ul className="space-y-4">
{posts
.filter((post) => !selectedFollower || post.username === selectedFollower)
.map((post, index) => (
<li key={index} className="p-4 border border-gray-200 rounded bg-gray-50 flex justify-
between items-center">
<div>
<strong className="text-blue-600">{post.username}</strong>:
<p className="text-gray-700">{post.content}</p>
</div>
<button
className="bg-blue-500 text-white px-3 py-1 rounded-lg hover:bg-blue-600"
onClick={() => handleFollow(post.username)}
>
Follow
</button>
</li>
))}
</ul>
</div>
</div>
);
};
export default App;
Server.js

const express = require('express');

const cors = require('cors');

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

const { MongoClient, ObjectId } = require('mongodb');

const app = express();

const PORT = 3001;

app.use(cors());

app.use(bodyParser.json());

let db;

// related to db setup

async function main() {

const uri = 'mongodb://0.0.0.0:27017';

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

try {

await client.connect();

console.log('Connected successfully to MongoDB');

db = client.db('microblog');

} catch (err) {

console.error('Connection failed:', err);

process.exit(1);

}
}

main().catch(console.error);

// related to add new users to the database

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

const { username } = req.body;

try {

let user = await db.collection('users').findOne({ username });

if (!user) {

const result = await db.collection('users').insertOne({

username,

followers: [username],

posts: []

});

user = { _id: result.insertedId, username, followers: [], posts: [] };

res.json(user);

} catch (error) {

res.status(500).json({ error: 'Failed to create or find user' });

});

// related to add new posts to the database

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

const { username, content } = req.body;


try {

console.log('user_id from adding post:', username);

const user = await db.collection('users').findOne({ username });

console.log('user from adding post:', user);

if (user && content) {

const result = await db.collection('posts').insertOne({

user_id: user._id,

username: user.username,

content,

timestamp: new Date()

});

await db.collection('users').updateOne(

{ username: username },

{ $push: { posts: result.insertedId } }

);

res.status(201).json({ _id: result.insertedId, content });

} else {

res.status(400).json({ error: 'User not found or content missing' });

} catch (error) {

res.status(500).json({ error: 'Failed to create post' });

});
// get all the posts

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

try {

const posts = await db.collection('posts').find().sort({ timestamp: -1 }).toArray();

res.json(posts);

} catch (error) {

res.status(500).json({ error: 'Failed to retrieve posts' });

});

// get selected users posts

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

const { username } = req.params;

try {

const posts = await db.collection('posts').find({ username: username }).sort({ timestamp: -1


}).toArray();

res.json(posts || []);

} catch (error) {

res.status(500).json({ error: 'Failed to retrieve user posts' });

);

// update the user's followers

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


const { followerusername, userNameToFollow } = req.body;

try {

if (followerusername === userNameToFollow) {

return res.status(400).json({ error: 'Cannot follow yourself' });

const user = await db.collection('users').findOne({ username: (followerusername) });

const followUser = await db.collection('users').findOne({ username: (userNameToFollow) });

if (user && followUser) {

await db.collection('users').updateOne(

{ username: followerusername },

{ $addToSet: { followers: (userNameToFollow) } }

);

res.json({ message: `You are now following ${followUser.username}` });

} else {

res.status(404).json({ error: 'User not found' });

} catch (error) {

res.status(500).json({ error: 'Failed to follow user' });

});

// get the followers of a user

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

const { userName } = req.query;


try {

const user = await db.collection('users').findOne({ username: userName });

res.json({ following: user.followers || [] });

} catch (error) {

res.status(500).json({ error: 'Failed to retrieve following list' });

});

app.listen(PORT, () => {

console.log(`Server is running on http://localhost:${PORT}`);

});

Result:
The microblogging application is successfully implemented, allowing users to
create posts, follow other users, and filter posts by followed users within a streamlined
interface.
Ex No: 4 Create a food delivery website where users can
order food from a particular restaurant listed in the
Date: website.

Aim:
To create a food delivery website using MERN stack where users can place food
orders for a particular restaurant.

Algorithm:
Required packages: express, cors, body-parser, mongoose packages

Setup MongoDB:

Step 1: Create a database called food_delivery_db


Step 2: Create a collection called items where the food orders will be stored.
Step 3: Insert two sample items as follows
[
{
_id: ObjectId('670f45f8d14746635ec73bf9'),
name: 'Sachin',
phone_no: '99888 99888',
ordered_items: { dosa: '2', chicken: '3', noodles: '2' },
cost: '250',
delivered_status: 'no'
},
{
_id: ObjectId('670f463cd14746635ec73bfa'),
name: 'Ramesh',
phone_no: '77773 87878',
ordered_items: { dosa: '1', chicken: '2', noodles: '1' },
cost: '150',
delivered_status: 'no'
}
]

Setup Express server:


Step 1: import the packages express, cors, body-parser, mongoose
Step 2: create express object and listen to the http client connection at port no. 3000
Step 3: Make provisions for the GET method, POST method for the express server.
Step 4: Using mongoose package, establish connection to food_delivery_db in the MongoDB
Step 5: Setup the schema to perform the CRUD operations as follows.
Output:

Login page:

Place order page:


name: String,
phone_no: String,
ordered_items: Object,
cost: String,
delivered_status: String
Step 6: In the GET Method, retrieve the details in the items table and send them to client
through the response object
Step 7: In the POST Method, recieve the food ordered details from the client and update the
items table in the MongoDB.

Setup React Client:


1. Install axios package
2. Create a Login.js file to show the two options.
(i) User – to place the orders
(ii) Restaurant manager – to view the orders
3. Create a file named Mainpage.js which is used by the restaurant manager to view the
orders from the items table in the food_delivery_db.
Create another file named Orderpage.js to place the order.

Program:
Server side:
Food_delivery_Server.js

const express = require('express'); // step 1: include the server module to the server-side script.
app = express(); // step 2: creating the app as server object

// step 3: make the server object use the objects of cors and body-parser module. It is for
sending the JSON message.
const cors = require('cors');
const bodyParser = require('body-parser');

app.use(cors());
app.use(bodyParser.json());

// MongoDB connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/food_delivery_db')

// Define a schema and model


const itemSchema = new mongoose.Schema({
name: String,
View ordered items
phone_no: String,
cost: String,
delivered_status: String,
});

const Item = mongoose.model('Item', itemSchema);

app.listen(5001, ()=>{
console.log('Server is waiting for connections from the client');
});
// step 4: write the get method to respond to the client.
app.get('/', async (req, res)=>{
try{
const jsobj1 = await Item.find();
res.json(jsobj1);
}catch(err){
res.send('error in the get method of food delivery - server-side code')
}
});

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


const item = new Item({
name: req.body.name,
phone_no: req.body.phoneno,
ordered_items: req.body.ordered_items,
cost: req.body.cost,
delivered_status: req.body.deliveredStatus,

});
console.log('name is: '+ req.body.name);
console.log('phone_no is: ' + req.body.phoneno);
console.log('ordered_items is: ' + req.body.ordered_items);
console.log('cost is: ' + req.body.cost);
console.log('delivered_status is: ' + req.body.deliveredStatus);
console.log('hello');
try{

const jsobj1 = await item.save();


res.status(201).json(jsobj1);
}catch(err){
res.send('error in the post method of server-side code')
console.log('error in server post method');
}
});
app.put('/', async (req, res)=>{
try{
console.log(`received id is:: ${req.body.id}`);
const item = await Item.findById(req.body.id);
console.log('item found in the db' + item);
if(item){
item.name = req.body.name;
item.description = req.body.description;
const updatedItem = await item.save();
res.statuscode(201).json(updatedItem);
}
else{
res.status(404).json({message: 'Item not found'});
}
}catch(err){
res.status(400).json({message: err.message});
}
});

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


try{
console.log(`received id is:: ${req.params.id}`);
const item = await Item.findById(req.params.id);
console.log('item found in the db' + item);
if(item){
const deletedItem = await item.deleteOne();
res.statuscode(201).json(deletedItem);
}
else{
res.status(404).json({message: 'Item not found'});
}
}catch(err){
res.status(400).json({message: err.message});
}
});

Client side:
Loginpage.js
import { useNavigate } from "react-router-dom";

const Login = ()=>{


const navigate = useNavigate();
function handleSubmit() {
window.alert('hi');
navigate('/Mainpage');
}
function handle_order_items(){
window.alert('order items button clicked');
navigate('/Orderpage')
}
return(
<div>
<form onSubmit={handleSubmit}>
<button type='All Orders details'> Click to view - All orders details </button>
</form>
<form onSubmit={handle_order_items}>
<button type='Order items'> Click to view - To place a new order </button>
</form>
</div>
);
}

export default Login;

Mainpage.js

import axios from 'axios';


import React, { useState } from 'react';
import './App.css';

const Mainpage=()=>{
const [items, setItems] = useState([])
const getItems = async ()=>{
window.alert('get_items buttion is clicked');
try{
var res = await axios.get('http://localhost:5001/');
setItems(res.data);
}catch(err){
window.alert('An error has occured'+ err);
}
}

return (
<div className="App">
<h1> Hi! </h1>
{/* <h4>{JSON.stringify(items)}</h4> */}

<button onClick={getItems}>Click here to get the details</button>


<h2> The list of orders received</h2>

<center>{items.map(item=>
<table style={{width: '800px', border: '2px solid green'}}>
<thead>
<td>item_id</td>
<td>name</td>
<td>phone_no</td>
<td>ordered_items</td>
<td>Total_cost</td>
<td>delivered_status</td>
</thead>
<tr>
<td>{item._id}</td>
<td>{item.name}</td>
<td>{item.phone_no}</td>
<td>
<ul>
{JSON.stringify(items.ordered_items)}
</ul>
</td>
<td>{item.cost}</td>
<td>{item.delivered_status}</td>
</tr>

</table>)}</center>
</div>
);
}

export default Mainpage;

Orderpage.js

import axios from 'axios';


import React, { useState } from 'react';
import './App.css';
const Orderpage=()=>{
const [items, setItems] = useState([])
const [name, setName] = useState('');
const [phoneno, setPhoneno] = useState('');

const [id, setID] = useState('');


const [cost, setCost] = useState('');

const [dosa, setDosaCount] = useState('');


const [berger, setBergerCount] = useState('');
const [noodles, setNoodlesCount] = useState('');

// const getItems = async ()=>{


// window.alert('get_items buttion is clicked');
// try{
// var res = await axios.get('http://localhost:5001/');
// setItems(res.data);
// }catch(err){
// window.alert('An error has occured'+ err);
// }
// }

const insertItems = async ()=>{


window.alert('insert items button is clicked '+ name + ' hello');
console.log('name is: ' + name);

window.alert('insert items button is clicked '+ phoneno + ' hello');


window.alert('insert items button is clicked '+ cost + ' hello');

var deliveredStatus = 'no';


window.alert('insert items button is clicked '+ deliveredStatus + ' hello');
var cost = 0;
if (dosa != null) cost = cost + 60*Number(dosa);
if (berger != null) cost = cost + 50*Number(berger);
if (noodles != null) cost = cost + 80*Number(noodles);
var ordered_items = {Dosa: dosa, Berger: berger, Noodles: noodles};
const newItem = {name, phoneno, ordered_items, cost, deliveredStatus};
try{
const response = await axios.post('http://localhost:5001/', newItem);
}catch(err){
window.alert('An error in put function : '+ err);
}
}
return (
<div className="App">
<h1> Hi! </h1>
<h2> Food Ordering Page </h2>
{/* <h4>{JSON.stringify(items)}</h4> */}

{/* <button onClick={getItems}>get_details</button> */}


<div>
<h3>Dosa: 60Rs.</h3>
<h3>Berger: 50Rs.</h3>
<h3>Noodles: 80Rs.</h3>

<button onClick={insertItems}>insert</button>
<input type='text' id='inserttext' placeholder='name'
onChange={(e)=>setName(e.target.value)} />
<input type='text' id='insert_phoneno' placeholder='phone no...'
onChange={(e)=>setPhoneno(e.target.value)}/>
<input type='text' id='insert_dosa' placeholder='dosa - enter count'
onChange={(e)=>setDosaCount(e.target.value)}/>
<input type='text' id='insert_berger' placeholder='berger - enter count'
onChange={(e)=>setBergerCount(e.target.value)}/>
<input type='text' id='insert_noodles' placeholder='noodles - enter count'
onChange={(e)=>setNoodlesCount(e.target.value)}/>
</div>

{/* <ul>{items.map(item=>(<li key={item._id}>name: {item.name}, phone_no:


{item.phone_no}, Total_cost: {item.cost}, delivered_status: {item.delivered_status}</li>))}</ul>
{items.map(item=>
<table style={{width: '800px', border: '2px solid green'}}>
<thead>
<td>item_id</td>
<td>name</td>
<td>phone_no</td>
<td>ordered_items</td>
<td>Total_cost</td>
<td>delivered_status</td>
</thead>
<tr>
<td>{item._id}</td>
<td>{item.name}</td>
<td>{item.phone_no}</td>
<td>
<ul>
{JSON.stringify(items.ordered_items)}
</ul>
</td>
<td>{item.cost}</td>
<td>{item.delivered_status}</td>
</tr>

</table>)} */}
</div>
);
}

export default Orderpage;

Result:
Thus the food ordering website using react.js has successfully been completed.
Ex No: 5 Develop a classifieds web application to buy and
sell used products
Date:

Aim:
To Develop a Classified web application to buy and sell used products

Algorithm:

Backend (Server-side) Algorithm:

1. Set up MongoDB and connect using Mongoose to manage product data.


2. Create a Mongoose schema for the Product model with fields: title, description, and
price.
3. Define API routes:
o GET /api/products: Fetch all products from the database.
o POST /api/products: Create a new product and save to the database.
o GET /api/products/:id: Fetch a single product by ID.
o PUT /api/products/:id: Update an existing product by ID.
o DELETE /api/products/:id: Delete a product by ID.
4. Set up Express server to handle incoming requests on a specified port.
5. Test the API routes using tools like Postman to ensure data is being handled correctly.

Frontend (Client-side) Algorithm:

1. Initialize React app using Create React App and install required libraries (react-router-
dom, axios).
2. Set up React Router for routing between the HomePage and CreateProductPage
components.
3. Use useState to manage the state for product listings and form data (title, description,
price).
4. Use axios to send:
o GET request to /api/products to fetch product data.
o POST request to /api/products to create new products.
5. Display the fetched products on the HomePage in a grid layout.
6. Implement a form on CreateProductPage to capture title, description, and price inputs.
Output:
Program:

Server Side

Server.js

const express = require('express');

const mongoose = require('mongoose');

const cors = require('cors');

const dotenv = require('dotenv');

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

const app = express();

dotenv.config();

app.use(express.json());

app.use(cors());

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

// Connect to MongoDB

Const MONGO_URI =
"mongodb+srv://admin:paswordadmin@cluster0.bkkmn.mongodb.net/Product"

mongoose.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })

.then(() => console.log('MongoDB Connected'))

.catch(err => console.log(err));

// MongoDB Models

// Product Model

const Product = mongoose.model('Product', new mongoose.Schema({

title: { type: String, required: true },


description: { type: String, required: true },

price: { type: Number, required: true },

createdAt: { type: Date, default: Date.now }

}));

// Routes

// Create Product Listing (No authentication required)

app.post('/api/products', async (req, res) => {

const { title, description, price } = req.body;

try {

const newProduct = new Product({

title,

description,

price

});

await newProduct.save();

res.status(201).json({ message: 'Product created', product: newProduct });

} catch (err) {

res.status(500).json({ message: 'Error creating product' });

});

// Get All Products

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

try {
const products = await Product.find();

res.json(products);

} catch (err) {

res.status(500).json({ message: 'Error fetching products' });

});

// Get Single Product Details

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

const productId = req.params.id;

try {

const product = await Product.findById(productId);

if (!product) return res.status(404).json({ message: 'Product not found' });

res.json(product);

} catch (err) {

res.status(500).json({ message: 'Error fetching product details' });

});

// Update Product Listing (No authentication required)

app.put('/api/products/:id', async (req, res) => {

const productId = req.params.id;

const { title, description, price } = req.body;

try {

const product = await Product.findById(productId);


if (!product) return res.status(404).json({ message: 'Product not found' });

product.title = title;

product.description = description;

product.price = price;

await product.save();

res.json({ message: 'Product updated', product });

} catch (err) {

res.status(500).json({ message: 'Error updating product' });

});

// Delete Product Listing (No authentication required)

app.delete('/api/products/:id', async (req, res) => {

const productId = req.params.id;

try {

const product = await Product.findById(productId);

if (!product) return res.status(404).json({ message: 'Product not found' });

await product.remove();

res.json({ message: 'Product deleted' });

} catch (err) {

res.status(500).json({ message: 'Error deleting product' });

});
// Start Server

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {

console.log(`Server running on port ${PORT}`);

});

Client Side

App.js:

// src/App.js

import React from 'react';

import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';

import HomePage from './pages/HomePage.js';

import CreateProductPage from './pages/CreateProductPage.js';

import Navbar from './components/Navbar';

import './App.css';

function App() {

return (

<Router>

<Navbar />

<div className="container">

<Routes>

<Route path="/" element={<HomePage />} />


<Route path="/create" element={<CreateProductPage />} />

</Routes>

</div>

</Router>

);

export default App;

HomePage.js:

// src/pages/HomePage.js

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

import axios from 'axios';

import './HomePage.css'

function HomePage() {

const [products, setProducts] = useState([]);

useEffect(() => {

axios.get('http://localhost:5000/api/products')

.then(response => setProducts(response.data))

.catch(error => console.error(error));

}, []);
return (

<div>

<h1>Classifieds</h1>

<div className="products">

{products.map(product => (

<div className="product" key={product._id}>

<h3>{product.title}</h3>

<p>{product.description}</p>

<p><strong>₹{product.price}</strong></p>

</div>

))}

</div>

</div>

);

export default HomePage;

CreateProductPage.js:

// src/pages/CreateProductPage.js

import React, { useState } from 'react';

import axios from 'axios';

import { useNavigate } from 'react-router-dom';


import './CreateProductPage.css'

function CreateProductPage() {

const [title, setTitle] = useState('');

const [description, setDescription] = useState('');

const [price, setPrice] = useState('');

const navigate = useNavigate();

const handleSubmit = async (e) => {

e.preventDefault();

try {

await axios.post('http://localhost:5000/api/products', { title, description, price });

navigate('/'); // Redirect to homepage after product creation

} catch (error) {

console.error('Error creating product:', error);

};

return (

<div>

<h2>Create Product Listing</h2>

<form onSubmit={handleSubmit}>

<input
type="text"

placeholder="Title"

value={title}

onChange={(e) => setTitle(e.target.value)}

required

/>

<textarea

placeholder="Description"

value={description}

onChange={(e) => setDescription(e.target.value)}

required

/>

<input

type="number"

placeholder="Price"

value={price}

onChange={(e) => setPrice(e.target.value)}

required

/>

<button type="submit">Create Listing</button>

</form>

</div>

);
}

export default CreateProductPage;

Navbar.js:

// src/components/Navbar.js

import React from 'react';

import { Link } from 'react-router-dom';

import './Navbar.css'

function Navbar() {

return (

<nav className="navbar">

<div className="container">

<Link to="/" className="logo">Classifieds</Link>

<ul>

<li><Link to="/create">Create Listing</Link></li>

</ul>

</div>

</nav>

);

}
export default Navbar;

StyleSheet

App.css:

/* src/App.css */

body {

font-family: 'Arial', sans-serif;

margin: 0;

padding: 0;

background-color: #f4f4f9;

.container {

max-width: 1200px;

margin: 0 auto;

padding: 20px;

h1, h2 {

color: #333;

button {
background-color: #007bff;

color: white;

border: none;

padding: 10px 20px;

cursor: pointer;

border-radius: 5px;

button:hover {

background-color: #0056b3;

input, textarea {

padding: 10px;

border-radius: 5px;

border: 1px solid #ccc;

width: 100%;

margin-bottom: 15px;

input:focus, textarea:focus {

outline: none;

border-color: #007bff;
}

form {

max-width: 600px;

margin: 0 auto;

padding: 20px;

background-color: #fff;

border-radius: 8px;

box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);

.products {

display: grid;

grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));

gap: 20px;

margin-top: 20px;

.product {

background-color: #fff;

padding: 20px;

border-radius: 8px;

box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);


text-align: center;

.product h3 {

font-size: 1.2em;

margin-bottom: 10px;

.product p {

color: #555;

.product strong {

font-size: 1.5em;

color: #007bff;

HomePage.css:

/* src/pages/HomePage.css */

h1 {

text-align: center;

color: #333;

font-size: 2.5em;
margin-bottom: 20px;

.products {

display: grid;

grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));

gap: 20px;

margin-top: 20px;

.product {

background-color: #fff;

padding: 20px;

border-radius: 8px;

box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);

text-align: center;

.product h3 {

font-size: 1.2em;

margin-bottom: 10px;

}
.product p {

color: #555;

.product strong {

font-size: 1.5em;

color: #007bff;

CreateProductPage.css:

/* src/pages/CreateProductPage.css */

h2 {

text-align: center;

margin-bottom: 20px;

form {

max-width: 600px;

margin: 0 auto;

padding: 20px;

background-color: #fff;

border-radius: 8px;

box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);


}

form input,

form textarea {

margin-bottom: 15px;

form button {

width: 100%;

padding: 15px;

Navbar.css:

/* src/components/Navbar.css */

.navbar {

background-color: #343a40;

padding: 15px 0;

color: white;

.navbar .container {

display: flex;

justify-content: space-between;
align-items: center;

.navbar .logo {

font-size: 1.5em;

font-weight: bold;

color: #ffffff;

text-decoration: none;

.navbar ul {

list-style-type: none;

margin: 0;

padding: 0;

display: flex;

.navbar ul li {

margin: 0 15px;

.navbar ul li a {

color: white;
text-decoration: none;

.navbar ul li a:hover {

text-decoration: underline;

.navbar ul li button {

background-color: transparent;

color: white;

border: none;

cursor: pointer;

.navbar ul li button:hover {

text-decoration: underline;

Result:
The Classifieds Web Application allows users to view and create product listings, with data
stored in MongoDB and served through a RESTful API using Express. The frontend, built with React,
allows users to interact with the product data via a responsive UI, making use of Axios for HTTP requests
and React Router for navigation.
Develop a leave management system for an organization
Ex No: 6 where users can apply different types of leaves such as casual
Date: leave and medical leave. They can also view the available no.
of days.

Aim:
To develop a leave management system for an organization to allow users to
apply for leaves and to view the remaining view leave details. (Assume available CL = 12 per
year, ML = 240 for the entire service)

Algorithm:
Required packages: express, cors, body-parser, mongoose packages

Setup MongoDB:

Step 1: Install MongoDB and check whether it is available at port no. 27017.
Step 2: The database created by the server is: exp5_db
The total leave count details of all the employees are maintained in
the table Leaves_count_col1. It structure is

The leave applied leave details are maintained in the table


Leaves_count_col1. It structure is
Output:

Login page:

Create_user page:

Before registering a user into the MongoDB database. The database is empty

After enter a user named Azharuddin in the Create_user page


Setup Express server:
Step 1: import the packages express, cors, body-parser, mongoose
Step 2: create express object and listen to the http client connection at port no. 3000
Step 3: Make provisions for the GET method, POST method for the express server.
Step 4: Using MongoClient package, establish connection to exp5_db in the
MongoDB. This package is used for the insertion (post) operations.
The API are used for the following purposes.
To create a new user:
app.post('/create_user', (req,res)=>{ …}

To update the leave details in both the collections:


app.post('/update_user', (req,res)=>{ …}

Step 5: Using Mongoose package, establish connection to exp5_db in the


MongoDB. This package is used for the get operations.
The API are used for the following purposes.

To get the leave count of all the employees:


app.get('/admin_view_leaves_count', async (req, res)=>{ …}

To get the leave applied details of all the employees:


app.get('/admin_view_leaves_detail', async (req, res)=>{ …}

To get the leave count of a particular employee:


app.get('/user_view_leaves_count', async (req, res)=>{ …}
The database also reflects one entry.

Update_user page

The DB shows that, no entry is made in the leaves_detail_col1 collection for Azharuddin.
In leaves_count_col1 collection, Azhauddin has applied no leave.
To get the leave applied details of a particular employee:
app.get('/user_view_leaves_detail', async (req, res)=>{ …}

Setup React Client:


1. Install axios package

2. Create a Login.js file to show the two options.


(i) Create user
(ii) Update user
(iii) HR – to view details of all the employees
(iv) View remaining details of one employee

3. Create a file Create_user.js file to get the following details.


(i) Employee id
(ii) Employee name
(iii) Employee designation
And enter these details to the leave_count_col1 collection in the exp5_db of MongoDB.

4. Create a file Update_user.js file to get the following details.


(i) Employee id
(ii) Leave type (CL or ML)
(iii) Leave count applied now
(iv) from the date
(v) to the date
And update these details to the leave_count_col1 collection for the employee in the
exp5_db of MongoDB. And add a new row for this leave applied in the collection
leaves_detail_col1 in the exp5_db of MongoDB.

5. Create a file Admin_view_leaves.js file to get the following details.


(i) To show total leave details of all the employees in the organization (from the
collection leave_count_col1)
(ii) To show details of the leaves applied by all the employees
(from the collection leave_detail_col1)

6. Create a file User_view_leaves.js file to get the following details.


(i) Get the employee id from the user
(iii) For the employee id, show the total leave details (from the collection
leave_count_col1)
(iv) For the employee id, show details of the leaves applied (from the collection
leave_detail_col1)
Go to the page Update user page and submit leave for Azharuddin.
Program:
Server side:
Leave_management_server.js
const express = require('express');
const app = express();
app.listen('4000', ()=>{
console.log('The server is waiting.');
});

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

const cors = require('cors');


app.use(cors());

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


app.use(bodyParser.json());

/*
input : emp_id, emp_name, emp_designation
output: Insert new document in the leave_count_details (create a user entry to count his leave
details in the furture)
*/

app.post('/create_user', (req,res)=>{
fn_create_user(req.body.emp_id, req.body.emp_name, req.body.emp_designation);
res.write('A new employee is inserted into the database successfully');
res.end();
});

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


const client = new MongoClient('mongodb://localhost:27017');

const fn_create_user = async(id, name, designation)=>{


try{
const database = client.db('exp5_db');
const collection = database.collection('leaves_count_col1');
const result = await collection.insertOne({emp_id: id, emp_name: name, emp_designation:
designation, casual_leave: Number(0), medical_leave: Number(0)});
}finally{
console.log('Emp -inserted');
}
}
The DB reflects the same entries in both the tables.
/*
input : emp_id, leave_type (CL or ML), count ( a number)
output: For the emp_id, update the document in the leave_count_details (leave_type if cl
means = old count + new count, ml means = old count + new count)
*/
app.post('/update_user', (req,res)=>{
fn_update_user(req.body.emp_id, req.body.leave_type, req.body.count);
fn_update_user_leaves(req.body.emp_id, req.body.leave_type, req.body.count,
req.body.from_date, req.body.to_date);
res.write('Details updated successfully');
res.end();
});

const fn_update_user = async(id, leave_type, count)=>{


try{
const database = client.db('exp5_db');
const collection = database.collection('leaves_count_col1');
//const result = await collection.insertOne({emp_id: id, emp_name: name,
emp_designation: designation, casual_leave: 0, medical_leave: 0});
if(leave_type == 'CL'){
//const result = await collection.updateOne({emp_id: id},{$set: {casual_leave:
count}},{upsert: true});
const result = await collection.updateOne({emp_id: id},{$inc: {casual_leave:
Number(count)}},{upsert: true});
}
if(leave_type == 'ML'){
const result = await collection.updateOne({emp_id: id},{$set: {medical_leave:
count}},{upsert: true});
}
}finally{
console.log('Emp -updated');
}
}

const fn_update_user_leaves = async(id, lt, cnt, from, to)=>{


console.log('hello');
try{
const database = client.db('exp5_db');
const collection = database.collection('leaves_detail_col1');
const result = await collection.insertOne({emp_id: id, leave_type: lt, count: cnt, from_date:
from, to_date: to});

}finally{
console.log('Leave details - added');
Admin_view_leaves page:

Thunder Client get request


}
}

// MongoDB connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/exp5_db')

// Define a schema and model


const itemSchema = new mongoose.Schema({
emp_id: String,
emp_name: String,
emp_designation: String,
casual_leave: Number,
medical_leave: Number,
});

const Item = mongoose.model('leaves_count_col1', itemSchema);


app.get('/admin_view_leaves_count', async (req, res)=>{
try{
const jsobj1 = await Item.find();
res.json(jsobj1);
}catch(err){
res.send('error in the get method of the leave request')
}
res.end();
});

const Item2 = mongoose.model('leaves_detail_col1', itemSchema);


app.get('/admin_view_leaves_detail', async (req, res)=>{
try{
const jsobj1 = await Item2.find();
res.json(jsobj1);
}catch(err){
res.send('error in the get method of the leave request for the leave details')
}
res.end();
});

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


console.log('A client request received - user leaves count');
try{
const jsobj1 = await Item.find({emp_id: req.body.user_emp_id});
res.json(jsobj1);
React client get request

Admin_view_leaves page:

Thunder client output:


console.log(jsobj1);
}catch(err){
res.send('user - get method error - leaves count')
}
res.end();
});
app.post('/user_view_leaves_detail', async (req, res)=>{
console.log('A client request received - user leaves details');
try{
const jsobj1 = await Item2.find({emp_id: req.body.user_emp_id});
res.json(jsobj1);
console.log(jsobj1);
}catch(err){
res.send('user - get method error - leave details')
}
res.end();
});

Client side:
Loginpage.js
import { useNavigate } from "react-router-dom";

const Login = ()=>{


const navigate = useNavigate();

function handleSubmit() {
window.alert('hi');
navigate('/Mainpage');
}
function handle_order_items(){
window.alert('order items button clicked');
navigate('/Orderpage')
}
return(
<div>
<form onSubmit={handleSubmit}>
<button type='All Orders details'> Click to view - All orders details </button>
</form>
<form onSubmit={handle_order_items}>
<button type='Order items'> Click to view - To place a new order </button>
</form>
</div>
);
React client get request

User_view_leaves page:
}

export default Login;

Create_user.js
import axios from 'axios';
import React, { useState } from 'react';
import './App.css';

const Create_user=()=>{
//const [items, setItems] = useState([])
const [emp_id, setId] = useState('');
const [emp_name, setName] = useState('');
const [emp_designation, setDesignation] = useState('');

const insertItems = async ()=>{


const newItem = {emp_id, emp_name, emp_designation};
try{
const response = await axios.post('http://localhost:4000/create_user', newItem);
document.getElementById('id1').innerHTML = response.data;
}catch(err){
window.alert('An error in insert user function : '+ err);
}
}

return (
<div className="App">
<h1> Hi! </h1>
<h2> User creation page </h2>
{/* <h4>{JSON.stringify(items)}</h4> */}

{/* <button onClick={getItems}>get_details</button> */}


<div style={{display: 'block'}}>

<input type='text' placeholder='id' onChange={(e)=>setId(e.target.value)} />


<input type='text' placeholder='name' onChange={(e)=>setName(e.target.value)} />
<input type='text' placeholder='designation'
onChange={(e)=>setDesignation(e.target.value)}/>
<button onClick={insertItems}>insert</button>

<h3 id='id1'> </h3>


</div>

</div>
);
}

export default Create_user;

Update_user.js
import axios from 'axios';
import React, { useState } from 'react';
import './App.css';

const Update_user=()=>{
//const [items, setItems] = useState([])
const [emp_id, setId] = useState('');
const [leave_type, setLeavetype] = useState('');
const [count, setLeavecount] = useState('');
const [from_date, setFromdate] = useState('');
const [to_date, setTodate] = useState('');

const updateItems = async ()=>{


const newItem = {emp_id, leave_type, count, from_date, to_date};
try{
const response = await axios.post('http://localhost:4000/update_user', newItem);
document.getElementById('id1').innerHTML = response.data;
}catch(err){
window.alert('An error in the update user function : '+ err);
}
}

return (
<div className="App">
<h1> Hi! </h1>
<h2> Leave update page </h2>

<div style={{display: 'block'}}>

<input type='text' placeholder='id' onChange={(e)=>setId(e.target.value)} />


<input type='text' placeholder='leave_type - type it as EL or ML'
onChange={(e)=>setLeavetype(e.target.value)} />
<input type='text' placeholder='count'
onChange={(e)=>setLeavecount(e.target.value)}/>
<input type='text' placeholder='From date'
onChange={(e)=>setFromdate(e.target.value)}/>
<input type='text' placeholder='To date' onChange={(e)=>setTodate(e.target.value)}/>
<button onClick={updateItems}>Update </button>
<h3 id='id1'> </h3>
</div>
</div>
);
}

export default Update_user;

Admin_view_leaves.js
import axios from 'axios';
import React, { useState } from 'react';
import './App.css';

const Admin_view_leaves=()=>{
const [items_all_leaves, setItems] = useState([])
const [items_leave_details, setLeaveDetails] = useState([])

const getItems = async ()=>{


window.alert('get_items buttion is clicked');
try{
var res = await axios.get('http://localhost:4000/admin_view_leaves_count');
setItems(res.data);
}catch(err){
window.alert('An error has occured'+ err);
}
}

const get_leave_details = async ()=>{


window.alert('get_leave_details buttion is clicked');
try{
var res = await axios.get('http://localhost:4000/admin_view_leaves_detail');
setLeaveDetails(res.data);
}catch(err){
window.alert('An error has occured'+ err);
}
}

return (
<div className="App">
<h1> Hi! </h1>
{/* <h4>{JSON.stringify(items)}</h4> */}

<button onClick={getItems}> View all employees - leave count details </button>

{/* <ul>{items.map(item=>(<li key={item._id}>name: {item.name}, phone_no:


{item.phone_no}, Total_cost: {item.cost}, delivered_status: {item.delivered_status}</li>))}</ul>
*/}
<h2> Leave details of all the employees </h2>

<center>{items_all_leaves.map(item=>
<table style={{width: '800px', border: '2px solid green'}}>
<thead>
<td>emp_id</td>
<td>emp_name</td>
<td>emp_designation</td>
<td>CL</td>
<td>ML</td>
</thead>
<tr>
<td>{item.emp_id}</td>
<td>{item.emp_name}</td>
<td>{item.emp_designation}</td>
<td>{item.casual_leave}</td>
<td>{item.medical_leave}</td>
</tr>

</table>)}</center>

<h2> Leave details of all the employees - leave type, from date, to date </h2>
<button onClick={get_leave_details}> View all employees - leave type details </button>

<center>{items_leave_details.map(item=>
<table style={{width: '800px', border: '2px solid green'}}>
<thead>
<td>emp_id</td>
<td>leave_type</td>
<td>count</td>
<td>from_date</td>
<td>to_date</td>
</thead>
<tr>
<td>{item.emp_id}</td>
<td>{item.leave_type}</td>
<td>{item.count}</td>
<td>{item.from_date}</td>
<td>{item.to_date}</td>
</tr>

</table>)}</center>
</div>
);
}

export default Admin_view_leaves;

User_view_leaves.js
import axios from 'axios';
import React, { useState } from 'react';
import './App.css';

const User_view_leaves=()=>{
const [items_all_leaves, setItems] = useState([])
const [items_leave_details, setLeaveDetails] = useState([])
const [user_emp_id, setUserempid] = useState('');

const getItems = async ()=>{


const new_item = {user_emp_id}
window.alert('get_items buttion is clicked');
try{
var res = await axios.post('http://localhost:4000/user_view_leaves_count', new_item);
setItems(res.data);
}catch(err){
window.alert('An error has occured'+ err);
}
}

const get_leave_details = async ()=>{


const new_item = {user_emp_id}
window.alert('get_leave_details buttion is clicked');
try{
var res = await axios.post('http://localhost:4000/user_view_leaves_detail', new_item);
setLeaveDetails(res.data);
}catch(err){
window.alert('An error has occured'+ err);
}
}
return (
<div className="App">
<h1> Hi! </h1>
{/* <h4>{JSON.stringify(items)}</h4> */}
<input type='text' placeholder='id' onChange={(e)=>setUserempid(e.target.value)} />
<button onClick={getItems}> View this employee's - leave count details </button>

{/* <ul>{items.map(item=>(<li key={item._id}>name: {item.name}, phone_no:


{item.phone_no}, Total_cost: {item.cost}, delivered_status: {item.delivered_status}</li>))}</ul>
*/}
<h2> Leave details of the employees </h2>

<center>{items_all_leaves.map(item=>
<table style={{width: '800px', border: '2px solid green'}}>
<thead>
<td>emp_id</td>
<td>emp_name</td>
<td>emp_designation</td>
<td>CL</td>
<td>ML</td>
</thead>
<tr>
<td>{item.emp_id}</td>
<td>{item.emp_name}</td>
<td>{item.emp_designation}</td>
<td>{item.casual_leave}</td>
<td>{item.medical_leave}</td>
</tr>

</table>)}</center>

<h2> Leave details of all the employees - leave type, from date, to date </h2>
<button onClick={get_leave_details}> View all employees - leave type details </button>

<center>{items_leave_details.map(item=>
<table style={{width: '800px', border: '2px solid green'}}>
<thead>
<td>emp_id</td>
<td>leave_type</td>
<td>count</td>
<td>from_date</td>
<td>to_date</td>
</thead>
<tr>
<td>{item.emp_id}</td>
<td>{item.leave_type}</td>
<td>{item.count}</td>
<td>{item.from_date}</td>
<td>{item.to_date}</td>
</tr>

</table>)}</center>
</div>
);
}

export default User_view_leaves;

Result:
Thus the leave management system using react.js has successfully been completed.
Develop a simple dashboard for the project management
Ex No: 7 where the statuses of various tasks are available. New
Date: tasks can be added and the status of existing tasks can be
changed among Pending, InProgress or Completed.

Aim:
To develop a project management dashboard with the following facilities
(i) Add new task
(ii) View the status of existing tasks
(iii) Update an existing task

Algorithm:

Required packages: express, cors, body-parser, mongodb (for database) packages

Setup MongoDB:

Step 1: Install MongoDB and check whether it is available at port no. 27017.
Step 2: The database created by the server is: exp6_db
The task details of all the tasks in the project are maintained in
the table tasks_col1. It structure is
Output:

Run the server program

View_task page:

Update_task.page:
Setup Express server:
Step 1: import the packages express, cors, body-parser, mongoose
Step 2: create express object and listen to the http client connection at port no. 5000
Step 3: Make provisions for the GET method, POST method for the express server.
Step 4: Using MongoClient package, establish connection to exp6_db in the
MongoDB. This package is used for the insertion (post) operations.
The API are used for the following purposes.
To create a new task:
app.post('/add_new_task, (req,res)=>{ …}

To update an new task:


app.post('/update_a_task, (req,res)=>{ …}

To view all the existing tasks of a given project:


app.post('/ tasks_view, (req,res)=>{ …}

Setup React Client:


1. Install axios package which will act as the http client to send http requests to the
express server

2. Setup routing in the App.js file to provide support for the following operations.
(i) Add a new task to the existing project.
(ii) Update an existing task
(iii) To view details of all the present tasks

3. Create a file Add_task.js file to get the following details.


(i) task id
(ii) task name
And enter these details to the tasks_col1 collection in the exp6_db of MongoDB.

4. Create a file Update_task.js file to get the following details.


(i) task id
(ii) task status
And update these details to the tasks_col1 collection in the exp6_db of MongoDB..

5. Create a file view_task.js file to get the following details of all the tasks.
(i) task id
(ii) task name
(iii) task status
Add_task.page:

MongoDB database:
Program:
Server Side
ProjectMgmtServer1.js

// step 1,2 - install using npm install express and import express server using require method.

const express = require('express');

// step 3 - create an instance for the express server

const app = express();

// step 4 - make app server object listen at a server port

app.listen(5000, ()=>{

console.log('Server is waiting atport no: 5000.');

});

// step 5 - install cors, body-parser package using npm install cors, body-parser and import
them here.

// Also, make app server object use these objects.

const cors = require('cors');

app.use(cors());

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

app.use(bodyParser.json());

// step 6 - provide support for getting form parameters encoded in the url.

app.use(express.json());

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

// step 7 - install mongodb and import it to use it in the three API's we use now.

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


// create an object for hte MongoClient class to access the mongodb database using the
mongodb package.

const client = new MongoClient('mongodb://localhost:27017/');

// Step - 8 - We connect to this database.

// If it doesn't exist, it is created newly.

// Else, we are just connecting to it.

const database = client.db('exp6_db');

/*

input : task_id, task_name

output: Insert new document in the tasks_col1 collection (in the exp6_db database)

*/

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

fn_create_task(req.body.task_id, req.body.task_name);

// task_status is added default as inprogress. So, we don't receive that as a param from the
client (i.e. from the front-end).

res.write('A new task is inserted into the database successfully');

res.end();

});

const fn_create_task = async(id, name, status)=>{

try{

//const database = client.db('exp5_db');

const collection = database.collection('tasks_col1');

const result = await collection.insertOne({task_id: id, task_name: name, task_status:


'InProgress'});
}finally{

console.log('new task - has been inserted into the tasks_col1 database');

/*

input : no params

output: return json object - statuses of the different tasks of the proj.

*/

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

fn_view_tasks();

const data = await fn_view_tasks();

res.json(data);

console.log('Tasks list - returned from the API to the client');

res.end();

});

const fn_view_tasks = async()=>{

try{

//const database = client.db('exp5_db');

const collection = database.collection('tasks_col1');

const result = await collection.find();

console.log('results is: ', result);

return result.toArray();

}finally{
console.log('details - of tasks returned to api method.');

/*

input : no params

output: return json object - statuses of the different tasks of the proj.

*/

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

console.log('task update request - received from the client');

fn_update_a_task();

const data = await fn_update_a_task(req.body.task_id, req.body.task_status);

res.json(data);

console.log('Task updated');

res.end();

});

const fn_update_a_task = async(id, task_stat)=>{

try{

const collection = database.collection('tasks_col1');

const result = await collection.updateOne({task_id: id},{$set:{task_status: task_stat}});

console.log('update operation - result is: ', result);

if (result == null){

console.log('Updated failed');

}
else{

console.log('Update successful');

}finally{

console.log('details - of tasks returned to api method.');

Client Side

Add_task.js

import axios from 'axios';

import React, { useState } from 'react';

import './App.css';

const Add_task=()=>{

//const [items, setItems] = useState([])

const [task_id, setId] = useState('');

const [task_name, setName] = useState('');

const insertItems = async ()=>{

const newItem = {task_id, task_name};

try{

const response = await axios.post('http://localhost:5000/add_new_task', newItem);

document.getElementById('id1').innerHTML = response.data;

}catch(err){
window.alert('An error in insert user function : '+ err);

return (

<div className="App">

<h1> Hi! </h1>

<h2> Task creation page </h2>

{/* <h4>{JSON.stringify(items)}</h4> */}

{/* <button onClick={getItems}>get_details</button> */}

<div style={{display: 'block'}}>

<input type='text' placeholder='task_id' onChange={(e)=>setId(e.target.value)} />

<input type='text' placeholder='task_name' onChange={(e)=>setName(e.target.value)} />

<button onClick={insertItems}>insert</button>

<h3 id='id1'> </h3>

</div>

</div>

);

export default Add_task;

Update_task.js

import axios from 'axios';


import React, { useState } from 'react';

import './App.css';

const Update_task=()=>{

//const [items, setItems] = useState([])

const [task_id, setId] = useState('');

const [task_status, setTaskStatus] = useState('');

const updateItems = async ()=>{

const newItem = {task_id, task_status};

try{

const response = await axios.post('http://localhost:5000/update_a_task', newItem);

document.getElementById('id1').innerHTML = response.data;

}catch(err){

window.alert('An error in the update user function : '+ err);

return (

<div className="App">

<h1> Hi! </h1>

<h2> Tasks update page </h2>

<div style={{display: 'block'}}>

<input type='text' placeholder='id' onChange={(e)=>setId(e.target.value)} />

<input type='text' placeholder='new task status' onChange={(e)=>setTaskStatus(e.target.value)}


/>
<button onClick={updateItems}>Update </button>

<h3 id='id1'> </h3>

</div>

</div>

);

export default Update_task;

View_task.js

import logo from './logo.svg';

import './App.css';

import axios from 'axios';

import React, { useState } from 'react';

function View_task() {

const [items, setItems] = useState([]);

const fetch_data = async ()=>{

try{

const response = await axios.get('http://localhost:5000/tasks_view');

document.getElementById('id1').innerHTML = response.data;

setItems(response.data);

}catch(err){

window.alert('An error in insert user function : '+ err);

}
}

return (

<div className="App">

<h2> Project status view page </h2>

{/* <h4>{JSON.stringify(items)}</h4> */}

<button onClick={fetch_data}> Submit </button>

<p id='id1'> </p>

<center>

<table style={{width: '800px', border: '2px solid green'}}>

<thead>

<td>task_id</td>

<td>task_name</td>

<td>task_status</td>

</thead>

{items.map(item=>

<tr>

<td>{item.task_id}</td>

<td>{item.task_name}</td>

<td>{item.task_status}</td>

</tr>

)}

</table>

</center>
</div>

);

export default View_task;

App.js

import logo from './logo.svg';

import './App.css';

import axios from 'axios';

import { Route, BrowserRouter as Router, Routes } from 'react-router-dom';

import View_task from './View_task';

import Add_task from './Add_task';

import Update_task from './Update_task.js';

function App() {

return (

<div className="App">

<Router>

<Routes>

<Route path="/" element= {<View_task />} />

<Route path="/add_new_task" element= {<Add_task />} />

<Route path="/tasks_view" element= {<View_task />} />

<Route path="/task_update" element= {<Update_task />} />

</Routes>
</Router>

</div>

);

export default App;

Result:
Thus the project management system using react.js and the express server has
successfully been completed.
Develop an online survey application where a
Ex No: 8
collection of questions is available and users are
Date: asked to answer any random 5 questions.

Aim:
To develop an online survey to provide the following facilities
(i) A user answers 5 questions randomly generated from the server.
(ii) Award marks once the questions are answered.

Algorithm:
Required packages: express, cors, body-parser, mongodb (for database) packages

Setup MongoDB:

Step 1: Install MongoDB and check whether it is available at port no. 27017.
Step 2: The MongoDB database created by the server is: exp7_db
The questions are maintained in the table named ‘test’.
Output:

Run the server program


Setup Express server:
Step 1: import the packages express, cors, body-parser, mongoose
Step 2: create express object and listen to the http client connection at port no. 5000
Step 3: Make provisions for the GET() method in the express server.
Using MongoClient package, establish connection to exp7_db in the
MongoDB. This package is used for retrieving the randomly selected 5
App.js client webpage:

After clicking the submit button, we get the questions.


questions from the MongoDB database.
The API is used for the following purposes.
app.get('/getData',async (req, res) => {…}

Setup React Client:


1. Install axios package which will act as the http client to send http requests to the
express server

2. Add the get method in the App.js file to get the following details for 5 questions from
the backend express server.

(i) Question name with yes or no option

Also, the answers to the questions are received. Once the user answers all the questions,
user has to click the Calculate result button which will produce the final marks.

Program:

Server Side

server1.js
const {MongoClient} = require('mongodb')
const bodyParser = require("body-parser")
const cors = require("cors")
const express = require('express')

const uri = 'mongodb://localhost:27017/'


var mongoclient = new MongoClient(uri);
const app = express()
let db;

app.use(cors())

async function main() {


db = await mongoclient.db("exp7_db");
console.log('connected to db')
}

main()

app.listen(5000, () => {
console.log('waiting')
})

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


const data = await db.collection('test').aggregate([{ $sample: {size: 5} }]).toArray()
console.log(data)

res.json(data)
})

Client Side

Add.js
import {useState} from 'react'

function App() {
const [data, setData] = useState(null)

const [val0, setVal0] = useState('no')


const [val1, setVal1] = useState('no')
const [val2, setVal2] = useState('no')
const [val3, setVal3] = useState('no')
const [val4, setVal4] = useState('no')

const handleSumbmit = async (e) => {


e.preventDefault()

const res = await fetch('http://127.0.0.1:5000/getData')


const data = await res.json()

setData(data)

console.log('data : ', data)


}

const handleResult = (e) => {


e.preventDefault();
let score = 0;
if (val0 === data[0].answer) score += 1
if (val1 === data[1].answer) score += 1
if (val2 === data[2].answer) score += 1
if (val3 === data[3].answer) score += 1
if (val4 === data[4].answer) score += 1
After clicking the Calculate Result button, we get the score results.
document.getElementById('score').innerHTML = `${score} / 5`

}
console.log('end')

return (
<div className="App">
{
data != null && (
<main>
<div>
{/* question 0 */}
<div>
<h1>{data[0].question} ?</h1>
<div>
<button onClick={() => setVal0('yes')}>
yes
</button>
<button onClick={() => setVal0('no')}>
no
</button>
</div>
</div>

{/* question 1 */}


<div>
<h1>{data[1].question} ?</h1>
<div>
<button onClick={() => setVal1('yes')}>
yes
</button>
<button onClick={() => setVal1('no')}>
no
</button>
</div>
</div>
{/* question 2*/}
<div>
<h1>{data[2].question} ?</h1>
<div>
<button onClick={() => setVal2('yes')}>
yes
</button>
<button onClick={() => setVal2('no')}>
no
</button>
</div>
</div>
{/* question 3 */}
<div>
<h1>{data[3].question} ?</h1>
<div>
<button onClick={() => setVal3('yes')}>
yes
</button>
<button onClick={() => setVal3('no')}>
no
</button>
</div>
</div>
{/* question 4*/}
<div>
<h1>{data[4].question} ?</h1>
<div>
<button onClick={() => setVal4('yes')}>
yes
</button>
<button onClick={() => setVal4('no')}>
no
</button>
</div>
</div>

</div>
</main>
)
}
<button onClick={handleSumbmit}>submit</button>
<button onClick={handleResult}>Calculate Result</button>

<h1>
score : <span id='score'></span>
</h1>
</div>
);
}

export default App;


Result:
Thus the online survey using react.js and the express server has successfully been
completed.

You might also like