Fullstack Lab
Fullstack Lab
1. Develop a portfolio website for yourself which gives details about yourself for a potential
recruiter.
Aim
To create a comprehensive and visually appealing online portfolio that provides potential
recruiters with a detailed overview of my skills, experiences, projects, and achievements, effectively
show casing my suitability for their organization.
Steps to Implement:
1. Create a new HTML file and paste the provided HTML code into it.
2. Create a "css" folder and place the "styles.css" file in it.
3. Create an "images" folder and place the image files mentioned in the HTML code.
4. Include the links to external libraries (Animate.css and Ionicons) in the <head> section.
5. Customize the content, images, and links according to your preferences.
6. Open the HTML file in a web browser to see the webpage in action.
Components Description:
HTML Structure:
• The HTML document starts with a <!DOCTYPE html> declaration, specifying the document
type.
• The <html> element encloses the entire HTML content of the page.
• The <head> section contains metadata about the page, such as character encoding, viewport
settings, and links to external resources like stylesheets and icons.
• The <body> section contains the main content of the webpage.
• Navigation (nav):
• The navigation bar (<nav>) contains the site's logo (heading) and a list of navigation
links (<ul>) using an unordered list.
• Each navigation link is represented by a list item (<li>) containing an anchor (<a>)
element.
• The burger icon button (<button>) is used to toggle the navigation menu on smaller
screens.
• The JavaScript code handles the toggle functionality of the navigation menu when the
burger icon is clicked.
• Hero Section:
• The "hero" section (<section>) contains an image of a person and a "bio" (<div>) with a
brief description.
• The bio includes a title (<h2>) and a paragraph (<p>) with text describing the person's
role and background.
• More About Section:
• The "more-about" section provides additional details about the person's involvement in
organizations.
• It includes a title (<h2>) and several paragraphs (<p>) with relevant information.
• Skills Section:
• The "skills" section displays the person's top skills using icons (<img> elements).
• Skills are divided into two groups using separate <div> containers with the class first-set
and second-set.
• The icons are animated using the animate.css library with the class animate pulse.
• Projects Section:
• The "projects" section showcases recent projects.
• Each project is contained within a <div> with the class project-container project-card.
• Each project includes an image (<img>), a title (<h3>), and a description (<p>).
• Contact Section:
• The "contact" section provides a form for users to get in touch.
lOMoARcPSD|35 870736
• The form includes fields for name, email, and a message (<input> and <textarea>
elements).
• The form uses the "formspree.io" service to handle form submissions.
• Social Buttons and Scroll to Top:
• Social media icons are displayed in a fixed column on the right side of the page (<div>
with class socials).
• A scroll-to-top button is positioned at the bottom right corner of the page.
CSS Styling:
• The provided CSS code defines the styling for various elements on the page.
• CSS variables are used to store reusable values such as colors, fonts, and spacing.
• Media queries are used to make the page responsive for different screen sizes.
JavaScript Interactivity:
• The JavaScript code handles the toggling of the navigation menu on smaller screens when the
burger icon is clicked.
• When a navigation link is clicked, the navigation menu closes automatically.
• The scroll-to-top button is implemented using JavaScript to smoothly scroll to the top of the
page when clicked.
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--CSS Styles -->
<link rel="stylesheet" href="E:\Nelson\FSWD\Exp_1\css\styles.css" />
<!-- Favicons -->
<link
rel="apple-touch-icon"
sizes="180x180"
href="assets/icons/apple-touch-icon.png"
/>
<link
rel="icon"
type="image/png"
sizes="32x32"
href="assets/icons/favicon-32x32.png"
/>
<!-- Animate CSS CDN -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
/>
<title>Jane Doe | Web Developer</title>
</head>
<body>
<nav>
<h1>NELSON SELVIN</h1>
<ul class="navigation">
<li><a href="#about" class="nav-link">About</a></li>
<li><a href="#skills" class="nav-link">Skills</a></li>
lOMoARcPSD|35 870736
alt=""
loading="lazy"
class="icon icon-card"
/>
<img src="E:\Nelson\FSWD\Exp_1\images\html.jpg"
alt=""
loading="lazy"
class="icon icon-card"
/>
<img src="E:\Nelson\FSWD\Exp_1\images\sql.jpg"
alt=""
loading="lazy"
class="icon icon-card"
/>
</div>
</div>
</section>
<section class="projects" id="projects">
<h2 class="projects-title">Some of my Recent Projects</h2>
<div class="projects-container">
<div class="project-container project-card">
<img src="E:\Nelson\FSWD\Exp_1\images\paper1.jpg"
alt="expense-tracker"
loading="lazy"
class="project-pic"
/>
<h3 class="project-title">K-MEANS Clustering</h3>
<p class="project-details">
Implementing the K-Means algorithm for safeguarding sensitive attributes offers robust data
protection through clustering. By grouping similar data points, K- Means minimizes the risk of
exposing sensitive information, enhancing privacy in various applications!
</p>
</div>
<div class="project-container project-card">
<img
src="E:\Nelson\FSWD\Exp_1\images\paper2.jpg"
alt="netflic-clone"
loading="lazy"
class="project-pic"
/>
<h3 class="project-title">Face Recognition using Laplacian Faces</h3>
<p class="project-details">
Leveraging Laplacian Faces for face recognition results in an advanced technique that
extracts distinctive facial features.
</p>
</div>
</div>
</section>
<section class="contact" id="contact">
<h2>Get In Touch With Me</h2>
<div class="contact-form-container">
<div class="contact-form">
<form action="https://formspree.io/f/xyylngw" method="POST">
<div class="form-control">
lOMoARcPSD|35 870736
<label for="name">Name</label>
<input
type="text"
id="name"
name="sender-name"
placeholder="Enter Your Name"
class="input-field"
required
/>
</div>
<div class="form-control">
<label for="email">Email</label>
<input
type="email"
id="email"
name="sender-email"
placeholder="Enter Your Email"
class="input-field"
required
/>
</div>
<div class="form-control">
<label for="message">Message</label>
<textarea
id="message"
cols="60"
rows="10"
placeholder="Enter Your Message"
name="message"
class="input-field"
required
>
</textarea>
</div>
<input
type="submit"
value="Submit"
id="submit-btn"
class="submit-btn"
/>
</form>
</div>
</div>
</section>
<!-- Website scripts -->
<script src="assets/js/app.js"></script>
<!-- Ion icons scripts -->
<script
type="module"
src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.esm.js"
></script>
<script
nomodule
src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.js"
lOMoARcPSD|35 870736
></script>
</body>
</html>
CSS Code:
margin: 8px; }
} .icon {
.burger-menu { width: 5.875rem;
display: block; height: 5.25rem;
} }
nav ul.show { .projects-container {
transform: translateX(0); flex-direction: column;
} }
.hero { .project-container {
margin-top: -4rem; width: 20.875rem;
flex-direction: column; }
gap: 0; .contact-form-container {
} max-width: 23.75rem;
.hero img { }
height: 37.5rem; }
width: 30rem; @media screen and (max-width: 420px)
} {
.bio { .hero img {
margin-top: -7rem; height: 37.5rem;
width: 20.5rem; width: 23rem;
} }
.more-about { .bio {
margin-top: 2rem; width: 18.3rem;
padding: 1rem 3.5rem; }
} .project-container {
.more-about h2 { width: 17.875rem;
text-align: center; }
} .contact-form-container {
.more-about p { max-width: 17.75rem;
text-align: justify; }}
JS Code:
// Nav hamburgerburger selections
const burger = document.querySelector("#burger-menu");
const ul = document.querySelector("nav ul");
const nav = document.querySelector("nav");
// Scroll to top selection
const scrollUp = document.querySelector("#scroll-up");
// Select nav links
const navLink = document.querySelectorAll(".nav-link");
// Hamburger menu function
burger.addEventListener("click", () => {
ul.classList.toggle("show");});
// Close hamburger menu when a link is clicked
navLink.forEach((link) =>
link.addEventListener("click", () => {
ul.classList.remove("show");
}));
// scroll to top functionality
scrollUp.addEventListener("click", () => {
window.scrollTo({
top: 0,
left: 0,
behavior: "smooth",
lOMoARcPSD|35 870736
});
});
Output:
lOMoARcPSD|35 870736
Result:
A professional portfolio website has been designed and developed successfully, thatpresents my
expertise, career journey, and project accomplishments in an organized man enabling potential recruiters
to gain insights into my capabilities and make informeddecisions regarding my candidacy.
This experiment is mapped with PO1, PO2, PO3, PO4, PO5, PO6, PO7, PO8, PO9,
PO10, PO11, PO12 and PSO1, PSO2 & PSO3.
lOMoARcPSD|35 870736
2. Create a web application to manage the TO-DO list of users, where users can login
and manage their to-do items
Aim
To create a web application to manage the TO-DO list of users, where users can login and
manage their to-do items.
Steps to Implement:
1. Set Up Your New React Project
• Create a new project: npx create-react-app todo-list-app
2. Create Components
• Inside the src folder, create components for the TO-DO list and TO-DO items.
3. Implement TO-DO List Component
• Edit the TO-DO list component to manage TO-DO list data and actions.
4. Implement TO-DO List Component UI
• Edit the TO-DO list component to display the list of items and input for adding
new items.
5. Implement TO-DO Item Component
• Create a component for individual TO-DO items.
• Define props and actions (e.g., marking as completed, deleting).
6. Implement TO-DO Item Component UI
• Edit the TO-DO item component to display an individual item with appropriate
actions.
7. Manage State
• Use React state to manage the list of TO-DO items and their properties.
8. Add Functionality
• Implement functions to add new items, mark items as completed, and potentially
delete items.
9. Styling
• Add CSS or use a styling library to enhance the appearance of your components.
10. Run the Application
• Start your React app using:
npm start
Components Description:
App
• Import React
• Import Components
• Create the App Component
• Export the App Component
• Usage and Rendering
TodoList
• State Initialization:
const [todos, setTodos] = useState([]);
const [newTodo, setNewTodo] = useState("");
The todos state holds an array of to-do items, and newTodo state holds the value
of the new to-do item being entered by the user.
• Adding a New To-Do Item:
lOMoARcPSD|35 870736
When the user types a new to-do item in the input field and clicks the "Add"
button, handleAddTodo function is triggered.
If the trimmed value of newTodo is not empty, a new to-do item is created and
added to the todos state array.
The newTodo state is then reset to an empty string to clear the input field.
• Deleting a To-Do Item:
Each to-do item in the list has a "Delete" button.
Clicking the "Delete" button triggers the handleDeleteTodo function with the
index of the clicked item.
The function creates a copy of the current todos array, removes the item at the
specified index, and updates the todos state with the new array.
• Toggling Completion Status:
Each to-do item includes a checkbox to mark the item as complete or incomplete.
Clicking the checkbox triggers the handleToggleTodo function with the index of
the clicked item.
The function toggles the checked property of the corresponding item in the todos
array and updates the state.
• Rendering To-Do Items:
The todos array is mapped over to render each individual to-do item.
For each item, a list element (<li>) is generated.
Each list item contains a checkbox (for completion status) and the text of the to-do
item.
The text is styled with a line-through decoration if the item is checked
(completed).
A "Delete" button is also provided for each to-do item.
• User Interaction:
The input field allows users to enter a new to-do item.
The "Add" button triggers the addition of the new to-do item to the list.
The checkbox allows users to mark to-do items as complete or incomplete.
The "Delete" button removes the corresponding to-do item from the list.
• Component Rendering:
The component renders a title, input field, "Add" button, and a list of to-do items.
• Component Export:
The TodoList component is exported as the default export of the module.
index
• Import React and Dependencies
• Import ReactDOM
• Import Styles and Components
• Render the Application
Use ReactDOM.createRoot to create a root instance for rendering.
The root instance is connected to the DOM element with the id of 'root'.
Within the root, the App component is rendered within a <React.StrictMode>
component. StrictMode is used for highlighting potential problems in the
application during development.
App.js:
import React from "react";
import TodoList from "./TodoList";
const App = () => {
return (
<div>
<TodoList />
</div>
lOMoARcPSD|35 870736
);};
export default App;
TodoList.js:
import React, { useState } from "react";
const TodoList = () => {
const [todos, setTodos] = useState([]);
const [newTodo, setNewTodo] = useState("");
const handleAddTodo = () => {
if (newTodo.trim() !== "") {
setTodos([...todos, { text: newTodo.trim(), checked: false }]);
setNewTodo("");
}
};
const handleDeleteTodo = (index) => {
const newTodos = [...todos];
newTodos.splice(index, 1);
setTodos(newTodos);
};
const handleToggleTodo = (index) => {
const newTodos = [...todos];
newTodos[index].checked = !newTodos[index].checked;
setTodos(newTodos);
};
return (
<div>
<h1>To-Do List</h1>
<input
type="text"
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
/>
<button onClick={handleAddTodo}>Add</button>
<ul>
{todos.map((todo, index) => (
<li
key={index}
style={{
display: "flex",
}}
>
<div style={{ display: "flex", alignItems: "center" }}>
<input
type="checkbox"
checked={todo.checked}
onChange={() => handleToggleTodo(index)}
/>
<span
style={{
marginRight: "10px",
textDecoration: todo.checked ? "line-through" : "none",
}}
>
{todo.text}
</span>
lOMoARcPSD|35 870736
</div>
<button
style={{ marginTop: "5px", marginBottom: "5px" }}
onClick={() => handleDeleteTodo(index)}
>
Delete
</button>
</li>
))}
</ul>
</div>
);
};
export default TodoList;
index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
Output:
lOMoARcPSD|35 870736
lOMoARcPSD|35 870736
Result
Thus the web application has been created to manage the TO-DO list of users, where
users can login and manage their to-do items.
This experiment is mapped with PO1, PO2, PO3, PO4, PO5, PO6, PO7, PO8, PO9,
PO10, PO11, PO12 and PSO1, PSO2 & PSO3.
lOMoARcPSD|35 870736
3. Create a simple micro blogging application (like twitter) that allows people to post
their content which can be viewed by people who follow them.
Aim
To develop a simple micro blogging web application that enabling user registration,
content posting.
Steps to Implement:
Steps to create the application:
Step 1: Create React Project
npx create-react-app blog
Step 2: Change your directory and enter your main folder MY-APP as
cd blog
Step 3: Install the required modules using the command
npm i bootstrap
npm i react-bootstrap
Step 4: The dependencies in package.json will look like:
package.json
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"bootstrap": "^5.3.0",
"react": "^18.2.0",
"react-bootstrap": "^2.7.4",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Step 5: Create a folder call components and create the files BlogNav.js, Posts.js, Post1.js,
Post2.js,
Post3.js, Post4.js
Step 6: Open the terminal and run the project using the command.
npm start
Components Description:
• App.js: This file imports all the components and displays
• BlogNav.js: This file is used to create the navigation bar
• Posts.js: This file renders the posts
• Post1.js, Post2.js, Post3.js, Post4.js: These files contain the content of the blog
App.js
import React from "react";
import "./App.css";
import Posts from "./components/Posts";
import Navbar from "./components/BlogNav"
const App = () => {
return (
<div className="main-container" style={{backgroundColor: "aliceblue"}}>
<Navbar />
<Posts />
</div>
);
};
lOMoARcPSD|35 870736
BlogNav.js
import React from "react";
import 'bootstrap/dist/css/bootstrap.css';
import { Navbar, Nav, Form, FormControl } from 'react-bootstrap';
const BlogNav = () => {
return (
<div>
<Navbar style={{
backgroundColor:"#A3C1D4"
lOMoARcPSD|35 870736
}}>
<img
src=' D:\nel\blog\Nelson_Pic.png'
height='30'
alt=''
loading='lazy'
/>
<Navbar.Brand href="#home" style={{color:"white",
marginLeft:"10px"}}>Nelson’s Blog</Navbar.Brand>
<Navbar.Toggle />
<Navbar.Collapse id="basic-navbar-nav" className="d-flex
justify-content-end">
<Nav>
<Nav.Link href="#home" style={{color:"white"}}>
JavaScript
</Nav.Link>
<Nav.Link href="#about" style={{color:"white"}}>
Data Structure
</Nav.Link>
<Nav.Link href="#services"
style={{color:"white"}}>
Algorithm
</Nav.Link>
<Nav.Link href="#contact"
style={{color:"white"}}>
Computer Network
</Nav.Link>
</Nav>
<Form inline>
<FormControl type="text" placeholder="Search"
className="ml-auto" />
</Form>
</Navbar.Collapse>
</Navbar>
</div>
)
}
export default BlogNav;
Post1.js
import { Card } from "react-bootstrap";
const Post1 = () => {
return (
<Card>
<Card.Img
variant="top"
src=
"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20230305183140/
Javascript.jpg"
width={20}
height={250}
/>
<Card.Body>
lOMoARcPSD|35 870736
<Card.Title>JAVASCRIPT</Card.Title>
<Card.Text>
JavaScript is the world most popular
lightweight, interpreted compiled programming
language. It is also known as scripting
language for web pages. It is well-known for
the development of web pages, many non-browser
environments also use it. JavaScript can be
used for Client-side developments as well as
Server-side developments
</Card.Text>
<a href="#" className="btn btn-primary">Read More</a>
</Card.Body>
</Card>
);
};
export default Post1;
Post2.js
import { Card } from "react-bootstrap";
const Post2 = () => {
return (
<Card>
<Card.Img
variant="top"
src=
"https://media.geeksforgeeks.org/img-practice/banner/coa-gate-2022-thumbnail.png"
width={20}
height={250}
/>
<Card.Body>
<Card.Title>Data Structure</Card.Title>
<Card.Text>
The word Algorithm means “a process
or set of rules to be followed in calculations
or other problem-solving operations”. Therefore
Algorithm refers to a set of rules/instructions
that step-by-step define how a work is to be
executed upon in order to get the expected
results.
</Card.Text>
<a href="#" className="btn btn-primary">Read More</a>
</Card.Body>
</Card>
)
}
export default Post2;
Post3.js
import { Card } from "react-bootstrap";
const Post3 = () => {
return (
<Card>
<Card.Img
lOMoARcPSD|35 870736
variant="top"
src=
"https://media.geeksforgeeks.org/img-practice/banner/google-test-series-thumbnail.png"
width={20}
height={250}
/>
<Card.Body>
<Card.Title>Algorithm</Card.Title>
<Card.Text>
The word Algorithm means “a process
or set of rules to be followed in calculations
or other problem-solving operations”. Therefore
Algorithm refers to a set of rules/instructions
that step-by-step define how a work is to be
executed upon in order to get the expected
results.
</Card.Text>
<a href="#" className="btn btn-primary">Read More</a>
</Card.Body>
</Card>
)
}
export default Post3;
Post4.js
import { Card } from "react-bootstrap";
const Post4 = () => {
return (
<Card>
<Card.Img
variant="top"
src=
"https://media.geeksforgeeks.org/img-practice/banner/cp-maths-java-thumbnail.png"
width={20}
height={250}
/>
<Card.Body>
<Card.Title>Computer Network</Card.Title>
<Card.Text>
An interconnection of multiple devices,
also known as hosts, that are connected using
multiple paths for the purpose of sending/
receiving data media. Computer networks can
also include multiple devices/mediums which
help in the communication between two different
devices; these are known as Network devices
and include things such as routers, switches,
hubs, and bridges.
</Card.Text>
<a href="#" className="btn btn-primary">Read More</a>
</Card.Body>
</Card>
)}
export default Post4;
lOMoARcPSD|35 870736
Output:
Result
Thus a simple micro blogging platform has been created successfully, that allowing users
to register, create posts, follow other users, and view personalized feeds based on the
followed users' posts.
This experiment is mapped with PO1, PO2, PO3, PO4, PO5, PO6, PO7, PO8, PO9,
PO10, PO11, PO12 and PSO1, PSO2 & PSO3.
lOMoARcPSD|35 870736
4. Create a food delivery website where users can order food from a particular
restaurant listed in the website.
Aim
To create a user-friendly React-based food delivery website to browse and customize
orders.
Steps to Implement:
Steps to create the application:
Step 1: Create a React App
npx create-react-app shopping-cart-app
Step 2: Change your working directory to the newly created app:
cd shopping-cart-app
Step 3: Functionality - Replace the src Directory “App.js” file Contents with the below code.
Step 4: Styling - Replace the src Directory “App.css” file contents with the below code.
Step 5: Running the App
npm start
Components Description:
App.js: It allows the user to view the list of products, add them to the cart, adjust
quantities, and see the total cost.
App.css: contains styling rules for a React-based shopping cart application, including
the app container, shopping modal, product list, cart, quantity, total cost, and buttons,
ensuring a visually appealing and functional user interface.
App.js:
import React, { useState } from 'react';
import './App.css';
function App() {
const [isShoppingOpen, setIsShoppingOpen] = useState(false);
const [products, setProducts] = useState([
{
id: 1,
name: 'Chat Masala',
image: '1.png',
price: 120000,
},
{
id: 2,
name: 'Tandoori',
image: '2.PNG',
price: 120000,
},
{
id: 3,
name: 'Chicken Salad',
image: '3.PNG',
price: 220000,
},
{
id: 4,
lOMoARcPSD|35 870736
{
id: 5,
name: 'Veg Salad',
image: '5.PNG',
price: 320000,
},
{
id: 6,
name: 'Paneer Pizza',
image: '6.PNG',
price: 120000,
},
]);
const [cart, setCart] = useState([]);
const openShopping = () => {
setIsShoppingOpen(true);
};
const closeShopping = () => {
setIsShoppingOpen(false);
};
const addToCart = (key) => {
const product = products[key];
const cartItem = {
...product,
quantity: 1,
};
setCart([...cart, cartItem]);
};
const changeQuantity = (key, newQuantity) => {
if (newQuantity === 0) {
const updatedCart = [...cart];
updatedCart.splice(key, 1);
setCart(updatedCart);
} else {
const updatedCart = [...cart];
updatedCart[key].quantity = newQuantity;
updatedCart[key].price = newQuantity * products[key].price;
setCart(updatedCart);
}
};
return (
<div className={`App ${isShoppingOpen ? 'active' : ''}`}>
<div className="shopping">
<button onClick={openShopping}>Open Shopping</button>
</div>
<div className="closeShopping">
<button onClick={closeShopping}>Close Shopping</button>
</div>
lOMoARcPSD|35 870736
<div className="list">
{products.map((product, key) => (
<div className="item" key={key}>
<img src={`image/${product.image}`} alt={product.name} />
<div className="title">{product.name}</div>
<div className="price">{product.price.toLocaleString()}</div>
<button onClick={() => addToCart(key)}>Add To Cart</button>
</div>
))}
</div>
<div className="listCard">
<ul>
{cart.map((cartItem, key) => (
<li key={key}>
<div>
<img src={`image/${cartItem.image}`} alt={cartItem.name} />
</div>
<div>{cartItem.name}</div>
<div>{cartItem.price.toLocaleString()}</div>
<div>
<button onClick={() => changeQuantity(key, cartItem.quantity - 1)}>-</button>
<div className="count">{cartItem.quantity}</div>
<button onClick={() => changeQuantity(key, cartItem.quantity + 1)}>+</button>
</div>
</li>
))}
</ul>
<div className="total-cost">
Total Cost: ${cart.reduce((total, item) => total + item.price, 0).toLocaleString()}
</div>
<div className="quantity">Quantity: {cart.reduce((total, item) => total +
item.quantity, 0)}</div>
</div>
</div>
);
}
export default App;
App.css
Output:
lOMoARcPSD|35 870736
lOMoARcPSD|35 870736
Result
Thus the food delivery website with menu browsing and order placement using React has
been created successfully.
This experiment is mapped with PO1, PO2, PO3, PO4, PO5, PO6, PO7, PO8, PO9,
PO10, PO11, PO12 and PSO1, PSO2 & PSO3.
lOMoARcPSD|35 870736
Aim
To create a classifieds webpage where users can search for products based on keywords
and view detailed product listings.
Steps to Implement:
Steps to create the application:
Step 1: Create your project structure according to the requirements and entered the code
properly.
Step 2: Install the dependencies (npm install express)
Step 3: Run the Server (node server.js)
Step 4: Open your web browser and navigate to http://localhost:3000 to access your
classifieds
webpage.
Components Description:
index.html
HTML file defining the structure of a classifieds webpage with sections for products and
including external CSS and JavaScript files.
styles.css
CSS file containing styles for resetting default styles, defining the page layout, styling the
header, navigation menu, search section, and product listings, and making the design
responsive.
script.js
JavaScript code that handles the functionality of the webpage, including searching for
products based on user input and displaying filtered product listings.
server.js
Node.js server script using Express to serve static files (HTML, CSS, JavaScript, and
images) and listening on port 3000 to host the classifieds webpage.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Classifieds - Buy and Sell</title>
</head>
<body>
<header>
<h1>Classifieds - Buy and Sell</h1>
</header>
<div class="container">
<section id="search-section">
<input type="text" id="search-input" placeholder="Search for products">
<button id="search-button">Search</button>
</section>
<section id="products">
<h2>Featured Products</h2>
lOMoARcPSD|35 870736
<ul id="product-list">
<!-- Product listings will be displayed here -->
</ul>
</section>
</div>
<script src="script.js"></script>
</body>
</html>
styles.css
script.js
document.addEventListener("DOMContentLoaded", () => {
const searchButton = document.getElementById("search-button");
const searchInput = document.getElementById("search-input");
const productList = document.getElementById("product-list");
searchButton.addEventListener("click", () => {
const searchTerm = searchInput.value.toLowerCase();
const filteredProducts = products.filter(product =>
product.title.toLowerCase().includes(searchTerm));
displayProducts(filteredProducts);
});
function displayProducts(productArray) {
productList.innerHTML = "";
productArray.forEach(product => {
const listItem = document.createElement("li");
listItem.classList.add("product");
listItem.innerHTML = `
<h3>${product.title}</h3>
<p>${product.price}</p>
<p>${product.description}</p>
<div class="product-images">
${product.images.map(image => `<img src="images/${product.category}/$
{image}" alt="${product.title}">`).join("")}
</div>
`;
productList.appendChild(listItem);
});
}
});
// Example data (you can replace this with your data)
const products = [
{
id: 1,
title: "Used Laptop",
price: "$300",
lOMoARcPSD|35 870736
server.js
const express = require("express");
const app = express();
const port = process.env.PORT || 3000;
app.use(express.static("public"));
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Output:
lOMoARcPSD|35 870736
.
lOMoARcPSD|35 870736
Result
Thus a functional classifieds webpage has been created, that allows users to search for
products, with filtered results displayed dynamically. The page provides an organized layout and
responsive design, ensuring an effective and user-friendly browsing experience for buying and
selling classified items.This experiment is mapped with PO1, PO2, PO3, PO4, PO5, PO6,
PO7, PO8, PO9,PO10, PO11, PO12 and PSO1, PSO2 & PSO3.
lOMoARcPSD|35 870736
6. Develop a leave management system for an organization where users can apply
different types of leaves such as casual leave and medical leave. They also can view the
available number of days
Aim
To design and implement a user-friendly Leave Management System enabling employees
to apply for different types of leaves (casual and medical) and check their leave balances,
enhancing organizational efficiency and employee satisfaction.
Steps to Implement:
Steps to create the application:
Step 1: Create a new React application using Create React App and install React Router
DOM for
handling routing.
Step 2: Inside the frontend/src directory, create a "components" folder. Inside the
"components"
folder, create Login.js, Signup.js, and Leavemanagement.js files with respective
functionalities
for user authentication and leave management.
Step 3: Implement the frontend components. Login.js handles user login, Signup.js handles
user
registration, and Leavemanagement.js handles leave application and balance display.
Step 4: Create a CSS file (Leavemanagement.css) for styling the components.
Step 5: Configure routes in App.js using React Router DOM to navigate between Login,
Signup, and
Leavemanagement components.
Step 6: Set up the backend:
Create a folder named "backend."
Inside the backend folder, run npm init -y to initialize a Node.js application.
Install required packages: npm install express mongoose body-parser bcrypt cors
dotenv
Step 7: Inside the backend folder, create "models" and "routes" folders.
In the "models" folder, create a leave.js file defining the MongoDB schema for user
leave
data.
In the "routes" folder, create login.js, signup.js, and leave.js files for handling
authentication,
registration, and leave management routes.
Step 8: Implement the backend routes:
login.js: Handle user login, validate credentials, and return user data.
signup.js: Handle user registration and save user data to the database.
leave.js: Handle leave application, deduct leave days from the user's balance, and
update the
database.
Step 9: Create an index.js file in the backend folder to set up Express server, connect to
MongoDB,
and define API routes.
Step 10: Start both frontend and backend:
In the frontend directory, run npm start to start the React development server.
In the backend directory, run node index.js to start the Express server.
Components Description:
Frontend
lOMoARcPSD|35 870736
Login.js
Login.js is a React component enabling user authentication. It captures username and
password, sends a login request to a server, and redirects users to a leave management page
upon successful login, also offering a signup option.
Signup.js
Signup.js is a React component allowing users to register by providing a username and
password. It sends a signup request to a server, displaying a success or error message, and
offers a link to the login page.
Leavemanagement.js
Leavemanagement.js is a React component managing leave applications. It displays user
information, allows applying for casual or medical leave, updates leave balances, and
provides real-time feedback on available leave days.
Leavemanagement.css
Leavemanagement.css is a CSS file defining styles for a leave management application. It
includes font imports, sets up a clean layout with centered headings and responsive form
elements. The CSS animations slideInLeft and slideInRight create smooth entry effects for
the form and balance containers, enhancing the user interface.
App.js
App.js is the main file of a React application, defining routes using the React Router
library. It sets up routes for login, signup, and leave management components, allowing
seamless navigation between different parts of the application based on the URL path.
index.js
index.js is the entry point of a React application. It uses ReactDOM to render the main
App component inside a Router component from React Router. The App component and its
defined routes are then rendered in the HTML element with the id 'root', effectively
initializing the React application and enabling navigation between different components
based on the URL path.
Backend
leave.js
leave.js is a Node.js module defining a Mongoose schema for user data. It specifies the
structure of user documents, including fields for username, password, casual leave balance,
and medical leave balance. The schema is used to create a Mongoose model named 'User',
which is then exported for use in other parts of the application. This schema is typically
utilized for database operations, enabling the storage and retrieval of user-related
information in a MongoDB database.
Routes
login.js
login.js is a Node.js module implementing user authentication logic for a login endpoint.
It verifies incoming username and password, responds with user details if authentication is
successful, and returns an error message if authentication fails. The module uses the User
model and Express.js for routing.
signup.js
signup.js is a Node.js module that manages user registration for a signup endpoint. It
checks if a user with the given username already exists in the database and, if not, creates a
new user with default leave balances. It provides a success message upon successful
registration and handles errors gracefully. This module utilizes the User model and
Express.js for routing.
lOMoARcPSD|35 870736
leave.js
leave.js is a Node.js module serving as a backend API for managing user leave balances.
It includes routes for retrieving a user's leave information by ID (GET request) and updating
their leave balances based on leave type and duration (PUT request). The module checks if
the requested leave balance update is valid and responds with success messages or error
messages if limits are exceeded. It utilizes the User model and Express.js for routing.
index.js
index.js is the main file of a Node.js server application. It creates an Express server,
establishes a connection to a MongoDB database, configures routes for user authentication
and leave management, and listens on a specific port. The server handles incoming requests
for user login, registration, and leave management operations, providing essential
functionality for the associated frontend application.
Login.js
// LEAVEMANAGEMENT\frontend\src\components
import React, { useState } from 'react';
import { useNavigate } from "react-router-dom";
function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
const [objectid, setObjectid] = useState('');
const navigate=useNavigate();
function handlesignup(){
navigate("/signup")
}
const handleLogin = async () => {
try {
const response = await fetch('http://localhost:3001/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
});
if (response.status === 200) {
const data = await response.json();
setObjectid(data.userId);
console.log("User ID : ",data.userId);
console.log("fjflf balance : ",data.leavebalance);
navigate("/Leavemanagement/",{state:
{id:data.userId,casual:data.casual,medical:data.medical,username:data.username1}});
} else {
const data = await response.json();
setMessage(data.message);
}
} catch (error) {
console.error(error);
}
};
return (
<div>
lOMoARcPSD|35 870736
<h2>Login</h2>
<p>{objectid}</p>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button onClick={handleLogin}>Login</button>
<p>{message}</p>
<br>
</br>
<h1 onClick={handlesignup}>Signup</h1>
</div>
);
}
export default Login;
Signup.js
//LEAVEMANAGEMENT\frontend\src\components
import React, { useState } from 'react';
import { useNavigate } from "react-router-dom";
function Signup() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
const navigate=useNavigate();
function handleLogin(){
navigate("/")
}
const handleSignup = async () => {
try {
const response = await fetch('http://localhost:3001/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
});
if (response.status === 201) {
const data = await response.json();
setMessage(data.message);
} else {
const data = await response.json();
setMessage(data.message);
}
} catch (error) {
console.error(error);
lOMoARcPSD|35 870736
}
};
return (
<div>
<h2>Signup</h2>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button onClick={handleSignup}>Signup</button>
<p>{message}</p>
<br>
</br>
<h1 onClick={handleLogin}>Login</h1>
</div>
);
}
export default Signup;
Leavemanagement.js
// LEAVEMANAGEMENT\frontend\src\components
import React, { useState, useEffect } from "react";
import './Leavemanagement.css'
import { useLocation } from "react-router-dom";
const Leavemanagement = () => {
const location = useLocation();
const [users, setUsers] = useState();
const [leavebalanceData, setLeaveBalanceData] = useState(location.state.casual);
const [message, setMessage] = useState("Welcome!!!");
const [medical, setMedical] = useState(location.state.medical);
const [casual, setCasual] = useState(location.state.casual);
const [data, setData] = useState([]);
const [leaveType, setLeaveType] = useState("casual");
const [leaveDays, setLeaveDays] = useState("");
const id = location.state.id;
const name=location.state.username;
const handleSignup = async () => {
fetchUsers();
try {
const response = await fetch('http://localhost:3001/leave', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ id, leaveType, leaveDays}),
});
lOMoARcPSD|35 870736
setLeaveType(event.target.value);
if (event.target.value == "casual") {
setLeaveBalanceData(casual);
console.log(event.target.value,casual,leavebalanceData);
}
else if (event.target.value == "medical") {
setLeaveBalanceData(medical);
console.log(event.target.value,medical,leavebalanceData);
}
};
const handleLeaveDaysChange = (event) => {
setLeaveDays(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
const days = parseInt(leaveDays);
setLeaveDays("");
updateleave();
handleSignup();
};
const updateleave = async () => {
try {
const response = await fetch(`http://localhost:3001/leave/${id}`);
const data = await response.json();
if (response.ok) {
setUsers(data.leavebalance);
} else {
console.error('Failed to fetch users:', data.message);
}
} catch (error) {
console.error('Error during user fetch:', error.message);
}
};
/*const reset = () =>{
setLeaveBalanceData({
...leaveBalanceData,
[leaveType]: leaveBalanceData[leaveType] + 5,
});
}
<button type="submit" onClick={() => reset()}>Reset</button>
*/
return (
<div className="container">
<h1>Leave Management System</h1>
<div className="form-container">
<h2>Leave Application</h2>
<table><tr>
<td>ID</td><td>: </td><td>{location.state.id}</td></tr>
<tr> <td>Name</td><td>: </td><td>{name}</td></tr>
<tr><td>Message</td><td>: </td><td>{message}</td></tr>
</table>
<br></br>
<form onSubmit={handleSubmit}>
<select value={leaveType} onChange={handleLeaveTypeChange}>
lOMoARcPSD|35 870736
Leavemanagement.css
// LEAVEMANAGEMENT\frontend\src\components
@import url('https://fonts.googleapis.com/css2?
family=Roboto:wght@300;400;500&display=swap');
body {
font-family: 'Roboto', sans-serif;
margin: 0;
padding: 0;
background-color: #f5f5f5;
}
.container {
width: 80%;
margin: auto;
}
h1 {
text-align: center;
color: #4CAF50;
}
.form-container,
.balance-container {
background-color: #fff;
margin-top: 20px;
padding: 20px;
border-radius: 5px;
}
form input[type="number"]{
width: 98%;
lOMoARcPSD|35 870736
padding: 10px;
margin-bottom: 10px;
}
form select,
form button {
width: 100%;
padding: 10px;
margin-bottom: 10px;
}
form button {
background-color: #4CAF50;
color: #fff;
}
.balance-container {
animation-name: slideInRight;
animation-duration: .5s;
animation-fill-mode: both;
}
.form-container {
animation-name: slideInLeft;
animation-duration: .5s;
animation-fill-mode: both;
}
@keyframes slideInLeft {
from { transform: translateX(-100%); }
to { transform: translateX(0); }
}
@keyframes slideInRight {
from { transform: translateX(100%); }
to { transform: translateX(0); }
}
App.js
// LEAVEMANAGEMENT\leavemanagement\src
import React from 'react';
import Login from './components/Login';
import Signup from './components/Signup';
import Leavemanagement from './components/Leavemanagement';
import { Route,Routes} from "react-router-dom";
function App() {
return (
<div className="App">
<Routes>
<Route path='/' element={<Login />} />
<Route path='/signup' element={<Signup />} />
<Route path='/Leavemanagement' element={<Leavemanagement />} />
</Routes>
</div>
);
}
export default App;
index.js
//LEAVEMANAGEMENT\leavemanagement\src
lOMoARcPSD|35 870736
leave.js
// LEAVEMANAGEMENT\backend\models
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
casual: {
type: String,
},
medical: {
type: String,
},
});
const User = mongoose.model('User', userSchema);
module.exports = User;
login.js
//LEAVEMANAGEMENT\backend\routes
const express = require('express');
const router = express.Router();
//const bcrypt = require('bcrypt');
const User = require('../models/leave'); // Assuming you have a User model
router.post('/', async (req, res) => {
const { username, password } = req.body;
try {
const user = await User.findOne({ username });
if (!user) {
return res.status(401).json({ message: 'Authentication failed' });
}
//const isPasswordValid = await bcrypt.compare(password, user.password);
//if (!isPasswordValid) {
const userId = user._id;
const medical=user.medical;
const casual=user.casual;const username1=user.username;
if(password!=user.password){
lOMoARcPSD|35 870736
signup.js
// LEAVEMANAGEMENT\backend\routes
const express = require('express');
const router = express.Router();
//const bcrypt = require('bcrypt');
const User = require('../models/leave');
router.post('/', async (req, res) => {
try {
const { username, password } = req.body;
const existingUser = await User.findOne({ username });
if (existingUser) {
return res.status(409).json({ message: 'User already exists' });
}
const casual="5";
const medical="5";
//const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({
username,
//password: hashedPassword,
password,casual,medical,
});
await newUser.save();
res.status(201).json({ message: 'Signup successful' });
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;
leave.js
//LEAVEMANAGEMENT/backend/routes
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
//const bcrypt = require('bcrypt');
const User = require('../models/leave');
router.get('/:id', async (req, res) => {
try {
const user = await User.findById(req.params.id);
console.log(req.params.id);
if (!user) {
lOMoARcPSD|35 870736
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;
index.js
// LEAVEMANAGEMENT/backend/
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const dotenv = require('dotenv');
dotenv.config();
const app = express();
const port = process.env.PORT || 3001;
// MongoDB connection
mongoose.connect("mongodb://0.0.0.0:27017/ananth_s", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on('connected', () => {
console.log('Connected to MongoDB');
});
mongoose.connection.on('error', (err) => {
console.error('MongoDB connection error:', err);
});
// Middleware
app.use(cors());
app.use(bodyParser.json());
// Routes
const loginRouter = require('./routes/login');
const signupRouter = require('./routes/signup');
const leaveRouter = require('./routes/leave');
app.use('/login', loginRouter);
app.use('/signup', signupRouter);
app.use('/leave', leaveRouter);
// Start the server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);});
Output:
lOMoARcPSD|35 870736
lOMoARcPSD|35 870736
Result
Thus a user-friendly Leave Management System has been designed and implemented
successfully, for enhancing organizational efficiency and employee satisfaction for improved
leave application and tracking processes.
This experiment is mapped with PO1, PO2, PO3, PO4, PO5, PO6, PO7, PO8, PO9,
PO10, PO11, PO12 and PSO1, PSO2 & PSO3.
lOMoARcPSD|35 870736
7. Develop a simple dashboard for project management where the statuses of various
tasks are available. New tasks can be added and the status of existing tasks can be
changed among Pending, InProgress or Completed.
Aim
To design and implement a user-friendly project management dashboard that allows users
to add new tasks and update task statuses among Pending, InProgress, or Completed, thereby
facilitating efficient task tracking and management.
Steps to Implement:
Step 1: Setup Frontend and Backend Projects
• Create a new folder named "ProjectDashboard".
• Inside "ProjectDashboard", create folders named "frontend" and "backend".
Step 2: Setup Frontend Project
• Open a terminal and navigate to "ProjectDashboard/frontend".
• Create a new React.js application inside the "frontend" folder:
o npx create-react-app frontend
• Install required dependencies for React Router and CanvasJS:
o cd frontend
o npm i react-router-dom @canvasjs/react-charts
Step 3: Setup Backend Project
• Open a terminal and navigate to "ProjectDashboard/backend".
• Initialize a new Node.js application and install required dependencies:
o npm init -y
o npm install express mongoose body-parser cors dotenv
Step 4: Define Frontend Components
• Inside "frontend/src", create a folder named "components".
• Create the following components inside the "components" folder: Homepage.js,
Newproject.js, and Project.js.
• Implement the logic for each component based on the provided code.
Step 5: Define Backend Routes and Models
• Inside "backend", create folders named "models" and "routes".
• Define the MongoDB schema for the user in "models/user.js".
• Implement backend routes for handling homepage, new project creation, and
project update in "routes/homepage.js", "routes/newproject.js", and
"routes/project.js" respectively.
Step 6: Configure Express.js Server
• Create an index.js file inside the "backend" folder.
• Configure Express.js server, connect to MongoDB, and define routes in the
index.js file.
• Start the Express server:
o node index.js
Step 7: Integrate Frontend and Backend
• Inside "frontend/src", configure API endpoints to make requests to the backend server
(e.g., http://localhost:3001).
• Integrate frontend components with backend routes by making HTTP requests to the
corresponding endpoints.
Step 8: Run the Application
• Open two separate terminals: one for frontend and one for backend.
• Start the React development server for frontend:
o cd frontend
o npm start
• Start the Express.js server for backend (in the backend folder):
o cd backend
lOMoARcPSD|35 870736
o node index.js
Step 9: Access the Application
• Open a web browser and navigate to http://localhost:3000 to access the project
management dashboard.
Components Description:
FrontEnd
Homepage.js is a React functional component responsible for rendering the main page of
the project management dashboard. It includes features for searching existing projects and
creating new projects, allowing users to interact with the application through input fields,
buttons, and dynamic navigation.
Newproject.js is a React functional component representing the form for creating a new
project within the project management dashboard. It provides input fields for project details
such as name, aim, algorithm, program, and output. Users can input information, submit the
form, and receive feedback messages regarding the status of the project creation process.
App.js is the main component of the project management dashboard frontend. It defines
the application routes using React Router, allowing navigation between the homepage, new
project creation, and project details display components. It serves as the entry point for
rendering different sections of the dashboard based on user interactions and URL paths.
index.js is the entry file of the React application. It initializes the ReactDOM rendering
process, wrapping the App component with BrowserRouter to enable routing functionality.
The rendered content is injected into the HTML element with the ID 'root', effectively
displaying the entire project management dashboard in the web browser.
Backend
user.js is a Mongoose schema file defining the structure of the 'User' model for the
MongoDB database. It specifies the properties of a project, including project name, aim,
algorithm, program, and output. The schema ensures data consistency and integrity when
interacting with the MongoDB database in the backend of the project management system.
homepage.js is an Express route file handling POST requests related to project details
retrieval. It queries the MongoDB database for a specific project name, validates the
existence of the project, and returns relevant project information, including ID, aim,
algorithm, program, and output. If the project doesn't exist, it responds with an error message
or a success message with project details if found, ensuring proper communication between
the frontend and backend of the project management system.
newproject.js is an Express route file handling POST requests for creating new projects.
It checks if the project with the given name already exists in the MongoDB database. If not,
it creates a new project entry with provided details including project name, aim, algorithm,
program, and output. It responds with a success message if the project is added successfully
or an error message in case of server issues, ensuring proper project creation functionality in
the backend of the project management system.
project.js is an Express route file handling POST requests for updating existing projects.
It searches for a project by its name in the MongoDB database. If found, it updates the
lOMoARcPSD|35 870736
project details including aim, algorithm, program, and output. It responds with a success
message upon successful update, or an error message if the project is not found or if there
are server issues, ensuring proper project update functionality in the backend of the project
management system.
index.js is the main entry point of the backend application for the
PROJECTDASHBOARD. It configures an Express server, establishes a connection to
MongoDB, sets up middleware for handling JSON data and enabling CORS, defines routes
for homepage, new project creation, and project updates, and starts the server on a specified
port. This file orchestrates the backend functionality, ensuring proper communication
between the frontend and the database, allowing seamless management of projects within the
dashboard.
Homepage.js
// PROJECTDASHBOARD\frontend\src\components
import React, { useState } from 'react';
import { useNavigate } from "react-router-dom";
function Homepage() {
const [projectname, setProjectname] = useState('');
const [message, setMessage] = useState('');
const [ Objectid,setObjectid] = useState('');
const navigate=useNavigate();
function handlenewproject(){
navigate("/newproject")
}
const handleProject = async () => {
try {
const response = await fetch('http://localhost:3001/homepage', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ projectname}),
});
if (response.status === 200) {
const data = await response.json();
setObjectid(data.userId);
navigate("/project/",{state:
{id:data.userId,projectname:projectname,projectaim:data.projectaim,projectalgorithm:data.p
rojectalgorithm,projectprogram:data.projectprogram,projectoutput:data.projectoutput}});
} else {
const data = await response.json();
setMessage(data.message);
}
} catch (error) {
console.error(error);
}
};
return (<center>
<div><div>
<h2>Search Project</h2>
<input
type="text"
placeholder="Project"
lOMoARcPSD|35 870736
value={projectname}
onChange={(e) => setProjectname(e.target.value)}
/>
<button onClick={handleProject}>Submit</button>
<p>{message}</p>
<br></br>
</div>
<div >
<h1 onClick={handlenewproject}>Create Project</h1>
</div></div></center>
);
};
export default Homepage;
Newproject.js
// PROJECTDASHBOARD\frontend\src\components
import React, { useState } from 'react';
function Newproject() {
const [projectname, setProjectname] = useState('');
const [projectaim, setProjectaim] = useState('');
const [projectalgorithm, setProjectalgorithm] = useState('');
const [projectprogram, setProjectprogram] = useState('');
const [projectoutput, setProjectoutput] = useState('');
const [message, setMessage] = useState('');
const handleNewproject = async () => {
try {
const response = await fetch('http://localhost:3001/newproject', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body:
JSON.stringify({ projectname,projectaim,projectalgorithm,projectprogram,projectoutput }),
});
if (response.status === 201) {
const data = await response.json();
setMessage(data.message);
} else {
const data = await response.json();
setMessage(data.message);
}
} catch (error) {
console.error(error);
}
};
return (
<center> <div>
<h1>New Project</h1>
<h4>Project name</h4>
<input
type="text"
placeholder="Name"
value={projectname}
onChange={(e) => setProjectname(e.target.value)}
lOMoARcPSD|35 870736
/>
<h4>Aim</h4>
<textarea
type="text"
placeholder="Aim"
value={projectaim}
onChange={(e) => setProjectaim(e.target.value)} rows={5} cols={100}
/>
<h4>Algorithm</h4>
<textarea
type="text"
placeholder="Algorithm"
value={projectalgorithm}
onChange={(e) => setProjectalgorithm(e.target.value)} rows={10} cols={100}
/>
<h4>Program</h4>
<textarea type="text"
placeholder="Program"
value={projectprogram}
onChange={(e) => setProjectprogram(e.target.value)} rows={10} cols={100} />
<h4>Output</h4>
<textarea
type="text"
placeholder="Output"
value={projectoutput}
onChange={(e) => setProjectoutput(e.target.value)} rows={10} cols={100}
/>
<h1></h1>
<button onClick={handleNewproject}>Submit</button>
<p>{message}</p>
</div></center>
);
}
export default Newproject;
Project.js
// PROJECTDASHBOARD\frontend\src\components
import React, { useState } from 'react';
import CanvasJSReact from '@canvasjs/react-charts';
import { useLocation } from 'react-router-dom';
var CanvasJSChart = CanvasJSReact.CanvasJSChart;
function countWordsInParagraph(paragraph) {
const words = paragraph.trim().split(/\s+/);
var a = words.length;
if (paragraph === "") {
a = 0;
}
return a;
}
function percentage(a, b) {
return (a / b) * 100;
}
const Project = () => {
const [message, setMessage] = useState('');
lOMoARcPSD|35 870736
try {
const updatedProjectDetails = {
projectname: projectName,
projectaim: projectDetails.projectAim || projectAim,
projectalgorithm: projectDetails.projectAlgorithm || projectAlgorithm,
projectprogram: projectDetails.projectProgram || projectProgram,
projectoutput: projectDetails.projectOutput || projectOutput,
};
const response = await fetch('http://localhost:3001/project', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updatedProjectDetails),
});
if (response.status === 201) {
const data = await response.json();
setMessage(data.message);
} else {
const data = await response.json();
setMessage(data.message);
}
} catch (error) {
console.error(error);
}
};
return (
<center>
<div>
<h4>Project name</h4>
<input
type="text"
placeholder="Name"
value={projectName}
onChange={(e) => setProjectname(e.target.value)}
/>
<h4>Aim</h4>
<textarea
type="text"
placeholder="Aim"
value={projectDetails.projectAim || projectAim}
onChange={(e) => handleInputChange('projectAim', e.target.value)}
rows={5}
cols={100}
/>
<h4>Algorithm</h4>
<textarea
type="text"
placeholder="Algorithm"
value={projectDetails.projectAlgorithm || projectAlgorithm}
onChange={(e) => handleInputChange('projectAlgorithm', e.target.value)}
rows={10}
cols={100}
/>
lOMoARcPSD|35 870736
<h4>Program</h4>
<textarea
type="text"
placeholder="Program"
value={projectDetails.projectProgram || projectProgram}
onChange={(e) => handleInputChange('projectProgram', e.target.value)}
rows={10}
cols={100}
/>
<h4>Output</h4>
<textarea
type="text"
placeholder="Output"
value={projectDetails.projectOutput || projectOutput}
onChange={(e) => handleInputChange('projectOutput', e.target.value)}
rows={10}
cols={100}
/>
<br />
<button onClick={() => { handleNewproject(); }}>Update</button>
<p>{message}</p>
{chartVisible ? (
<div>
<CanvasJSChart options={options} />
<button onClick={handleHide}>Hide Report</button>
</div>
) : null}
{buttonVisible ? (
<div>
<button onClick={handlechart}>View Report</button>
</div>
) : null}
</div>
</center>
);
};
export default Project;
App.js
// PROJECTDASHBOARD\frontend \src
import React from 'react';
import Project from './components/Project';
import Homepage from './components/Homepage';
import Newproject from './components/Newproject';
import { Route,Routes} from "react-router-dom";
function App() {
return (
<div className="App">
<Routes>
<Route path='/' element={<Homepage />} />
<Route path='/newproject' element={<Newproject />} />
<Route path='/project' element={<Project />} /> {/* Add this route for the Project */}
</Routes>
lOMoARcPSD|35 870736
</div>
);
}
export default App;
index.js
// PROJECTDASHBOARD\frontend \src
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);
user.js
// PROJECTDASHBOARD\backend\models
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
projectname: { type: String, required: true},
projectaim: { type: String },
projectalgorithm: { type: String },
projectprogram: { type: String },
projectoutput: { type: String }
});
module.exports = mongoose.model('User', userSchema);
PROJECTDASHBOARD\backend\routes
homepage.js
const express = require('express');
const router = express.Router();
const UserModel = require('../models/user');
router.post('/', async (req, res) => {
const { projectname } = req.body;
try {
const user = await UserModel.findOne({ projectname });
if (!user) {
return res.status(401).json({ message: 'Project name is wrong' });
}
const userid=user.id;
const projectaim=user.projectaim;
const projectalgorithm=user.projectalgorithm;
const projectprogram=user.projectprogram;
const projectoutput=user.projectoutput;
res.status(200).json({ message: 'Project
successful',userid:userid,projectname,projectaim,projectalgorithm,projectprogram,projectout
put});
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;
lOMoARcPSD|35 870736
newproject.js
PROJECTDASHBOARD\backend\routes
const express = require('express');
const router = express.Router();
const User = require('../models/user');
router.post('/', async (req, res) => {
try {
const { projectname,projectaim,projectalgorithm,projectprogram,projectoutput } =
req.body;
const existingUser = await User.findOne({ projectname });
if (existingUser) {
return res.status(409).json({ message: 'Project already exists' });
}
const newUser = new User({
projectname,projectaim,projectalgorithm,projectprogram,projectoutput,
});
await newUser.save();
res.status(201).json({ message: 'Project added successful' });
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;
project.js
// PROJECTDASHBOARD/backend/routes
const express = require('express');
const router = express.Router();
const User = require('../models/user');
router.post('/', async (req, res) => {
try {
const { projectname, projectaim, projectalgorithm, projectprogram, projectoutput } =
req.body;
// Find the existing user by projectname
const existingUser = await User.findOne({ projectname});
if (!existingUser) {
return res.status(404).json({ message: 'Project not found' });
}
existingUser.projectaim = projectaim;
existingUser.projectalgorithm = projectalgorithm;
existingUser.projectprogram = projectprogram;
existingUser.projectoutput = projectoutput;
await existingUser.save();
res.status(200).json({ message: 'Project updated successfully' });
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;
index.js
lOMoARcPSD|35 870736
// PROJECTDASHBOARD/backend/
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const dotenv = require('dotenv');
const bodyParser = require('body-parser');
dotenv.config();
const app = express();
const port = process.env.PORT || 3001;
// MongoDB connection
mongoose.connect("mongodb://0.0.0.0:27017/gokul", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on('connected', () => {
console.log('Connected to MongoDB');
});
mongoose.connection.on('error', (err) => {
console.error('MongoDB connection error:', err);
});
// Middleware
app.use(cors());
app.use(bodyParser.json());
// Routes
const homepageRouter = require('./routes/homepage');
const newprojectRouter = require('./routes/newproject');
const projectRouter = require('./routes/project');
// const leaveRouter = require('./routes/leave');
app.use('/homepage', homepageRouter);
app.use('/newproject', newprojectRouter);
app.use('/project', projectRouter);
// app.use('/leave', leaveRouter);
// Start the server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Output:
lOMoARcPSD|35 870736
lOMoARcPSD|35 870736
Result
Thus the Project Management Dashboard has been developed for enabling users to
seamlessly add tasks and update statuses, enhancing task tracking and management
efficiency. The system streamlines project progress, fostering effective collaboration and
organization.
This experiment is mapped with PO1, PO2, PO3, PO4, PO5, PO6, PO7, PO8, PO9,
PO10, PO11, PO12 and PSO1, PSO2 & PSO3.
lOMoARcPSD|35 870736
Aim
To create an online survey application with a diverse collection of questions, allowing
users to answer random queries, enhancing their engagement and feedback participation.
Steps to Implement:
Step 1: Create a new folder named "SURVEY".
Step 2: Inside the "SURVEY" folder, create a frontend application:
Open a new terminal.
Navigate to the "SURVEY" folder (cd SURVEY).
Run the following commands:
o mkdir frontend
o cd frontend
o npx create-react-app frontend
o npm i react-router-dom
o npm install --save recharts
Step 3: Create the frontend components and styles:
Inside the "SURVEY/frontend/src" folder:
o Create a folder named "components".
o Inside the "components" folder, create three files: "Login.js", "Signup.js", and
"Survey.js".
o Create a CSS file for styling named "Survey.css".
o Copy and paste the respective code for each file.
Step 4: Set up the backend application:
Inside the "SURVEY" folder, create a backend application:
o Open a new terminal.
o Run the following commands:
mkdir backend
cd backend
npm init -y
npm install express mongoose body-parser bcrypt cors dotenv
mkdir models
mkdir routes
Step 5: Create backend routes and models:
Inside the "SURVEY/backend/models" folder, create a file named "survey.js". Copy
and paste the code for the mongoose schema.
Inside the "SURVEY/backend/routes" folder, create three files: "login.js", "signup.js",
and "survey.js". Copy and paste the respective code for each file.
Step 6: Set up the backend server:
Inside the "SURVEY/backend" folder, create a file named "index.js". Copy and paste
the code for setting up the Express server.
Step 7: Run the application:
Open two separate terminals.
In the first terminal, navigate to "SURVEY/frontend" and run npm start to start the
frontend application.
In the second terminal, navigate to "SURVEY/backend" and run node index.js to
start the backend server.
Step 8: Access the application:
Open a web browser and go to "http://localhost:3000" to access the frontend
application.
lOMoARcPSD|35 870736
Components Description:
FrontEnd
Login.js component handles user authentication by allowing users to enter their username
and password. It sends a request to the server for validation, and if successful, it redirects the
user to the survey page. Users can also navigate to the signup page by clicking the "Signup"
link.
Survey.js is a React component that displays a student survey form, allowing users to
provide feedback on instructors and class experiences. Users select staff members, answer
survey questions, and submit responses, which are then visualized using a bar chart.
Additionally, users can review previous survey responses.
Survey.css is a cascading style sheet (CSS) file defining the styles for the survey form
interface. It specifies the layout, colors, and animations, enhancing the visual presentation of
the survey components. The styles include responsive design, button formatting, and a fade-
in animation for smooth user experience.
App.js is the main entry point of the React application. It defines the routes for different
components (Login, Signup, and Survey) using the React Router library, allowing users to
navigate between login, signup, and survey interfaces within the application.
index.js serves as the entry point for the React application, rendering the main App
component within the BrowserRouter provided by React Router. It establishes the
connection between the React app and the HTML root element, allowing the application
components to be displayed in the specified DOM element.
Backend
survey.js defines a Mongoose schema for user data in a MongoDB database. It specifies
the structure of user documents, including fields like username, password, regno, and ratings
for different staff members (Manivannan, Nelson, Kosalairaman, MaheshKumar, Gobinath,
Umamaheswari). The schema is used to create a Mongoose model called User, which can be
manipulated to interact with the MongoDB database.
login.js is an Express.js route module responsible for handling user authentication during
login. It receives a POST request with username and password parameters, queries the
database for a matching user, and validates the provided password. If authentication
succeeds, it sends a JSON response indicating a successful login along with the user's ID,
name, and registration number. If authentication fails, it returns an error message and a 401
status code.
response sums, and retrieving user survey data by ID. The module communicates with the
MongoDB database using Mongoose to perform these operations.
index.js in the SURVEY/backend/ directory sets up an Express.js server that listens for
incoming requests on a specified port. It establishes a connection to a MongoDB database,
uses middleware for handling JSON data and enabling CORS, and defines routes for login,
signup, and survey-related operations, ensuring the backend functionality for the survey
application.
FrontEnd
Login.js
//SURVEY\frontend\src\components
import React, { useState } from 'react';
import { useNavigate } from "react-router-dom";
function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
const [objectid, setObjectid] = useState('');
const navigate = useNavigate();
function handlesignup() {
navigate("/signup")
}
const handleLogin = async () => {
try {
const response = await fetch('http://localhost:3001/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password }),
});
if (response.status === 200) {
const data = await response.json();
setObjectid(data.userId);
console.log("User ID : ", data.userId);
navigate("/Survey/", { state: { id: data.userId, name1: data.name, regno1:
data.regno } });
} else {
const data = await response.json();
setMessage(data.message);
}
} catch (error) {
console.error(error);
}
};
return (
<div>
<h2>Login</h2>
<p>{objectid}</p>
<input
type="text"
placeholder="Username"
lOMoARcPSD|35 870736
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button onClick={handleLogin}>Login</button>
<p>{message}</p>
<br>
</br>
<h1 onClick={handlesignup}>Signup</h1>
</div>
);
}
export default Login;
Signup.js
//SURVEY\frontend\src\components
import React, { useState } from 'react';
import { useNavigate } from "react-router-dom";
function Signup() {
const [username, setUsername] = useState('');
const [regno, setRegno] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
const navigate = useNavigate();
function handleLogin() {
navigate("/")
}
const handleSignup = async () => {
try {
const response = await fetch('http://localhost:3001/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, password, regno }),
});
if (response.status === 201) {
const data = await response.json();
setMessage(data.message);
} else {
const data = await response.json();
setMessage(data.message);
}
} catch (error) {
console.error(error);
}
};
lOMoARcPSD|35 870736
return (
<div>
<h2>Signup</h2>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<input
type="text"
placeholder="Reg No."
value={regno}
onChange={(e) => setRegno(e.target.value)}
/>
<button onClick={handleSignup}>Signup</button>
<p>{message}</p>
<br>
</br>
<h1 onClick={handleLogin}>Login</h1>
</div>
);
}
export default Signup;
Survey.js
// SURVEY\frontend\src\components
import React, { useState } from 'react';
import { BarChart, Bar, CartesianGrid, XAxis, YAxis } from 'recharts';
import './Survey.css'
import { useLocation } from "react-router-dom";
const Survey = () => {
const location = useLocation();
const id1 = location.state.id;
const staffNames = ["Manivannan", "Nelson", "Kosalairaman", "MaheshKumar",
"Gobinath", "Umamaheswari"];
const questions = [
{
id: 'q1',
question: '1. The class was very well organized',
},
{
id: 'q2',
question: '2. The instructor was very knowledgeable about the topic that was taught',
},
{
id: 'q3',
question: '3. The instructor was very good at communication',
lOMoARcPSD|35 870736
},
{
id: 'q4',
question: '4. The instructor was motivating and enthusiastic',
},
{
id: 'q5',
question: "5. The instructor's methods helped in understanding the topic better",
},
{
id: 'q6',
question: '6. The grading system was not biased',
},
{
id: 'q7',
question: '7. The facilities provided were up to your expectations',
},
{
id: 'q8',
question: '8. The teaching environment in the class helped in better learning',
},
{
id: 'q9',
question: '9. The hygiene was very well maintained at the facility',
},
{
id: 'q10',
question: '10. Is the instructor biased between three classes',
},
];
const choiceValues = {
'Strongly disagree': 1,
'Somewhat disagree': 2,
'Neutral': 3,
'Somewhat agree': 4,
'Strongly agree': 5,
};
console.log("id :", id1);
console.log("name:", location.state.name1);
console.log("regm=n: ", location.state.regno1);
const [staffMember, setStaffMember] = useState('');
const [Manivannan, setManivannan] = useState('');
const [Nelson, setNelson] = useState('');
const [Kosalairaman, setKosalairaman] = useState('');
const [MaheshKumar, setMaheshKumar] = useState('');
const [Gobinath, setGobinath] = useState('');
const [Umamaheswari, setUmamaheswari] = useState('');
const [responses, setResponses] = useState({});
const [message, setMessage] = useState('Welcome!!!!');
const handleStaffChange = (e) => {
setResponses({});
setStaffMember(e.target.value);
};
const data = [
lOMoARcPSD|35 870736
setResponses((prevResponses) => ({
...prevResponses,
[questionId]: value,
}));
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('Data to be submitted:', {
staffMember,
responses,
});
};
return (
<div className="container">
<h1>Student Survey Form</h1>
<form onSubmit={handleSubmit}>
<p>{message}</p>
<p>Name :{location.state.name1}</p>
<p>RegNo : {location.state.regno1}</p>
<div className="student-info">
<div className="form-group">
<label htmlFor="staffMember">Select Staff Member:</label>
<select
name="staffMember"
id="staffMember"
value={staffMember}
onChange={handleStaffChange}
>
<option value="">Select a staff member</option>
{staffNames.map((name, index) => (
<option key={index} value={name}>
{name}
</option>
))}
</select>
</div>
</div>
{questions.map((question) => (
<div key={question.id}>
<p>{question.question}</p>
<div className="options">
{Object.keys(choiceValues).map((choice) => (
<div key={choice}>
<label>
<input
type="radio"
name={question.id}
value={choice}
checked={responses[question.id] === choiceValues[choice]}
onChange={() => handleResponseChange(question.id, choice)}
/>
{choice}
</label>
</div>
lOMoARcPSD|35 870736
))}
</div>
</div>
))}
<button type="submit" className="btn btn-primary"
onClick={handleSubmit1}>
Submit
</button><br></br><br></br>
<button
type="button"
className="btn btn-secondary"
onClick={review}
>
Review
</button>
</form>
<br></br>
<BarChart width={700} height={600} data={data}>
<Bar dataKey="students" fill="green" />
<CartesianGrid stroke="#ccc" />
<XAxis dataKey="name" />
<YAxis domain={[0, 5]} />
</BarChart>
</div>
);
};
export default Survey;
Survey.css
// SURVEY\frontend\src\components
.container {
max-width: 700px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
animation: fade-in 1s ease-in-out;
}
@keyframes fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.btn {
background-color: #007bff;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
lOMoARcPSD|35 870736
);
}
export default App;
index.js
// SURVEY\frontend\src
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);
Backend
survey.js
//SURVEY\backend\models
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
regno: {
lOMoARcPSD|35 870736
type: String,
},
Manivannan: {
type: String,
},
Nelson: {
type: String,
},
Kosalairaman: {
type: String,
},
MaheshKumar: {
type: String,
},
Gobinath: {
type: String,
},
Umamaheswari: {
type: String,
},
});
const User = mongoose.model('User', userSchema);
module.exports = User;
login.js
SURVEY\backend\routes
const express = require('express');
const router = express.Router();
//const bcrypt = require('bcrypt');
const User = require('../models/survey'); // Assuming you have a User model
router.post('/', async (req, res) => {
const { username, password } = req.body;
try {
const user = await User.findOne({ username });
if (!user) {
return res.status(401).json({ message: 'Authentication failed' });
}
//const isPasswordValid = await bcrypt.compare(password, user.password);
//if (!isPasswordValid) {
const userId = user._id;
const name = user.username;
const regno = user.regno;
if(password!=user.password){
return res.status(401).json({ message: 'Authentication failed' });
}
// Handle successful login
res.status(200).json({ message: 'Login successful',userId,name,regno});
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;
lOMoARcPSD|35 870736
signup.js
// SURVEY\backend\routes
const express = require('express');
const router = express.Router();
//const bcrypt = require('bcrypt');
const User = require('../models/survey');
router.post('/', async (req, res) => {
try {
const { username, password,regno } = req.body;
const existingUser = await User.findOne({ username });
if (existingUser) {
return res.status(409).json({ message: 'User already exists' });
}
const Manivannan="0";
const Nelson="0";
const Kosalairaman="0";
const MaheshKumar="0";
const Gobinath="0";
const Umamaheswari="0";
console.log(username,
//password: hashedPassword,
password,regno,Manivannan,Nelson,Kosalairaman,MaheshKumar,Gobinath,Umamahes
wari);
//const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({
username,
//password: hashedPassword,
password,regno,Manivannan,Nelson,Kosalairaman,MaheshKumar,Gobinath,Umamahes
wari,
});
await newUser.save();
res.status(201).json({ message: 'Signup successful' });
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;
survey.js
// SURVEY/backend/routes
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const User = require('../models/survey');
router.put('/', async (req, res) => {
try {
const { id1, staffMember, responses } = req.body;
console.log("id = ", id1);
const existingUser = await User.findById(id1);
const user = await User.findById(id1);
if (!existingUser) {
return res.status(409).json({ message: 'User found' });
}
lOMoARcPSD|35 870736
}
else if (staffMember == "Umamaheswari") {
console.log("if staf 6 =", user.Umamaheswari);
const Umamaheswari = calculateSumOfResponses(responses);
if (staffMember == "Umamaheswari" && user.Umamaheswari == "0") {
console.log("Sum = ", Umamaheswari);
updatedUser = await User.findByIdAndUpdate(
id1,
{ Umamaheswari },
{ new: true }
);
if (!updatedUser) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json({ message: 'Update successful', user: updatedUser });
}
else {
console.log("already filed");
res.json({ message: 'limit exeeded' });
}
}
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
router.get('/:id', async (req, res) => {
try {
const user = await User.findById(req.params.id);
console.log(req.params.id);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json(user);
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
});
module.exports = router;
index.js
// SURVEY/backend/
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const dotenv = require('dotenv');
dotenv.config();
const app = express();
const port = process.env.PORT || 3001;
// MongoDB connection
mongoose.connect("mongodb://0.0.0.0:27017/ananth", {
useNewUrlParser: true,
lOMoARcPSD|35 870736
useUnifiedTopology: true,
});
mongoose.connection.on('connected', () => {
console.log('Connected to MongoDB');
});
mongoose.connection.on('error', (err) => {
console.error('MongoDB connection error:', err);
});
// Middleware
app.use(cors());
app.use(bodyParser.json());
// Routes
const loginRouter = require('./routes/login');
const signupRouter = require('./routes/signup');
const surveyRouter = require('./routes/survey');
app.use('/login', loginRouter);
app.use('/signup', signupRouter);
app.use('/survey', surveyRouter);
// Start the server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Output:
lOMoARcPSD|35 870736
lOMoARcPSD|35 870736
Result
Thus the interactive online survey platform has been developed successfully, for enabling
users to answer diverse questions randomly, promoting active engagement and providing
valuable feedback for academic research purposes.
This experiment is mapped with PO1, PO2, PO3, PO4, PO5, PO6, PO7, PO8, PO9,
PO10, PO11, PO12 and PSO1, PSO2 & PSO3.