EX.
NO:01
IMPLEMENT COMPONENT BASED UI WITH PROPS,
STATES AND EVENT HANDLING
DATE: 30/6/25
AIM:
To implement the component based UI with props, states and event \handling.
PROCEDURE:
• Step 1: Set Up the React Project
• Step 2: Create the Component Structure
• Step 3: Implement the Greeting Component (Props)
• Step 4: Implement the Counter Component (State & Event Handling)
• Step 5: Combine Components in [Link]
• Step 6: Run the Application
• Step 7: Test the Output
• Step 8: (Optional) Add Styling and Improvement
Code:
import React, { useState } from "react";
// Greeting Component (uses props)
function Greeting({ name }) {
return <h2>Hello, {name}! ◻</h2>;
}
// Counter Component (uses state & event handling)
function Counter() {
const [count, setCount] = useState(0);
const handleIncrease = () => setCount(count + 1);
const handleDecrease = () => setCount(count - 1);
return (
<div>
<h3>Count: {count}</h3>
<button onClick={handleIncrease}>➕Increase</button>
<button onClick={handleDecrease}>➖Decrease</button>
ASMITHA D - 71812201024
</div>
);
}
// Main App Component
function App() {
return (
<div style={{ padding: "20px", fontFamily: "Arial" }}>
<h1>React Component-Based UI</h1>
<Greeting name="Asmitha" />
<Counter />
</div>
);
}
OUTPUT:
RESULT:
Thus, successfully implemented Component - Based UI with Props, States and Event handling.
ASMITHA D - 71812201024
[Link]
DEVELOP A FORM WITH VALIDATION AND
DATE: 07/07/25 CONDITIONAL RENDERING
AIM:
To develop a form with validation and conditional rendering using HTML.
PROCEDER:
• Step 1: Create a Project Folder
• Step 2: Create Required Files
• Step 3: Write HTML Code
• Step 4: Style the Form with CSS
• Step 5: Add Validation and Conditional Rendering with JavaScript
• Step 6: Test the Webpage
• Step 7 (Optional): Host the Project Online
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>User Registration Form</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
padding-top: 60px;
}
.container {
background: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 0 10px #aaa;
width: 300px;
ASMITHA D - 71812201024
}
h2 {
text-align: center;
}
label {
display: block;
margin-top: 10px;
}
input, button {
width: 100%;
padding: 8px;
margin-top: 5px;
}
button {
background-color: #28a745;
color: white;
border: none;
margin-top: 15px;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
.hidden {
display: none;
}
#message {
margin-top: 20px;
padding: 10px;
background-color: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
border-radius: 5px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
ASMITHA D - 71812201024
<h2>User Registration</h2>
<form id="userForm">
<label for="name">Name:</label>
<input type="text" id="name" required />
<label for="email">Email:</label>
<input type="email" id="email" required />
<label for="age">Age:</label>
<input type="number" id="age" required />
<button type="submit">Submit</button>
</form>
<div id="message" class="hidden"> Form submitted successfully!</div>
</div>
<script>
[Link]("userForm").addEventListener("submit", function (e) {
[Link]();
const name = [Link]("name").[Link]();
const email = [Link]("email").[Link]();
const age = [Link]("age").[Link]();
const message = [Link]("message");
if (name && [Link]("@") && !isNaN(age) && age > 0) {
[Link]("hidden"); // Conditional rendering
} else {
alert("Please enter valid details in all fields.");
}
});
</script>
</body>
</html>
ASMITHA D - 71812201024
OUTPUT:
RESULT:
Successfully created the validation and conditional rendering through HTML.
ASMITHA D - 71812201024
[Link]
PERFORM CRUD OPERATION USING
DATE: 12/07/25
MONGODB WITH MONGOOSE
AIM:
To perform crud operations using MongoDB with Mongoose
PROCEDURE:
• Install [Link] and MongoDB.
• Start MongoDB server using mongod.
• Create a folder exp2a.
• Create file [Link] with CRUD code.
• Run npm init -y.
• Run npm install mongoose.
• Run node [Link].
• Check the output for create, read, update, and delete operations.
CODE:
const mongoose = require("mongoose");
// connect to MongoDB
[Link]("mongodb://[Link]:27017/mydb")
.then(() => [Link]("Connected to MongoDB"))
.catch(err => [Link](err));
// define schema
const userSchema = new [Link]({
name: String,
age: Number
});
ASMITHA D - 71812201024
// model
const User = [Link]("User", userSchema);
// run CRUD
async function runCRUD() {
// CREATE
const user = await [Link]({ name: "Rahul", age: 22 });
[Link]("Created:", user);
// READ
const found = await [Link]({ name: "Rahul" });
[Link]("Found:", found);
// UPDATE
const updated = await [Link]({ name: "Rahul" }, { $set: { age: 23 } });
[Link]("Updated:", updated);
// DELETE
const deleted = await [Link]({ name: "Rahul" });
[Link]("Deleted:", deleted);
[Link]();
}printf(“Arun - 71812401034 \nProducer–Consumer Problem using Semaphore\n"); printf("\n\n1.
Produce\n2. Consume\n3. Exit");
while (1) {
printf("\nEnter your choice: ");
scanf("%d", &n);
switch (n) {
case 1:
if ((mutex == 1) && (empty != 0))
producer();
else
printf("\nBuffer is full!");
break;
case 2:
if ((mutex == 1) && (full != 0))
consumer();
else
printf("\nBuffer is empty!");
break;
case 3:
exit(0);
ASMITHA D - 71812201024
break;
default:
printf("\nInvalid choice!");
}
}
}
OUTPUT:
RESULT:
In this program successfully performed the CRUD operation.
ASMITHA D - 71812201024
[Link]
DESIGN AND IMPLEMENT SCHEMA
DATE: 21/07/25
VALIDATION AND INDEXING
AIM:
To design and implement the schema validation and indexing using mongoose.
PROCEDURE:
• Create a folder exp2b.
• Create file [Link] with schema validation and indexing code.
• Run npm init -y.
• Run npm install mongoose.
• Start MongoDB server using mongod.
• Run node [Link].
• Check the output for valid user creation, validation error, and indexing on email.
CODE:
const mongoose = require("mongoose");
// connect to MongoDB
[Link]("mongodb://[Link]:27017/mydb")
.then(() => [Link]("Connected to MongoDB"))
.catch(err => [Link](err));
// schema with validation + index
const userSchema = new [Link]({
name: { type: String, required: true },
age: { type: Number, min: 18 },
email: { type: String, required: true, unique: true } // validation + index
});
ASMITHA D - 71812201024
// model
const User = [Link]("User", userSchema);
async function runValidation() {
try {
// valid user
const user = await [Link]({ name: "Rahul", age: 22, email: "rahul@[Link]" });
[Link]("Valid user created:", user);
// invalid user (missing email)
await [Link]({ name: "TestUser", age: 20 });
} catch (err) {
[Link]("Validation error:", [Link]);
}
[Link]();
}
runValidation();printf(“Arun - 71812401034 \nProducer–Consumer Problem using Semaphore\n");
printf("\n\n1. Produce\n2. Consume\n3. Exit");
while (1) {
printf("\nEnter your choice: ");
scanf("%d", &n);
switch (n) {
case 1:
if ((mutex == 1) && (empty != 0))
producer();
else
printf("\nBuffer is full!");
break;
case 2:
if ((mutex == 1) && (full != 0))
consumer();
else
printf("\nBuffer is empty!");
break;
case 3:
exit(0);
break;
default:
printf("\nInvalid choice!");
}
ASMITHA D - 71812201024
}
}
OUTPUT:
RESULT:
Successfully designed and implemented schema validation and indexing.
ASMITHA D - 71812201024
[Link]
CREATE A RESTFUL API WITH ROUTING AND
DATE: 28/07/25
HTTP METHODS
AIM:
To create a restful API with routing and HTTP methods
PROCEDURE:
• nstall [Link] and npm.
• Make a new folder.
• Create file [Link] and paste the Part A code.
• Run in terminal:
• npm init -y
• npm install express
• node [Link]
• Open Postman/browser → test with:
• GET [Link]
• POST [Link] (add user)
• PUT and DELETE for update/delete.
CODE:
[Link]
const express = require("express");
const app = express();
[Link]([Link]());
let users = [
{ id: 1, name: "Rahul" },
{ id: 2, name: "Priya" }
];
// GET all users
[Link]("/users", (req, res) => {
[Link](users);
});
// GET user by id
ASMITHA D - 71812201024
[Link]("/users/:id", (req, res) => {
const user = [Link](u => [Link] == [Link]);
user ? [Link](user) : [Link](404).json({ error: "User not found" });
});
// POST add user
[Link]("/users", (req, res) => {
const newUser = { id: [Link] + 1, name: [Link] };
[Link](newUser);
[Link](201).json(newUser);
});
// PUT update user
[Link]("/users/:id", (req, res) => {
const user = [Link](u => [Link] == [Link]);
if (user) {
[Link] = [Link];
[Link](user);
} else {
[Link](404).json({ error: "User not found" });
}
});
// DELETE user
[Link]("/users/:id", (req, res) => {
users = [Link](u => [Link] != [Link]);
[Link]({ message: "User deleted" });
});
// Start server
[Link](3000, () => [Link]("Part A API running on [Link]
ASMITHA D - 71812201024
OUTPUT:
ASMITHA D - 71812201024
ASMITHA D - 71812201024
RESULT:
Successfully created restful API with routing and HTTP methods.
ASMITHA D - 71812201024
EXP NO:6
Implement error handling and middleware for
DATE: 04/08/25 secure API endpoints
AIM:
To implement error handling and middleware for secure API endpoints.
PROCEDURE:
STEP 1:Configure MongoDB Connection:
Create a config/[Link] file and connect the Express application to MongoDB using
Mongoose with environment variables for secure configuration.
STEP 2:Design User Model:
Create a [Link] file in the models folder to define the user schema with fields
— name, email, and password, along with timestamps.
STEP 3:Implement Middleware:
Add [Link] for global error handling and [Link] for verifying
JWT tokens to protect private routes.
STEP 4:Develop User Controller and Routes:
Create [Link] to handle user registration, login, and profile fetching. Define
routes in [Link] to map these functionalities.
STEP 5:Setup Server and Run Application:
Initialize the server in [Link], connect all routes and middleware, and start the
application using npx nodemon [Link] to test API endpoints.
CODE:
config/[Link]
const mongoose = require("mongoose");
const connectDB = async () => {
try {
const conn = await [Link]([Link].MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
ASMITHA D - 71812201024
[Link](`MongoDB Connected: ${[Link]}`);
} catch (error) {
[Link](`Error: ${[Link]}`);
[Link](1);
}
};
[Link] = connectDB;
models/[Link]
const mongoose = require("mongoose");
const userSchema = [Link](
{
name: {
type: String,
required: [true, "Please add a name"],
},
email: {
type: String,
required: [true, "Please add an email"],
unique: true,
},
password: {
type: String,
required: [true, "Please add a password"],
},
},
{
ASMITHA D - 71812201024
timestamps: true,
}
);
[Link] = [Link]("User", userSchema);
[Link]
const notFound = (req, res, next) => {
const error = new Error(`Not Found - ${[Link]}`);
[Link](404);
next(error);
};
const errorHandler = (err, req, res, next) => {
const statusCode = [Link] === 200 ? 500 : [Link];
[Link](statusCode);
[Link]({
message: [Link],
stack: [Link].NODE_ENV === "production" ? null : [Link],
});
};
[Link] = { notFound, errorHandler };
middleware/[Link]
const jwt = require("jsonwebtoken");
const User = require("../models/userModel");
const protect = async (req, res, next) => {
let token;
if ([Link] && [Link]("Bearer")) {
try {
token = [Link](" ")[1];
ASMITHA D - 71812201024
const decoded = [Link](token, [Link].JWT_SECRET);
[Link] = await [Link]([Link]).select("-password");
next();
} catch (error) {
[Link](401);
throw new Error("Not authorized, token failed");
}
}
if (!token) {
[Link](401);
throw new Error("Not authorized, no token");
}
};
[Link] = { protect };
[Link]
const asyncHandler = require("express-async-handler");
const User = require("../models/userModel");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const generateToken = (id) => {
return [Link]({ id }, [Link].JWT_SECRET, { expiresIn: "30d" });
};
const registerUser = asyncHandler(async (req, res) => {
const { name, email, password } = [Link];
const userExists = await [Link]({ email });
if (userExists) {
[Link](400);
throw new Error("User already exists");
ASMITHA D - 71812201024
}
const salt = await [Link](10);
const hashedPassword = await [Link](password, salt);
const user = await [Link]({ name, email, password: hashedPassword });
if (user) {
[Link](201).json({
_id: [Link],
name: [Link],
email: [Link],
token: generateToken(user._id),
});
} else {
[Link](400);
throw new Error("Invalid user data");
}
});
const loginUser = asyncHandler(async (req, res) => {
const { email, password } = [Link];
const user = await [Link]({ email });
if (user && (await [Link](password, [Link]))) {
[Link]({
_id: [Link],
name: [Link],
email: [Link],
token: generateToken(user._id),
});
} else {
ASMITHA D - 71812201024
[Link](401);
throw new Error("Invalid email or password");
}
});
const getUserProfile = asyncHandler(async (req, res) => {
const user = [Link];
[Link]({
_id: [Link],
name: [Link],
email: [Link],
});
});
[Link] = { registerUser, loginUser, getUserProfile };
[Link]
const express = require("express");
const router = [Link]();
const { registerUser, loginUser, getUserProfile } =
require("../controllers/userController");
const { protect } = require("../middleware/authMiddleware");
[Link]("/register", registerUser);
[Link]("/login", loginUser);
[Link]("/profile", protect, getUserProfile);
[Link] = router;
[Link]
const express = require("express");
const dotenv = require("dotenv");
ASMITHA D - 71812201024
const connectDB = require("./config/db");
const userRoutes = require("./routes/userRoutes");
const { notFound, errorHandler } = require("./middleware/errorMiddleware");
[Link]();
connectDB();
const app = express();
[Link]([Link]()); // Parse JSON bodies
[Link]("/", (req, res) => [Link]("API is running..."));
[Link]("/api/users", userRoutes);
[Link](notFound);
[Link](errorHandler);
const PORT = [Link] || 5000;
[Link](PORT, () => [Link](`Server running on port ${PORT}`));
.env
PORT=5000
MONGO_URI=your_mongo_connection_string
JWT_SECRET=your_jwt_secret_key
NODE_ENV=development
Run the Server
npx nodemon [Link]
ASMITHA D - 71812201024
OUTPUT:
ASMITHA D - 71812201024
RESULT:
The API endpoints were successfully secured using middleware. Error
handling worked properly for invalid routes and unauthorized access. The middleware
helped improve the security and stability of the API.
ASMITHA D - 71812201024
[Link]
BUILD A BASIC SERVER WITH [Link]
DATE: 18/08/25
MODULES AND EVENTS
AIM:
To build a basic server with [Link] modules and events.
PROCEDURE:
• Install [Link]
• Create a project folder
• Create server_a.js file
• Open terminal and navigate to folder
• Run the server
• Open browser and test the server
CODE:
// server_a.js
const http = require("http");
const EventEmitter = require("events");
// Create an EventEmitter instance
const myEmitter = new EventEmitter();
// Define a custom event
[Link]("requestReceived", (url) => {
[Link](`Request received at: ${url}`);
});
// Create the server
const server = [Link]((req, res) => {
// Emit custom event
[Link]("requestReceived", [Link]);
ASMITHA D - 71812201024
[Link](200, { "Content-Type": "text/plain" });
[Link]("Hello! This is Part (a): Basic [Link] server with events.\n");
});
// Start server
[Link](3000, () => {
[Link]("Part (a) server running at [Link]
});
OUTPUT:
RESULT:
Successfully created a basic server using [Link] modules and events.
ASMITHA D - 71812201024
EXP NO:8
Integrate file handling, form data processing, and
DATE: 01/09/25 console utilities
AIM
To Integrate file handling, form data processing, and console utilities.
PROCEDURE
STEP 1:Create Folder Structure:
• Create a folder named uploads to store uploaded files.
• Create [Link] and .env files for server code and environment variables.
STEP 2:Setup Express Server:
• Initialize Express app, configure middleware for JSON and URL-encoded data,
and use Morgan to log HTTP requests.
STEP 3:Configure File Uploads:
• Use Multer to configure storage for uploaded files with unique filenames.
• Define the upload handler using [Link]('file').
STEP 4:Create Routes:
• Add a GET route / to test server.
• Add a POST route /upload to handle form submission and file upload, logging
data to the console.
STEP 5:Run Server:
• Start the server using node [Link] and test by submitting form data and files.
CODE
[Link]
const express = require('express');
const multer = require('multer');
const morgan = require('morgan');
const dotenv = require('dotenv');
const path = require('path');
ASMITHA D - 71812201024
[Link]();
const app = express();
[Link]([Link]());
[Link]([Link]({ extended: true }));
[Link](morgan('dev'));
const storage = [Link]({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, [Link]() + [Link]([Link])); // unique name
}
});
const upload = multer({ storage: storage });
[Link]('/', (req, res) => {
[Link]('Welcome to File + Form + Console Integration ');
});
[Link]('/upload', [Link]('file'), (req, res) => {
[Link]('Form Data:', [Link]);
[Link]('Uploaded File:', [Link]);
if (![Link]) {
return [Link](400).json({ message: 'No file uploaded' });
}
[Link]({
message: 'File uploaded successfully!',
formData: [Link],
fileInfo: [Link]
ASMITHA D - 71812201024
});
});
const PORT = [Link] || 5000;
[Link](PORT, () => [Link](`Server running on [Link]
.env
PORT=5000
Run Command
node [Link]
OUTPUT
RESULT
The server successfully handled form submissions and file uploads.
Uploaded files were saved in the uploads folder, and form data and file details were
displayed in the console.
ASMITHA D - 71812201024
EXP NO:9
Connect frontend with backend for data exchange
DATE: 15/09/25
AIM
To Connect frontend with backend for data exchange.
PROCEDURE
Setup Backend:
• Create a [Link] file with Express and connect it to MongoDB using
Mongoose.
• Add middleware (cors and [Link]()) for handling requests.
• Define a sample route /api/data that returns JSON data.
• Add .env file with MONGO_URI and PORT.
• Update [Link] scripts to run the server with nodemon.
• Start backend using npm run server.
Setup Frontend:
• Navigate to the frontend folder and create a React app using npx create-react-
app ..
• Install Axios for HTTP requests.
• Modify [Link] to fetch data from backend route [Link]
and display it.
• Start frontend using npm start and verify the data is displayed.
CODE
[Link]
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();
const app = express();
ASMITHA D - 71812201024
[Link](cors());
[Link]([Link]());
[Link]([Link].MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => [Link]('MongoDB Connected '))
.catch(err => [Link](err));
[Link]('/api/data', (req, res) => {
[Link]({ message: "Hello from backend!" });
});
const PORT = [Link] || 5000;
[Link](PORT, () => [Link](`Server running on [Link]
Backend – .env
MONGO_URI=your_mongodb_connection_string_here
PORT=5000
[Link] scripts
"scripts": {
"start": "node [Link]",
"server": "nodemon [Link]"
}
[Link]
import { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState('');
useEffect(() => {
ASMITHA D - 71812201024
[Link]('[Link]
.then(res => setData([Link]))
.catch(err => [Link](err));
}, []);
return (
<div>
<h1>Data from Backend:</h1>
<p>{data}</p>
</div>
);
}
export default App;
Run Commands:
npm run server
npm start
OUTPUT
ASMITHA D - 71812201024
RESULT
The frontend React app successfully fetched data from the [Link] backend.
The message "Data from backend!" was displayed in the browser, confirming proper
communication between frontend and backend.
ASMITHA D - 71812201024
[Link]
DEVELOP AND DEPLOY AN APPLICATION WITH
DATE: 22/09/25 DATABASE INEGRATION USING DOCKER
AIM:
To develop and containerize a full-stack MERN application using Docker and docker-compose for seamless
multi-container deployment.
PROCEDURE:
• Set up Project Structure
• Create Backend ([Link] + Express + MongoDB)
• Create Frontend (React)
• Write API Routes for CRUD Operations
• Create Dockerfiles for Backend and Frontend
• Write [Link] for Multi-Container Setup
• Set Environment Variables (.env file)
• Build and Run Docker Containers
• Test Application in Browser
• Optional: Connect to MongoDB GUI Tool
CODE:
[Link]
{
"name": "backend",
"version": "1.0.0",
"main": "[Link]",
"scripts": {
"start": "node [Link]"
},
"dependencies": {
"express": "^4.18.2",
"mongoose": "^7.3.1",
"cors": "^2.8.5"
}
}
[Link]
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
ASMITHA D - 71812201024
const usersRoute = require('./routes/users');
require('dotenv').config();
const app = express();
[Link](cors());
[Link]([Link]());
[Link]('/api/users', usersRoute);
const PORT = [Link] || 5000;
[Link]([Link].MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
[Link]("MongoDB connected");
[Link](PORT, () => [Link](`Server running on port ${PORT}`));
}).catch(err => [Link](err));
/routes/[Link]
const express = require('express');
const router = [Link]();
const mongoose = require('mongoose');
const userSchema = new [Link]({
name: String,
email: String
});
const User = [Link]('User', userSchema);
[Link]('/', async (req, res) => {
const users = await [Link]();
[Link](users);
});
[Link]('/', async (req, res) => {
const user = new User([Link]);
await [Link]();
[Link](user);
});
[Link] = router;
Frontend: React
{
"name": "frontend",
"version": "1.0.0",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build"
},
ASMITHA D - 71812201024
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "^5.0.1",
"axios": "^1.6.0"
}
}
Docker Setup
version: '3'
services:
mongo:
image: mongo
container_name: mongo
ports:
- "27017:27017"
environment:
MONGO_INITDB_DATABASE: testdb
backend:
build: ./backend
container_name: backend
ports:
- "5000:5000"
environment:
- MONGO_URI=mongodb://mongo:27017/testdb
depends_on:
- mongo
frontend:
build: ./frontend
container_name: frontend
ports:
- "3000:3000"
depends_on:
- backend
backend/Dockerfile
FROM node:18
WORKDIR /app
COPY [Link] .
RUN npm install
COPY . .
EXPOSE 5000
CMD ["npm", "start"]
frontend/Dockerfile
FROM node:18
WORKDIR /app
COPY [Link] .
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
ASMITHA D - 71812201024
OUTPUT:
RESULT:
The backend, frontend, and MongoDB services successfully ran in isolated containers, enabling CRUD
operations with persistent data storage and frontend interaction.
ASMITHA D - 71812201024