FSWD Lab
FSWD Lab
TINDIVANAM
(A Constituent College of Anna University, Chennai)
Page | 1
University College of Engineering, Tindivanam
UNIVERSITY COLLEGE OF ENGINEERING
TINDIVANAM
(A Constituent College of Anna University, Chennai)
Page | 2
University College of Engineering, Tindivanam
INDEX
S.No. Date Experiment Page No Signature
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.
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>
);
}
Footer.js:
function Footer() {
return (
<div style={{textAlign:'right', border:'1px solid grey', width:'100%', height:'25px'}}>
Developed by .............
</div>
);
}
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 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.
Login page:
Mainpage.js:
description: String,
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));
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')
}
});
});
try{
const jsobj1 = await item.save();
res.status(201).json(jsobj1);
}catch(err){
res.send('error in the post method of server-side code')
}
});
Loginpage.js
import { useNavigate } from "react-router-dom";
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('');
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>
);
}
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>
app.use(cors());
app.use(bodyParser.json());
let db;
// related to db setup
try {
await client.connect();
db = client.db('microblog');
} catch (err) {
process.exit(1);
}
}
main().catch(console.error);
try {
if (!user) {
username,
followers: [username],
posts: []
});
res.json(user);
} catch (error) {
});
user_id: user._id,
username: user.username,
content,
});
await db.collection('users').updateOne(
{ username: username },
);
} else {
} catch (error) {
});
// get all the posts
try {
res.json(posts);
} catch (error) {
});
try {
res.json(posts || []);
} catch (error) {
);
try {
await db.collection('users').updateOne(
{ username: followerusername },
);
} else {
} catch (error) {
});
} catch (error) {
});
app.listen(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:
Login page:
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')
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')
}
});
});
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{
Client side:
Loginpage.js
import { useNavigate } from "react-router-dom";
Mainpage.js
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> */}
<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>
);
}
Orderpage.js
<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>
</table>)} */}
</div>
);
}
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:
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
dotenv.config();
app.use(express.json());
app.use(cors());
// Connect to MongoDB
Const MONGO_URI =
"mongodb+srv://admin:paswordadmin@cluster0.bkkmn.mongodb.net/Product"
// MongoDB Models
// Product Model
}));
// Routes
try {
title,
description,
price
});
await newProduct.save();
} catch (err) {
});
try {
const products = await Product.find();
res.json(products);
} catch (err) {
});
try {
res.json(product);
} catch (err) {
});
try {
product.title = title;
product.description = description;
product.price = price;
await product.save();
} catch (err) {
});
try {
await product.remove();
} catch (err) {
});
// Start Server
app.listen(PORT, () => {
});
Client Side
App.js:
// src/App.js
import './App.css';
function App() {
return (
<Router>
<Navbar />
<div className="container">
<Routes>
</Routes>
</div>
</Router>
);
HomePage.js:
// src/pages/HomePage.js
import './HomePage.css'
function HomePage() {
useEffect(() => {
axios.get('http://localhost:5000/api/products')
}, []);
return (
<div>
<h1>Classifieds</h1>
<div className="products">
{products.map(product => (
<h3>{product.title}</h3>
<p>{product.description}</p>
<p><strong>₹{product.price}</strong></p>
</div>
))}
</div>
</div>
);
CreateProductPage.js:
// src/pages/CreateProductPage.js
function CreateProductPage() {
e.preventDefault();
try {
} catch (error) {
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Title"
value={title}
required
/>
<textarea
placeholder="Description"
value={description}
required
/>
<input
type="number"
placeholder="Price"
value={price}
required
/>
</form>
</div>
);
}
Navbar.js:
// src/components/Navbar.js
import './Navbar.css'
function Navbar() {
return (
<nav className="navbar">
<div className="container">
<ul>
</ul>
</div>
</nav>
);
}
export default Navbar;
StyleSheet
App.css:
/* src/App.css */
body {
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;
cursor: pointer;
border-radius: 5px;
button:hover {
background-color: #0056b3;
input, textarea {
padding: 10px;
border-radius: 5px;
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;
.products {
display: grid;
gap: 20px;
margin-top: 20px;
.product {
background-color: #fff;
padding: 20px;
border-radius: 8px;
.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;
gap: 20px;
margin-top: 20px;
.product {
background-color: #fff;
padding: 20px;
border-radius: 8px;
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;
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
Login page:
Create_user page:
Before registering a user into the MongoDB database. The database is empty
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)=>{ …}
app.use(express.json());
app.use(express.urlencoded({extended: true}));
/*
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();
});
}finally{
console.log('Leave details - added');
Admin_view_leaves page:
// MongoDB connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/exp5_db')
Admin_view_leaves page:
Client side:
Loginpage.js
import { useNavigate } from "react-router-dom";
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:
}
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('');
return (
<div className="App">
<h1> Hi! </h1>
<h2> User creation page </h2>
{/* <h4>{JSON.stringify(items)}</h4> */}
</div>
);
}
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('');
return (
<div className="App">
<h1> Hi! </h1>
<h2> Leave update page </h2>
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([])
return (
<div className="App">
<h1> Hi! </h1>
{/* <h4>{JSON.stringify(items)}</h4> */}
<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>
);
}
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('');
<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>
);
}
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:
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:
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)=>{ …}
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
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.
app.listen(5000, ()=>{
});
// step 5 - install cors, body-parser package using npm install cors, body-parser and import
them here.
app.use(cors());
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.
/*
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.end();
});
try{
/*
input : no params
output: return json object - statuses of the different tasks of the proj.
*/
fn_view_tasks();
res.json(data);
res.end();
});
try{
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.
*/
fn_update_a_task();
res.json(data);
console.log('Task updated');
res.end();
});
try{
if (result == null){
console.log('Updated failed');
}
else{
console.log('Update successful');
}finally{
Client Side
Add_task.js
import './App.css';
const Add_task=()=>{
try{
document.getElementById('id1').innerHTML = response.data;
}catch(err){
window.alert('An error in insert user function : '+ err);
return (
<div className="App">
<button onClick={insertItems}>insert</button>
</div>
</div>
);
Update_task.js
import './App.css';
const Update_task=()=>{
try{
document.getElementById('id1').innerHTML = response.data;
}catch(err){
return (
<div className="App">
</div>
</div>
);
View_task.js
import './App.css';
function View_task() {
try{
document.getElementById('id1').innerHTML = response.data;
setItems(response.data);
}catch(err){
}
}
return (
<div className="App">
<center>
<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>
);
App.js
import './App.css';
function App() {
return (
<div className="App">
<Router>
<Routes>
</Routes>
</Router>
</div>
);
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:
2. Add the get method in the App.js file to get the following details for 5 questions from
the backend express server.
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')
app.use(cors())
main()
app.listen(5000, () => {
console.log('waiting')
})
res.json(data)
})
Client Side
Add.js
import {useState} from 'react'
function App() {
const [data, setData] = useState(null)
setData(data)
}
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>
</div>
</main>
)
}
<button onClick={handleSumbmit}>submit</button>
<button onClick={handleResult}>Calculate Result</button>
<h1>
score : <span id='score'></span>
</h1>
</div>
);
}