0% found this document useful (0 votes)
78 views105 pages

FSD2 Record - Final

The document outlines the Full Stack Development-2 Lab curriculum for the III B.Tech I Semester at Sir C.R. Reddy College of Engineering, detailing various experiments in TypeScript, Express JS, ReactJS, and MongoDB. It includes a certification of practical work, an index of experiments, and sample programs demonstrating key concepts in each area. The curriculum is designed to provide hands-on experience with essential technologies for web development.

Uploaded by

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

FSD2 Record - Final

The document outlines the Full Stack Development-2 Lab curriculum for the III B.Tech I Semester at Sir C.R. Reddy College of Engineering, detailing various experiments in TypeScript, Express JS, ReactJS, and MongoDB. It includes a certification of practical work, an index of experiments, and sample programs demonstrating key concepts in each area. The curriculum is designed to provide hands-on experience with essential technologies for web development.

Uploaded by

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

SIR C.R.

REDDY COLLEGE OF ENGINEERING, ELURU


(Approved by AICTE, New Delhi and Affiliated to JNTUK)
ACCREDITED By NBA, NAAC –‘A’ Grade

VATLURU, ELURU-534007
DEPARTMENT OF ARTIFICIAL INTELLIGENCE & MACHINE LEARNING

FULL STACK DEVELOPMENT-2 LAB


(R2331056)

III B. Tech I Semester


R23 Regulation
Academic Year: 2025-2026
SIR C.R.REDDY COLLEGE OF ENGINEERING, ELURU
DEPARTMENT OF ARTIFICIAL INTELLIGENCE & MACHINE LEARNING

This is to certify that this book is a bonafide record practical work done
in Full Stack Development – 2 Laboratory in I semester of III year B.Tech
COMPUTER SCIENCE AND ENGINEERING during academic year 2025-
2026.
 Total Number of Experiments held :
 Total Number of Experiments done :

Name of the Student : __________________________________________________

Register Number :

LAB INCHARGE HEAD OF DEPARTMENT

EXTERNAL EXAMINER
INDEX
S.NO NAME OF THE DATE GRADE SIGN
EXPERIMENT
1 Typescript
a. Write a program to understand simple and
special types.
b. Write a program to understand function
parameter and return types.
c. Write a program to show the importance
with Arrow function, Use optional, default
and REST parameters.
d. Write a program to understand the
working of typescript with class,
constructor, properties, methods and
access specifiers.
e. Write a program to understand the
working of namespaces and modules.
f. Write a program to understand generics
with variables, functions and constraints.
2 Express JS – Routing, HTTP
Methods, Middleware.
a. Write a program to define a route,
Handling Routes, Route Parameters,
Query Parameters and URL building.
b. Write a program to accept data,
retrieve data and delete a specified
resource using http methods.
c. Write a program to show the working
of the middleware.
3 Express JS – Templating, Form Data
a. Write a program using templating
engine.
b. Write a program to work with
form data.

4. ExpressJS – Cookies, Sessions,


Authentication
a. Write a program for session management
using cookies and sessions.
b. Write a program to work with form data.
5 Express JS – Database, RESTful APIs
a. Write a program to connect
MongoDB database using Mangoose
and perform CRUD operations.
b. Write a program to develop a single
page application using RESTful APIs.

6 ReactJS – Render HTML, JSX,


Components – functions & Class

a. Write a program to render HTML to


a web page.
b. Write a program for writing markup
with JSX.
c. Write a program for creating and
nesting components (function and
class).
7 ReactJS – Props and States, Styles,
Respond to Events
a. Write a program to work with props
and states.
b. Write a program to add styles (CSS &
Saas Styling) and display data.
c. Write a program for responding to
events.

8 ReactJS – Conditional Rendering,


Rendering Lists, React Forms
a. Write a program for conditional
rendering.
b. Write a program for rendering lists.
c. Write a program for working with
different form fields using react
forms.
9 ReactJS – React Router, Updating the
Screen
a. Write a program for routing to
different pages using react router.
b. Write a program for updating the
screen.
10 ReactJS – Hooks, Sharing data
between Components
a. Write a program to understand the
importance of using hooks.
b. Write a program for sharing data
between components.
11 ReactJS Applications – To-do list and
Quiz
a. Design to-do list application.

12 MongoDB – Installation, Configuration,


CRUD operations
a. Install MongoDB and configure
ATLAS
b. Write MongoDB queries to perform
CRUD operations on document using
insert(), find(), update(), remove().

13 MongoDB – Databases, Collections


and Records
a. Write MongoDB queries to Create
and drop databases and collections.
b. Write MongoDB queries to work with
records using find(), limit(), sort(),
createIndex(), aggregate().

14 Augmented Programs: (Any 2 must be


completed)
a. Design a to-do list application using
NodeJS and ExpressJS.
b. Design a Quiz app using ReactJS.
c. Complete the MongoDB certification
from MongoDB University website.
EXPERIMENT – 1

1.TypeScript

a. write aprogram to understand simple and special types.

Program:

// SIMPLE TYPES

let myNumber: number = 42;

let myString: string = "Hello, TypeScript!";

let myBoolean: boolean = true;

// Output simple types

console.log("Number:", myNumber);

console.log("String:", myString);

console.log("Boolean:", myBoolean);

// SPECIAL TYPES

// 1. any - Can be any type, no type safety

let myAny: any = 10;

console.log("Any (number):", myAny);

myAny = "Now a string";

console.log("Any (string):", myAny);

// 2. unknown - Like any, but safer (requires type checking)

let myUnknown: unknown = "Possible string";

if (typeof myUnknown === "string") {

console.log("Unknown (string):", myUnknown.toUpperCase());

}
// 3. void - Function that returns nothing

function logMessage(): void {

console.log("This is a message from a void function.");

logMessage();

// 4. null and undefined

let myNull: null = null;

let myUndefined: undefined = undefined;

console.log("Null value:", myNull);

console.log("Undefined value:", myUndefined);

// 5. never - Function that never returns (e.g., throws an error)

function throwError(): never {

throw new Error("This is a 'never' type function.");

// Uncomment below line to test never (will stop execution)

// throwError();

OUTPUT

Number: 42

String: Hello, TypeScript!

Boolean: true

Any (number): 10

Any (string): Now a string

Unknown (string): POSSIBLE STRING

This is a message from a void function.

Null value: null

Undefined value: undefined


DESCRIPTION

Type Description

number Numeric values

string Text values

boolean true or false

any Can be assigned any type, but not type-safe

unknown Like any but forces you to check type before using

void Functions that do not return a value

null Explicitly represents "no value"

undefined Value not assigned

never Function never returns (e.g., throws, infinite loop)

undefined Value not assigned

Function never returns (e.g., throws, infinite


never
loop)
b. write a program to understand function and returntypes.

Program:

// Function with number return type

function add(a: number, b: number): number {

return a + b;

// Function with string return type

function greet(name: string): string {

return "Hello, " + name + "!";

// Function with boolean return type

function isEven(num: number): boolean {

return num % 2 === 0;

// Function with void return type (does not return anything)

function printMessage(msg: string): void {

console.log("Message: " + msg);

// Function with array return type

function getFruits(): string[] {

return ["Apple", "Banana", "Mango"];

// Function with object return type

function getPerson(): { name: string; age: number } {

return { name: "John", age: 30 };


}

// Testing the functions

console.log("Add: ", add(5, 3)); // 8

console.log(greet("Alice")); // Hello, Alice!

console.log("Is 10 even?", isEven(10)); // true

printMessage("This is a sample message."); // logs message

console.log("Fruits: ", getFruits()); // ["Apple", "Banana", "Mango"]

console.log("Person: ", getPerson()); // { name: 'John', age: 30 }

OUTPUT

Add: 8

Hello, Alice!

Is 10 even? true

Message: This is a sample message.

Fruits: [ 'Apple', 'Banana', 'Mango' ]

Person: { name: 'John', age: 30 }

c. write a program to show the importance with Arrow function. Use optional,
default and REST parameters.

Program:

// Arrow function with optional parameter

const greet = (name?: string): string => {

return name ? `Hello, ${name}!` : "Hello!";

};

// Arrow function with default parameter

const multiply = (a: number, b: number = 2): number => {


return a * b;

};

// Arrow function with rest parameters

const sumAll = (...numbers: number[]): number => {

return numbers.reduce((acc, val) => acc + val, 0);

};

// Output

console.log(greet()); // Hello!

console.log(greet("Pavithra")); // Hello, Pavithra!

console.log(multiply(5)); // 10 (5 * default 2)

console.log(multiply(5, 3)); // 15

console.log(sumAll(1, 2, 3)); // 6

console.log(sumAll(10, 20, 30, 40)); // 100

OUTPUT

Hello!

Hello, Pavithra!

10

15

100

DESCRIPTION:

Concept Syntax Example Meaning

Optional Parameter name?: string name can be string or undefined


Concept Syntax Example Meaning

Default Parameter b: number = 2 b will be 2 if not passed

Rest Parameter ...numbers: number[] Allows multiple arguments as array

Arrow Function const fn = () => {} Short, lexical this, cleaner syntax

d. write a program to understand the working of typescipt with


class,constructor,properties,methods and access specifiers.

Program:

// Class definition

class Person {

// Properties with access specifiers

public name: string; // Accessible everywhere

private age: number; // Accessible only inside the class

protected gender: string; // Accessible inside the class and subclasses

// Constructor

constructor(name: string, age: number, gender: string) {

this.name = name;

this.age = age;

this.gender = gender;

// Public method

public introduce(): void {

console.log(`Hi, I'm ${this.name}.`);

this.displayAge(); // calling private method inside the class

}
// Private method

private displayAge(): void {

console.log(`My age is ${this.age}.`);

// Protected method

protected showGender(): void {

console.log(`Gender: ${this.gender}`);

// Subclass

class Student extends Person {

public grade: number;

constructor(name: string, age: number, gender: string, grade: number) {

super(name, age, gender);

this.grade = grade;

public showDetails(): void {

this.introduce(); // can access public method

console.log(`Grade: ${this.grade}`);

this.showGender(); // can access protected method

// Create objects

const student1 = new Student("Alice", 20, "Female", 9);

student1.showDetails();
OUTPUT

Hi, I'm Alice.

My age is 20.

Grade: 9

Gender: Female

e. Write a program to understand the working of namespaces and modules.

Program:

// Demonstration of Namespaces and Modules in TypeScript

namespace MathOperations {

// Function inside namespace

export function add(a: number, b: number): number {

return a + b;

// Another function inside namespace

export function subtract(a: number, b: number): number {

return a - b;

// Class inside namespace

export class Calculator {

public multiply(a: number, b: number): number {

return a * b;

public divide(a: number, b: number): number {


return a / b;

// Main program

class Demo {

public static show(): void {

// Accessing functions and class using namespace

const sum = MathOperations.add(8, 2);

const difference = MathOperations.subtract(8, 2);

const calc = new MathOperations.Calculator();

const product = calc.multiply(4, 3);

const quotient = calc.divide(20, 5);

console.log("Addition:", sum);

console.log("Subtraction:", difference);

console.log("Multiplication:", product);

console.log("Division:", quotient);

// Calling the function

Demo.show();
Output:

Addition: 10

Subtraction: 6

Multiplication: 12

Division: 4

f. Write a program to understand generics with variables, functions and constraints.

Program:

// Demonstration of Generics with Variables, Functions, and Constraints

// Generic Variable (Generic Interface)

interface Box<T> {

value: T;

// Using generic variable

const numberBox: Box<number> = { value: 100 };

const stringBox: Box<string> = { value: "Hello Generics!" };

console.log("Number Box:", numberBox.value);

console.log("String Box:", stringBox.value);

//Generic Function

function displayValue<T>(item: T): void {

console.log("Value:", item);

// Calling generic function with different types

displayValue<number>(42);

displayValue<string>("TypeScript is powerful!");
displayValue<boolean>(true);

// Generic Function with Multiple Types

function combine<T, U>(a: T, b: U): string {

return `Combined: ${a} and ${b}`;

console.log(combine<string, number>("Age", 21));

// Generics with Constraints

interface HasLength {

length: number;

// Function that works only with types having 'length' property

function logLength<T extends HasLength>(item: T): void {

console.log("Length:", item.length);

// Valid calls

logLength("Hello"); // string has length

logLength([1, 2, 3, 4]); // array has length

logLength({ length: 10 }); // object with length property

// Invalid call (Uncommenting this line will cause an error)

// logLength(123); // number doesn't have a length property

Output:

Number Box: 100

String Box: Hello Generics!


Value: 42

Value: TypeScript is powerful!

Value: true

Combined: Age and 21

Length: 5

Length: 4

Length: 10
FSD – 2 Lab Record

EXPERIMENT – 2
1. Express JS – Routing, HTTP Methods, Middleware

Express.js is a minimal and flexible Node.js web application framework that provides a set of
features for building web and mobile applications easily. It simplifies the development of server-
side applications by offering an easy-to-use API for routing, middleware, and HTTP utilities.

Features of Express.js

Built on Node.js for fast and scalable server-side development.


Simplifies routing and middleware handling for web applications.
Supports building REST APIs, real-time applications, and single-page applications (SPA).
Provides a lightweight structure for flexible and efficient server-side development.

Routing in Express.js
Routing in Express.js is the process of mapping to handle client requests.
Routing Flow
HTTP Request: Represents the incoming request with method and path (e.g., GET /users).
Route Matching: Lists all defined routes and determines which route matches the request.
Handler Execution: Executes the matching route’s handler function (req, res).
Sending Response: The server sends a response back to the client using methods like:
res.send()
res.json()
res.render()
Routing enables developers to configure endpoints for various paths and operations, such as:
Rendering views
Processing form data
Performing CRUD (Create, Read, Update, Delete) actions on resources
Syntax:
app.METHOD(PATH, HANDLER);

HTTP Methods in Express.js


HTTP methods determine how a server handles client requests. They define the type of operation
to perform on a resource, such as retrieving, creating, updating, or deleting data. Express allows
defining routes that handle requests efficiently and in an organized manner.
1. GET Method

The GET method is used by a client to retrieve data from the server.
It takes two parameters: the URL to listen on and a callback function with req (client request) and
res (server response) as arguments.

Syntax:

app.get("URL", (req, res) => {});

1
FSD – 2 Lab Record

2. POST Method

The POST method sends data from the client to the server, usually to store it in a database.
It takes two parameters: the URL to listen on and a callback function with req (client request) and
res (server response). The data sent is available in the request body and must be parsed as JSON.
Syntax:
app.post("URL", (req, res) => {});

3. PUT Method

The PUT method updates existing data in the database.


It takes two parameters: the URL to listen on and a callback function with req (client request
containing updated data in the body) and res (server response).

Syntax:

app.put("URL", (req, res) => {});

4. DELETE Method
The DELETE method removes data from the database.
It takes two parameters: the URL to listen on and a callback function with req (containing the ID of
the item to delete in the body) and res (server response).
Syntax:
app.delete("URL", (req, res) => {});

5. PATCH Method

The PATCH method is used to partially update data on the server.


It takes two parameters: the URL to listen on and a callback function with req (containing the data
to update, usually in the body or URL parameters) and res (server response).

Syntax:

app.patch("URL", (req, res) => {});

Running the Application

Steps to Run the Express.js Application:

1. Save the Code:


Save your Express.js code into a file (for example, app.js).

2. Run the Application:


Open the terminal or command prompt and execute the following command:

3. node app.js

4. Open the Application in a Browser:


Use any browser and go to the following URLs to test your routes:
2
FSD – 2 Lab Record

o Homepage:
http://localhost:3000/

o User Route (Example with User ID):


http://localhost:3000/user/123

o Search Route with Ǫuery Parameters:


http://localhost:3000/search?query=Node.js

o Dynamic URL Route:


http://localhost:3000/build-url

3
FSD – 2 Lab Record

OUTPUT:

4
FSD – 2 Lab Record

2(a). Write a program to define a route, handle routes, route parameters, query parameters, and
URL building

Program:

const express = require('express');


const app = express();
const port = 3000;

// Route without parameters


app.get('/', (req, res) => {
res.send('Welcome to the homepage!');
});

// Route with route parameters (e.g., /user/:id)


app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID is: ${userId}`);
});

// Route with query parameters (e.g., /search?query=Node.js)


app.get('/search', (req, res) => {
const query = req.query.query;
res.send(`You searched for: ${query}`);
});

// Handling multiple route parameters


app.get('/posts/:category/:id', (req, res) => {
const { category, id } = req.params;
res.send(`Post in category ${category} with ID ${id}`);
});

// Route to build a URL dynamically


app.get('/build-url', (req, res) => {
const dynamicUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
res.send(`Built URL is: ${dynamicUrl}`);
});

// Start the server


app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

5
FSD – 2 Lab Record

OUTPUT:

6
FSD – 2 Lab Record

2(b). Write a program to accept data, retrieve data, and delete a specified resource using
HTTP methods

Program:

const express = require('express');


const app = express();
const port = 3001;

app.use(express.json());

let items = [
{ id: 1, name: "Pen" },
{ id: 2, name: "Notebook" }
];

// GET – Retrieve
app.get('/items', (req, res) => {
res.json(items);
});

// POST – Accept Data


app.post('/items', (req, res) => {
const newItem = {
id: items.length + 1,
name: req.body.name
};
items.push(newItem);
res.status(201).json(newItem);
});

// DELETE – Delete by ID
app.delete('/items/:id', (req, res) => {
const id = parseInt(req.params.id);
items = items.filter(item => item.id !== id);
res.send(`Item with id ${id} deleted`);
});

// Start the Server


app.listen(port, () => {
console.log(`App listening on http://localhost:${port}`);
});

7
FSD – 2 Lab Record

8
FSD – 2 Lab Record

Step 1: Start Your ServerSave your code in a file, for example: 1b.js
Run it in the Command Prompt using the following command:node 1b.js
You should see the message:App listening on http://localhost:3001
Step 2: Use curlBase URL:http://localhost:3001
A. GET /items – Retrieve all items
Method: GET URL: http://localhost:3001/items
No request body required.
Response:[
{ "id": 1, "name": "Pen" },
{ "id": 2, "name": "Notebook" }
]
B. POST /items – Add a new item
Method: POST URL: http://localhost:3001/items
Steps:Open another Command Prompt window.
Run the following command:curl -X POST http://localhost:3001/items -H "Content-Type:
application/json" -d "{\"name\":\"Marker\"}"
After running the command, open your browser and go to:http://localhost:3001/items
You should now see the third item ("Marker") added to the list.
C. DELETE /items/:id – Delete an item by ID
Method: DELETE Command:
curl -X DELETE http://localhost:3001/items/2URL: http://localhost:3001/items/2
(This deletes the item with ID = 2

Response:Item with id 2 deleted.

9
FSD – 2 Lab
Record

OUTPUT:

Testing the Middleware


To test how middleware works in your Express application, follow these steps after running the
server with:
node app.js(or the filename you saved, e.g., 1c.js)
1. Access the Public Route
URL:
http://localhost:3000/
Expected Output:
Displays Welcome to the public route!
2. Access the Secure Route without Authentication
URL: http://localhost:3000/secure
Expected Output:
Displays Unauthorized access. Add ?auth=true to the URL.
3. Access the Secure Route with Authentication
URL: http://localhost:3000/secure?auth=true
Expected Output:
Displays Welcome to the secure route!
4. Trigger the Error Route URL:http://localhost:3000/error
Expected Output:
Displays Internal Server Error and logs the error message in the terminal.

10
FSD – 2 Lab
Record

2(c). Write a program to show the working of middleware

Program:

Here’s a simple and clear example demonstrating how middleware works in Node.js using the
Express framework.
This program includes:
Global Middleware (runs on all requests)
Route-specific Middleware,Error-handling Middleware,Install Required Packages in Command
Prompt:
npm init -y
npm install express
const express = require('express');
const app = express(); const port = 3000;
// Global Middleware: Logs every request
app.use((req, res, next) => {
console.log(`[LOG] ${req.method} request to ${req.url}`);
next(); // Pass control to the next middleware/route
});
// Middleware to simulate authentication
const authMiddleware = (req, res, next) => {
const authorized = req.query.auth === 'true';
if (authorized) {
console.log('User is authenticated');
next();
} else {
res.status(401).send('Unauthorized access. Add ?auth=true to the URL.');
}};
// Route with no middleware
app.get('/', (req, res) => {
res.send('Welcome to the public route!');
});
// Route with authentication middleware
app.get('/secure', authMiddleware, (req, res) => {
res.send('Welcome to the secure route!');
});
// Route that throws an error
app.get('/error', (req, res, next) => {
next(new Error('Something went wrong!')); // Pass error to error-handling middleware
});
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(`[ERROR] ${err.message}`); res.status(500).send('Internal Server Error');
});
// Start the server
app.listen(port, () => {
console.log(`Middleware demo app running at
http://localhost:${port}`);});
11
FSD – 2 Lab
Record

OUTPUT:

12
FSD – 2 Lab
Record

EXPERIMENT – 3
3. Express JS – Templating, Form Data

3a. Write a program using templating engine.


Program:
const express = require('express');
const app = express();
const port = 3000;

// Set EJS as templating engine


app.set('view engine', 'ejs');
// Home route

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


const user = {
name: 'Sravani',
age: 25,
hobbies: ['Reading', 'Coding', 'Traveling']
};

res.render('index', { user: user });


});

// Start server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Save as File name: Index.ejs
<!DOCTYPE html>

<html>
<head>
<title>Welcome <%= user.name %></title>
</head>

<body>
<h1>Hello, <%= user.name %>!</h1>
<p>Age: <%= user.age %></p>

<h2>Hobbies:</h2>
<ul>
<% user.hobbies.forEach(function(hobby) { %>
<li><%= hobby %></li> <% }); %>
</ul>
</body>
</html>
13
FSD – 2 Lab
Record

OUTPUT:

Click on submit then

14
FSD – 2 Lab
Record

3b. Write a program to work with form data.


Program:
const express = require('express');
const app = express();
const port = 3000;
// Middleware to parse form data
app.use(express.urlencoded({ extended: true }));
// Set view engine
app.set('view engine', 'ejs');
// Route: show form
app.get('/', (req, res) => {
res.render('form');
});
// Route: handle form submission
app.post('/submit', (req, res) => {
const { name, email, message } = req.body;
res.render('success', { name, email, message });
});
// Start server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Save as form.ejs
<!DOCTYPE html>
<html>
<head>
<title>Contact Form</title></head>
<body>
<h1>Contact Us</h1>
<form action="/submit" method="POST"><label>Name:</label><br>
<input type="text" name="name" required><br><br>
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
<label>Message:</label><br>
<textarea name="message" required></textarea><br><br>
<button type="submit">Submit</button> </form></body>
</html>
Save as success.ejs
<!DOCTYPE html>
<html>
<head>
<title>Submission Successful</title> </head>
<body><h1>Thank You, <%= name %>!</h1>
<p><strong>Email:</strong> <%= email %></p>
<p><strong>Message:</strong> <%= message %></p>
</body>
</html>

15
FSD – 2 Lab
Record

OUTPUT:

16
FSD – 2 Lab Record

EXPERIMENT – 4
4. Express JS – Cookies, Sessions, Authentication

4a. Session Management using Cookies and Sessions

const express = require('express');


const session = require('express-session');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Session middleware
app.use(session({
secret: 'mySecretKey',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 300000 } // 5 minutes
}));
app.get('/', (req, res) => {
res.send(`<form method="POST" action="/login">
<input name="username" placeholder="Enter name" />
<button type="submit">Login</button>
</form>`);
});
app.post('/login', (req, res) => {
const { username } = req.body;
req.session.user = username;
res.send(`Welcome, ${username}! <a href="/profile">Go to profile</a>`);
});
app.get('/profile', (req, res) => {
if (req.session.user) {
res.send(`Hello ${req.session.user}, this is your profile`);
} else {
res.send('Please login first!');
}
});

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


req.session.destroy();
res.send('Logged out successfully');
});
app.listen(3000, () =>
console.log("Server running on http://localhost:3000")
);
17
FSD – 2 Lab Record

OUTPUT:

18
FSD – 2 Lab Record

4b. Write a program for user authentication in Express JS.

Program:

const express = require('express'); const session = require('express-session');


const bodyParser = require('body-parser');
const app = express();
const port = 3006;
// Middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: 'authSecret',
resave: false,
saveUninitialized: true
})); // Dummy credentials
const user = {
username: 'admin',
password: '12345'
}; // Login Form (GET)
app.get('/login', (req, res) => {
res.send(`
<h2>Login</h2>
<form method="POST" action="/login">
Username: <input name="username" /><br />
Password: <input type="password" name="password" /><br />
<button type="submit">Login</button>
</form>
`); }); // Login Handler (POST)
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username === user.username CC password === user.password) {
req.session.authenticated = true;
req.session.username = username;
res.send('Login successful. <a href="/protected">Go to Protected Page</a>');
} else {
res.send('Invalid credentials. <a href="/login">Try again</a>');
} });
// Protected Route
app.get('/protected', (req, res) => {
if (req.session.authenticated) {
res.send(`Welcome ${req.session.username}, this is a protected page.`);
} else { res.send('Unauthorized access. <a href="/login">Login</a>'); } }); // Logout
app.get('/logout', (req, res) => {
req.session.destroy(); res.send('Logged out. <a href="/login">Login again</a>');
});
app.listen(port, () => { console.log(`Auth app running at http://localhost:${port}`); });
19
FSD – 2 Lab Record

OUTPUT:

20
FSD – 2 Lab Record

EXPERIMENT – 5
5. ExpressJS – Database, RESTful APIs

5a.Write a program to connect MongoDB database using Mongoose and perform CRUD operations

Program:

const mongoose = require('mongoose');

// 1. Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('MongoDB connected'))
.catch(err => console.error('MongoDB connection error:', err));

// 2. Define a schema and model


const userSchema = new mongoose.Schema({
name: String,
email: String,
age: Number
});

const User = mongoose.model('User', userSchema);

// 3. CRUD operations as async functions

// Create a user
async function createUser() {
const user = new User({
name: 'John Doe',
email: '[email protected]',
age: 30
});
const savedUser = await user.save();
console.log('User created:', savedUser);
}

// Read all users


async function getUsers() {
const users = await User.find();
console.log('All users:', users);
}

21
FSD – 2 Lab Record

// Update a user by id
async function updateUser(userId) {

22
FSD – 2 Lab Record

23
FSD – 2 Lab Record

const updatedUser = await User.findByIdAndUpdate(

userId,
{ age: 35 },
{ new: true }
);
console.log('User updated:', updatedUser);
}

// Delete a user by id
async function deleteUser(userId) {
const deletedUser = await User.findByIdAndDelete(userId);
console.log('User deleted:', deletedUser);
}

// Run the functions in sequence as an example


async function run() {
await createUser();
await getUsers();

// For demonstration, fetch one user to update and delete


const users = await User.find();
if (users.length > 0) {
const id = users[0]._id;
await updateUser(id);
await deleteUser(id);
}

mongoose.connection.close();
}

run();

24
FSD – 2 Lab Record

OUTPUT:

Execution:

Save file as server.js npm init -y

npm install express cors node server.js

25
FSD – 2 Lab Record

5b.Write a program to develop a single page application using RESTful APIs

Program:
// Step 1: Backend REST API (Express)
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 3000;
app.use(cors());
app.use(express.json());
let items = [
{ id: 1, name: "Item One" },
{ id: 2, name: "Item Two" }
];
// Get all items
app.get('/api/items', (req, res) => {
res.json(items);
});
// Create new item
app.post('/api/items', (req, res) => {
const newItem = {
id: items.length + 1,
name: req.body.name
};
items.push(newItem);
res.status(201).json(newItem);
});
// Update an item by id
app.put('/api/items/:id', (req, res) => {
const id = parseInt(req.params.id);
const item = items.find(i => i.id === id);
if (item) {
item.name = req.body.name;
res.json(item);
} else {
res.status(404).json({ message: 'Item not found' });
}
});
// Delete an item by id
app.delete('/api/items/:id', (req, res) => {
const id = parseInt(req.params.id);
items = items.filter(i => i.id !== id);
res.status(204).end();
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`); });
26
FSD – 2 Lab Record

OUTPUT:

Execution:
1. Run the backend: node server.js

2. Open index.html in your browser (just double click or serve via live-server)

3. You get a SPA with Add, Edit, Delete functionality using RESTful API calls!

27
FSD – 2 Lab Record

Step 2: Frontend SPA (index.html)


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>SPA with REST API</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
ul {
list-style: none;
padding: 0;
}
li {
margin: 5px 0;
}
button {
margin-left: 10px;
}
</style>
</head>
<body>
<h1>Items</h1>

<ul id="itemsList"></ul>

<input type="text" id="itemName" placeholder="New item name" />


<button onclick="addItem()">Add Item</button>

<script>
const apiUrl = 'http://localhost:3000/api/items';

// Fetch and display items


async function fetchItems() {
const res = await fetch(apiUrl);
const items = await res.json();
const list = document.getElementById('itemsList');
list.innerHTML = '';

items.forEach(item => {
const li = document.createElement('li');
li.textContent = item.name; // Edit button
const editBtn = document.createElement('button');

28
FSD – 2 Lab Record

29
FSD – 2 Lab Record

editBtn.textContent = 'Edit';
editBtn.onclick = () => editItem(item.id, item.name);
// Delete button
const delBtn = document.createElement('button');
delBtn.textContent = 'Delete';
delBtn.onclick = () => deleteItem(item.id);

li.appendChild(editBtn);
li.appendChild(delBtn);
list.appendChild(li);
});
} // Add a new item
async function addItem() {
const input = document.getElementById('itemName');
const name = input.value.trim();
if (!name) return alert('Please enter a name');await fetch(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name })
});

input.value = '';
fetchItems();
} // Edit an item
async function editItem(id, oldName) {
const newName = prompt('Edit item name:', oldName);
if (!newName) return;
await fetch(`${apiUrl}/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newName })
});
fetchItems();
}

// Delete an item
async function deleteItem(id) {
await fetch(`${apiUrl}/${id}`, { method: 'DELETE' });
fetchItems();
}

// Initial load
fetchItems();
</script></body></html>

30
FSD – 2 Lab Record

Output:

Hello, this is plain HTML rendered

in React! React makes rendering

easy

31
FSD – 2 Lab Record

EXPERIMENT - 6
6. ReactJS – Render HTML, JSX, Components – function & Class

a. Write a program to render HTML to a web page.


b. Write a program for writing markup with JSX.
c. Write a program for creating and nesting components (function and class). What is ReactJS?

ReactJS is a JavaScript library developed by Facebook (Meta) in 2013.


It is used to build user interfaces (UI), especially for single-page applications (SPA).
React follows a component-based architecture, meaning the UI is broken into reusable, independent
components.It uses a Virtual DOM (Document Object Model) for fast rendering and performance.
React helps developers create fast, dynamic, and interactive web applications easily.

Key Features of ReactJS


1. Component-Based
o UI is built using reusable components.
o Example: A button, navbar, footer can be separate components reused across the app.
2. JSX (JavaScript XML)
o Lets you write HTML inside JavaScript.
o Example:const element = <h1>Hello, React!</h1>;
3. Virtual DOM
o React creates a virtual copy of the real DOM.
o When something changes, React updates only the necessary part
o instead of reloading the entire page.
o This makes React apps super fast.
4. Unidirectional Data Flow
o Data flows in one direction (parent → child), making the app more predictable and easier
to debug.
5. Declarative Syntax
o You just declare what you want to show, and React handles the rendering.
o Example:<p>{user.name}</p>
6. Rich Ecosystem G Tools
o Works with libraries like Redux, React Router, and tools like Next.js.

Uses of ReactJS
ReactJS is mainly used for Front-End Development. Examples:
1. Single Page Applications (SPA) – like Gmail, Facebook, Instagram.
2. Dynamic Websites – live content updates without page reload.
3. Cross-Platform Development – with React Native
4. , you can build mobile apps for Android C iOS using the same React code.
5. Dashboards and Data-Driven Apps – real-time updates, charts, analytics.
6. E-commerce Sites – product pages that update instantly.

32
FSD – 2 Lab Record

Why ReactJS is Important in Full Stack Development (FSD)


In Full Stack Development (FSD), developers handle both
Front-End (client side) and Back-End (server side).
 Frontend (ReactJS) → What the user sees C interacts with.
 Backend (Node.js, Express, MongoDB, etc.) → Handles data, APIs, and business logic.

33
FSD – 2 Lab Record

34
FSD – 2 Lab Record

Role of React in FSD:


1. Efficient Frontend Development
o Makes UI development fast, modular, and maintainable.
2. Seamless Integration with Backend
o Works perfectly with APIs from Node.js, Django, Spring Boot, etc.
o Example: Fetching user data from backend and displaying it instantly.
3. Reusable Components
o Reduces code duplication → faster project delivery.
4. Huge Community G Job Demand
o React is one of the most popular frameworks in the industry.
o Almost every Full Stack Developer role requires React knowledge.
5. Supports Modern Web Apps
o Works with technologies like GraphǪL, Redux, Next.js → essential in enterprise-level
apps.

6a.Write a program to render HTML to a web page.

ReactJS Installation G Execution Guide Step 1: Install Node.js


1. Go to https://nodejs.org
2. LTS version (recommended for most users).
3. Install → just click Next → Next → Finish.
4. Verify installation:
Open Command Prompt / Terminal and run:
5. node -v

import React from "react"; function App() {


return (
<div>
<h1>Hello, this is plain HTML rendered in React!</h1>
<p>React makes rendering easy </p>
</div>
);
}
export default App;

35
FSD – 2 Lab Record

OUTPUT:
Welcome to ReactJS Current Year: 2025
2+3=5

36
FSD – 2 Lab Record

6b. Writing Markup with JSX Code:


function App() {
const name = "ReactJS"; const year = 2025; return (
<div>
<h1>Welcome to {name}</h1>
<p>Current Year: {year}</p>
<p>2 + 3 = {2 + 3}</p>
</div>
);}
export default App;

37
FSD – 2 Lab Record

OUTPUT:
Main App Component
Hello from Greeting Component!

38
FSD – 2 Lab Record

6c. Creating and Nesting Components


(i).Function Component Example:
import React from "react";
// Child Component function Greeting() {
return <h2>Hello from Greeting Component!</h2>;
}
// Parent Component function App() { return (
<div>
<h1>Main App Component</h1>
<Greeting /> {/* Nesting the child */}
</div>
);
}
export default App;
(ii).Class Component Example:
import React, { Component } from 'react'; class Welcome extends Component { render() {
return <h2>Hello from Class Component!</h2>;
}
}
function App() { return (
<div>
<h1>Main App Component</h1>
<Welcome />
</div>
);
}
export default App;

39
FSD – 2 Lab Record

OUTPUT:

40
FSD – 2 Lab Record

EXPERIMENT – 7
7. ReactJS – Props and States, Styles, Respond to Events
(a) Program to Work with Props and State
Theory:
Props (Properties)
 Definition: Props are inputs to a React component.
 Nature: Read-only (cannot be modified inside the component).
 Purpose: Used to pass data from parent to child component.
 Analogy: Props are like function parameters.
State
 Definition: State represents data that belongs to a component and can change over time.
 Nature: Mutable (can be updated).
 Purpose: Used to manage data that changes when the user interacts (e.g., button clicks, typing).
 Analogy: State is like a component’s personal memory.

Program:
import React, { useState } from "react";

// Child component using props


function ChildComponent(props) {
return <h2>Hello, {props.name}! Your age is {props.age}</h2>;
}

// Parent component using state


function App() {
const [age, setAge] = useState(20);

return (
<div>
<h1>React Props and State Example</h1>
{/* Passing props */}
<ChildComponent name="Bhargavi" age={age} />
<button onClick={() => setAge(age + 1)}>Increase Age</button>
</div>
);
}

export default App;

41
FSD – 2 Lab Record

OUTPUT:

42
FSD – 2 Lab Record

(b) Program to Add Styles (CSS G Inline) and Display Data

Theory:

React allows multiple ways to style components:


Inline CSS → For quick, component-specific styles.
External CSS → For reusable and organized styles.
CSS Modules → Scoped styles to prevent conflicts.
Sass → Advanced styling with variables, nesting, etc.

Program (App.js):

import React from "react";


import "./App.css"; // External CSS file
function App() {
const inlineStyle = {
color: "blue",
fontSize: "20px",
padding: "10px",
border: "2px solid green"
};

return (
<div>
<h1 style={{ textAlign: "center", color: "purple" }}>
React Styling Example
</h1>

{/* Inline Styling */}


<p style={inlineStyle}>This is styled with inline CSS</p>

{/* External CSS */}


<p className="externalStyle">This is styled with external CSS</p>
</div>
);
}

export default App;


Program (App.css):
.externalStyle {
color: red;
font-size: 18px;
background-color: yellow;
padding: 8px;
border-radius: 5px;
}

43
FSD – 2 Lab Record

OUTPUT:

44
FSD – 2 Lab Record

(c) Program for Responding to Events


Theory:
In React, events are handled similarly to DOM events but use camelCase syntax (e.g., onClick,
onChange, onMouseOver).
You can pass event handler functions to JSX elements, which are triggered by user interactions.

Common Event Types:


 onClick → Triggered when a button or element is clicked.
 onChange → Triggered when input field value changes.
 onMouseOver → Triggered when the mouse pointer hovers over an element.

Program (App.js):
import React, { useState } from "react";

function App() {
const [message, setMessage] = useState("Click the button!");

function handleClick() {
setMessage("Button was clicked!");
}

function handleInput(event) {
setMessage("You typed: " + event.target.value);
}
return (
<div>
<h1>React Event Handling Example</h1>
<p>{message}</p>

{/* onClick event */}


<button onClick={handleClick}>Click Me</button>

<br /><br />

{/* onChange event */}


<input
type="text"
placeholder="Type something"
onChange={handleInput}
/>
</div>
);
}

export default App;

45
FSD – 2 Lab Record

OUTPUT:

46
FSD – 2 Lab Record

EXPERIMENT – 8
8. ReactJS – Conditional Rendering, Rendering Lists, React Forms
a. Program for Conditional Rendering
Theory:
Conditional Rendering in React means displaying different components or
elements based on specific conditions — just like using if, else, or switch statements in JavaScript.
React automatically updates the UI when state or props change,
which makes conditional rendering ideal for creating interactive and dynamic interfaces.
Common Techniques for Conditional Rendering:
1. Ternary Operator
Syntax:
2. condition ? <ComponentA /> : <ComponentB />
Example: Render one element if a user is logged in, and another if not.
3. Logical AND (GG)
Syntax:
4. condition CC <Component />
Example: Render an element only when the condition is true.
5. if–else Statements
Used outside of JSX to determine which component to return.

Program (ConditionalRendering.js):
import React, { useState } from 'react';

function ConditionalRendering() {
const [isLoggedIn, setIsLoggedIn] = useState(false);

return (
<div>
{isLoggedIn ? (
<h1>Welcome back, User!</h1>
):(
<h1>Please log in to continue.</h1>
)}

<button onClick={() => setIsLoggedIn(!isLoggedIn)}>


{isLoggedIn ? 'Log out' : 'Log in'}
</button>
</div>
);
}

export default ConditionalRendering;

47
FSD – 2 Lab Record

OUTPUT:

48
FSD – 2 Lab Record

b. Program for Rendering Lists


import React from 'react';

function RenderList() {
const fruits = ['Apple', 'Banana', 'Cherry', 'Date'];

return (
<div>
<h1>Fruits List</h1>
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
</div>
);
}

export default RenderList;

49
FSD – 2 Lab Record

OUTPUT:

50
FSD – 2 Lab Record

C. Program for Working with Different Form Fields using React Forms

Theory:
In React, forms are managed using controlled components.
A controlled component is an input element (like <input>, <textarea>, <select>) whose value is
controlled by React state.
This allows developers to manage, validate, and handle user inputs effectively in real time.

Key Concepts:
1. Controlled Components:
The value of form elements is tied to React’s state.
Example:
<input type="text" value={username} onChange={handleChange} />
2. State Management:
o Form data is stored in a single state object.
o Updated dynamically using event handlers.
3. Event Handling:
o onChange: Updates state when the user types or selects input.
o onSubmit: Handles form submission and prevents page reload.
4. Advantages:
o Full control over form inputs.
o Easy validation and data manipulation.
o Predictable and reactive form behavior.

Program (ReactForms.js):
import React, { useState } from 'react';
function ReactForms() {
const [formData, setFormData] = useState({
username: '',
email: '',
password: ''
});

const handleChange = (e) => {


const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};

const handleSubmit = (e) => {


e.preventDefault();
alert(`Username: ${formData.username}\nEmail: ${formData.email}\nPassword:
${formData.password}`);
};

return ( <form onSubmit={handleSubmit}> <label>

51
FSD – 2 Lab Record

52
FSD – 2 Lab Record

Username:
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
</label>
<br />

<label>
Email:
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
</label>
<br />

<label>
Password:
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
/>
</label>
<br />

<button type="submit">Submit</button>
</form>
);
}

export default ReactForms;

53
FSD – 2 Lab Record

output:

Execution process:

 Start the server: npm start

 Open http://localhost:3000

Click links → Page updates without reloading

54
FSD – 2 Lab Record

EXPERIMENT – 9

9. ReactJS – React Router, Updating the Screen


a) Program for Routing to Different Pages using React Router

What is React Router?


React Router is a library in React used for navigation betweendifferent pages or components without
reloading the entire webpage.
It provides a Single Page Application (SPA) experience — the page does not reload, only the necessary
component updates.
Key Components in React Router
BrowserRouter → Wraps the entire app to enable routing.
Routes → Collection of all route definitions.Route → Defines a path (URL) and the component to display.
Link / NavLink → Provides navigation links to switch between pages.
Why Use React Router?
In traditional websites, every page load causes a full refresh → slow.
In React, with Router:Navigation is faster.
Only the required components update.Provides a smoother user experience.
Program:
// App.js
import React from "react";
import { BrowserRouter as Router, Route, Routes, Link } from "react-router-dom";
// Pages
function Home() {
return <h2> Welcome to Home Page </h2>;
}
function About() {
return <h2> ℹ About Us Page </h2>;
}
function Contact() {
return <h2> Contact Page </h2>;
}
function App() {
return (
<Router>
<div>
<h1>React Router Example</h1>

{/* Navigation Links */}


<nav>
<Link to="/">Home</Link> |{" "}
<Link to="/about">About</Link> |{" "}

55
FSD – 2 Lab Record

56
FSD – 2 Lab Record

<Link to="/contact">Contact</Link>
</nav>

{/* Routing Configuration */}


<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</div>
</Router>
);
}

export default App;

57
FSD – 2 Lab Record

OUTPUT:

Steps to Run

Create a React app:


npx create-react-app myapp
cd myapp npm install react-router-dom npm start Replace App.js with the following code:

58
FSD – 2 Lab Record

b.What is Updating the Screen in React

 In React, the screen updates automatically whenever the state or props of a component
change.
 This is achieved using React’s virtual DOM → only the changed part of UI re-renders.

Ways to Update the Screen

1. Using useState Hook → update variables dynamically.


2. Using Props → when parent data changes, child re-renders.
3. API Calls (useEffect) → update data after fetching from server.

When to Use

 React Router: When building applications with multiple pages like Home, About, Contact.
 Updating Screen: When creating interactive UIs (counters, forms, live data, etc.) where values
change dynamically.

Why is This Needed?

 Routing → to organize large apps into multiple pages.


 Screen Updating → to make apps interactive without page reload.

We use React useState Hook to update content dynamically.

Program:

// App.js
import React, { useState } from "react";

function App() {
const [count, setCount] = useState(0);

return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
<h1>React State Update Example</h1>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>+ Increase</button>
<button onClick={() => setCount(count - 1)}>— Decrease</button>
<button onClick={() => s e t C o u n t ( 0 ) } > ■³
– Reset</button>
</div>
);
}
export default App;

59
FSD – 2 Lab Record

OUTPUT:

Execution Steps

1. Create project:

2. npx create-react-app myapp

3. cd myapp

1. Replace src/App.js with above code.

2. Run:

2. npm start

3. Open http://localhost:3000.

o Initially count = 0.
o Click Increase → count updates. Click Decrease → count reduces.

60
FSD – 2 Lab Record

EXPERIMENT – 10
10. ReactJS – Hooks, Sharing Data Between Components
a) Program to Understand Importance of Using Hooks
What is a Hook in React?
 A Hook is a special function in React that lets you use state and other React features in
functional components (without writing class components).
 Examples:
o useState → for state management
o useEffect → for side effects (API calls, timers, etc.)
o useContext → for sharing data globally
o useRef, useReducer, etc.
How to Use Hooks?
1. Import from React:
2. import React, { useState } from "react";
3. Call inside a functional component:
4. const [count, setCount] = useState(0);
o count → variable (state)
o setCount → function to update the variable
5. Update state using setCount → causes re-render of UI.
When to Use Hooks?
 When you need to store and update data inside a component (like form inputs, counters,
toggles).
 When you want to fetch or update data automatically when a component mounts (using
useEffect).
 When you need to reuse logic between multiple components.

Program:
import React, { useState } from "react";

function App() {
// useState Hook: count is variable, setCount is function to update it
const [count, setCount] = useState(0);

return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
<h1>React useState Hook Example</h1>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increase</button>
<button onClick={() => setCount(count - 1)}>Decrease</button>
</div>
);
}

export default App;

61
FSD – 2 Lab Record

OUTPUT:

62
FSD – 2 Lab Record

b) Program for Sharing Data Between Components


Concept Overview
We can pass data from Parent → Child using props.
If multiple children need access to the same data, React Context can also be used.
Here, we’ll use props for simplicity.
Concept:Data is stored in the Parent (App) component using useState, and then passed
down to the Child component using props.Whenever the parent’s data changes, the child re-renders
automatically.
Sharing Data Between Components
In React, data usually flows from Parent → Child using props.
Ways to Share Data
1. Props (Most Common):
o Pass data as attributes from parent to child.
o Child can only read (not modify) parent’s data.
2. Callback Functions (Child → Parent):
o Pass a function from parent to child.
o Child calls the function to send data back to parent.
3. Context API (Global Sharing):
o Used when data is needed by many components at different levels.
o Avoids “prop drilling” (passing props through multiple layers).
Why is Sharing Data Needed?
 In React, each component is independent.
 In real-world apps, components need to communicate — for example:
o A form component updating parent data.
o A navbar sending data to content components.
 Sharing data ensures synchronization of UI between components.
Program:
import React, { useState } from "react";// Child Component
function Child({ message }) {
return (
<div style={{ border: "1px solid gray", padding: "10px", margin: "10px" }}>
<h3>Child Component</h3>
<p>Message from Parent: {message}</p>
</div>
);
}// Parent Component
function App() {
const [text, setText] = useState("Hello from Parent!");
return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
<h1>Sharing Data Between Components</h1>
<input
type="text" value={text}
onChange={(e) => setText(e.target.value)} />
<Child message={text} /> </div> );} export default App;

63
FSD – 2 Lab Record

OUTPUT:

64
FSD – 2 Lab Record

EXPERIMENT-11

11. ReactJS Applications – To-Do list and Quiz

a. Design a to-do list application


A To-Do List application is a basic productivity tool that allows a user to write down
tasks,keep track of them, and remove them when completed.

Program:
src/App.js:
import React, { useState } from 'react';
import './App.css';

function App() {
// State variables
const [task, setTask] = useState('');
const [tasks, setTasks] = useState([]);

// Function to add a new task


const addTask = () => {
if (task.trim() !== '') {
setTasks([...tasks, task]);
setTask(''); // clear input box
}
};

// Function to delete a task


const deleteTask = (index) => {
const updatedTasks = tasks.filter((_, i) => i !== index);
setTasks(updatedTasks);
};
return (
<div className="App">
<h1>📝 To-Do List</h1>
<div className="input-container">
<input
type="text"
placeholder="Enter your task..."
value={task}
onChange={(e) => setTask(e.target.value)}
/>
<button onClick={addTask}>Add</button>
</div>

<ul>
65
FSD – 2 Lab Record

{tasks.map((t, index) => (


<li key={index}>
{t}
<button className="delete-btn" onClick={() => deleteTask(index)}>
Delete
</button>
</li>
))}
</ul>
</div>
);
}

export default App;

src/App.css:
.App {
text-align: center;
margin-top: 50px;
font-family: Arial, sans-serif;
}

.input-container {
margin-bottom: 20px;
}

input {
padding: 10px;
width: 250px;
font-size: 16px;
}

button {
padding: 10px 15px;
margin-left: 10px;
font-size: 16px;
cursor: pointer;
}
ul {
list-style-type: none;
padding: 0;
max-width: 300px;
margin: 0 auto;
text-align: left;
}

li {
display: flex;
66
FSD – 2 Lab Record

justify-content: space-between;
background: #f0f0f0;
padding: 8px;
margin-bottom: 10px;
border-radius: 4px;
}

.delete-btn {
background: red;
color: white;
border: none;
cursor: pointer;
}

Execution process:
1) open command prompt
i) npx create-react-app todo-app
ii) cd todo-app
iii) npm start
2) open your folder in vs code
3) replace src/App.js and src/App.css from above codes

67
FSD – 2 Lab Record

OUTPUT:

68
FSD – 2 Lab Record

EXPERIMENT – 12
12. MongoDB – Installation, Configuration, CRUD Operations

a. Install MongoDB and Configure Atlas

MongoDB is a NoSǪL database that stores data in JSON-like documents.


Unlike traditional SǪL databases, it doesn’t use tables and rows.
It’s flexible and widely used in modern web applications.

MongoDB Atlas is the cloud version of MongoDB.


It allows you to host and manage MongoDB databases without installing MongoDB locally.

Step-by-Step Installation and Configuration


1. Create a MongoDB Atlas Account
 Go to: https://www.mongodb.com/cloud/atlas
 Sign up for a free account.
2. Create a Cluster
 After logging in, click "Build a Cluster".
 Choose the free tier (shared cluster).
 Select your cloud provider (AWS, GCP, Azure) and region.
 Click Create Cluster (this might take a few minutes).
3. Create a Database User
 Go to Database Access > Add New Database User.
 Set a username and password (remember them!).
 Grant read and write access to any database.
4. Allow Network Access
 Go to Network Access > Add IP Address.
 Use 0.0.0.0 to allow access from anywhere (not recommended for production).
5. Connect Your Application
 Go to Clusters > Click Connect > Choose Connect your application.
 Copy the connection string. Example:
mongodb+srv://<username>:<password>@cluster0.mongodb.net/
myFirstDatabase?retryWrites=trueCw=majority
 Replace <username>, <password>, and myFirstDatabase with your details.

a. Write MongoDB Ǫueries to Perform CRUD Operations on Document


Using insert(), find(), update(), remove()
CRUD stands for:
 Create → insert(), insertOne(), insertMany()
 Read → find(), findOne()
 Update → updateOne(), updateMany(), replaceOne()
 Delete → deleteOne(), deleteMany()
MongoDB CRUD operations are performed on collections within databases.
Let’s assume a database school and a collection students.
1. Create (Insert Documents)
Insert one document
69
FSD – 2 Lab Record

db.students.insertOne({
name: "Alice", age: 20, course: "Math"

70
FSD – 2 Lab Record

OUTPUT:

71
FSD – 2 Lab Record

);
Insert multiple documents
db.students.insertMany([
{ name: "Bob", age: 22, course: "Science" }, { name: "Carol", age: 21, course: "English" }
]);
2. Read (Find Documents)
Find all documents
db.students.find();
Find one document
db.students.findOne({ name: "Alice" });
Find with condition
db.students.find({ age: { $gt: 20 } });
3. Update (Modify Documents)
Update one document
db.students.updateOne(
{ name: "Alice" },
{ $set: { course: "Computer Science" } }
);
Update multiple documents
db.students.updateMany(
{ age: { $gt: 20 } },
{ $set: { status: "Senior" } }
);
4. Delete (Remove Documents)
Delete one document
db.students.deleteOne({ name: "Bob" });
Delete multiple documents
db.students.deleteMany({ age: { $lt: 21 } });

// Insert many documents db.students.insertMany([


{ name: "Bob", age: 22, course: "Science" },
{ name: "Charlie", age: 21, course: "English" }
]);

72
FSD – 2 Lab Record

OUTPUT

OUTPUT:

73
FSD – 2 Lab Record

2. Read (Find Documents)

Find all documents


db.students.find();
Find with condition
db.students.find({ age: { $gt: 20 } }); // age > 20

3. Update Documents
Update one document
db.students.updateOne(
{ name: "Alice" }, // Filter
{ $set: { age: 21 } } // Update
);

Update many documents


db.students.updateMany(
{ course: "Science" },
{ $set: { passed: true } }
);
4. Delete Documents
// Delete one document
db.students.deleteOne({ name: "Charlie" });
// Delete many documents
db.students.deleteMany({ age: { $lt: 21 } }); // age < 21

Tools You Can Use:

• MongoDB Atlas (cloud-based)


• MongoDB Compass (GUI)
• Mongo Shell or MongoDBShell (mongosh) (command-line)

74
FSD – 2 Lab Record

Output :

75
FSD – 2 Lab Record

EXPERIMENT – 13
13. MongoDB – Databases, Collections, and Records
a. Write MongoDB queries to Create and Drop Databases and Collections
Concept Overview:
 A database is a container for collections.
 A collection is a container for documents (equivalent to tables in SǪL).
 A document is a single record (in JSON format).
1. Creating a Database
In MongoDB, you don’t explicitly create a database. When you insert a
document into a collection in a non-existing database, it is automatically created.
use myDatabase;
// Switches to or creates the database
show dbs;
// Lists all databases

2. Creating a Collection
You can create a collection explicitly using the createCollection() method or automatically by
inserting a document into a new collection.
// Syntax
db.createCollection("students");

// Or auto-create by inserting a document


db.students.insertOne({ name: "John", age: 20 });

3. Dropping a Collection
You can remove an existing collection from the database using the drop() method.
// Delete the 'students' collection
db.students.drop();

4. Dropping a Database
To delete an entire database, first switch to it using the use command, then call db.dropDatabase().
use myDatabase; // Switch to the database

// Deletes the current database


db.dropDatabase();

76
FSD – 2 Lab Record

output:

77
FSD – 2 Lab Record

3. sort() – Sorting Results


You can sort query results in ascending (1) or descending (-1) order using the sort() method.
// Sort by age in ascending order
db.students.find().sort({ age: 1 });

// Sort by age in descending order


db.students.find().sort({ age: -1 });

// Sort by age descending


db.students.find().sort({ age: -1 });
4. createIndex() – Indexing
Indexes are used to improve the speed of search queries in MongoDB.
You can create an index on a specific field using the createIndex() method.
// Create an index on the "name" field (ascending order)
db.students.createIndex({ name: 1 });
5. aggregate() – Data Aggregation
Aggregation in MongoDB is used to process data records and return computed or summarized
results.
It is similar to SǪL’s GROUP BY clause.
// Aggregation example: Count number of students in Math course
db.students.aggregate([
{ $match: { course: "Math" } }, // Filter documents where course = "Math"
{ $group: { _id: "$course", total: { $sum: 1 } } } // Group by course and count total
]);
Example
Let’s put all MongoDB operations together in a single example.
use schoolDB;
// Create or switch to the database
db.createCollection("students"); // Create a collection
// Insert multiple student records
db.students.insertMany([
{ name: "Alice", age: 20, course: "Math" },
{ name: "Bob", age: 22, course: "Science" },
{ name: "Charlie", age: 21, course: "Math" }
]);
// Read all documents
db.students.find();
// Limit the output to 2 documents
db.students.find().limit(2);
// Sort the records by age in descending order
db.students.find().sort({ age: -1 });
// Create an index on the 'name' field
db.students.createIndex({ name: 1 });
// Aggregate: count number of students in each course
db.students.aggregate([

78
FSD – 2 Lab Record

{ $match: { course: "Math" } }, { $group: { _id: "$course", count: { $sum: 1 } } } ]);


OUTPUT:

79
FSD – 2 Lab Record

EXPERIMENT – 14
14. Augmented Programs: (Any 2 must be completed)
a. Design a To-Do List Application using NodeJS and ExpressJS
Objective
To design a simple To-Do List application using Node.js, Express.js, and MongoDB that performs
CRUD operations.
Concept Overview
A To-Do List App is a beginner-level project that helps understand:
 RESTful API development
 ExpressJS routing
 CRUD operations using MongoDB
Project Requirements
 Backend: Node.js + Express.js
 Database: MongoDB (Local or Atlas)
Features:
 Add a Task
 View All Tasks
 Mark Task as Complete
 Delete Task
Step-by-Step Implementation
1. Folder Structure and Project Setup
mkdir todo-app
cd todo-app
npm init -y
npm install express mongoose body-parser
2. Connect to MongoDB (Atlas or Local) — app.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const taskRoutes = require('./routes/taskRoutes');
const app = express();
app.use(bodyParser.json());
// MongoDB Connection
mongoose.connect('mongodb://127.0.0.1:27017/todoDB', {
useNewUrlParser: true,
useUnifiedTopology: true
});
app.use('/tasks', taskRoutes);
app.listen(3000, () => {
console.log("Server running on port 3000");
});
3. Create Mongoose Schema — models/Task.js
const mongoose = require('mongoose');
const taskSchema = new mongoose.Schema({ title: String, completed: {

80
FSD – 2 Lab Record

81
FSD – 2 Lab Record

type: Boolean,
default: false
}
});

module.exports = mongoose.model('Task', taskSchema);


4. Create API Routes — routes/taskRoutes.js
const express = require('express');
const router = express.Router();
const Task = require('../models/Task');

// Create Task
router.post('/', async (req, res) => {
const task = new Task(req.body);
await task.save();
res.send(task);
});

// Get All Tasks


router.get('/', async (req, res) => {
const tasks = await Task.find();
res.send(tasks);
});

// Mark Task as Complete


router.patch('/:id', async (req, res) => {
const task = await Task.findByIdAndUpdate(
req.params.id,
{ completed: true },
{ new: true }
);
res.send(task);
});

// Delete Task
router.delete('/:id', async (req, res) => {
await Task.findByIdAndDelete(req.params.id);
res.send({ message: 'Task deleted' });
});

module.exports = router;

82
FSD – 2 Lab Record

OUTPUT:

83
FSD – 2 Lab Record

(b) Design a Ǫuiz App using ReactJS


npx create-react-app quiz-app
cd quiz-app
npm start
import React, { useState } from 'react';

const questions = [
{
question: "What is the capital of France?",
options: ["Paris", "London", "Berlin", "Madrid"],
answer: "Paris"
},
{
question: "What is 2 + 2?",
options: ["3", "4", "5", "6"],
answer: "4"
},
{
question: "Who wrote 'Hamlet'?",
options: ["Shakespeare", "Tolstoy", "Homer", "Dante"],
answer: "Shakespeare"
}
];

function App() {
const [current, setCurrent] = useState(0);
const [score, setScore] = useState(0);
const [showScore, setShowScore] = useState(false);

const handleAnswer = (option) => {


if (option === questions[current].answer) {
setScore(score + 1);
}

const next = current + 1;


if (next < questions.length) {
setCurrent(next);
} else {
setShowScore(true);
}
};

return (
<div style={{ padding: '30px', textAlign: 'center' }}>
{showScore ? ( <h2>You scored {score} out of {questions.length}</h2> ):(

84
FSD – 2 Lab Record

85
FSD – 2 Lab Record

<>

<h3>{questions[current].question}</h3>
{questions[current].options.map((opt, index) => (
<button
key={index}
onClick={() => handleAnswer(opt)}
style={{
display: 'block',
margin: '10px auto',
padding: '10px 20px',
backgroundColor: '#4CAF50',
color: 'white',
border: 'none',
borderRadius: '8px',
cursor: 'pointer'
}}
>
{opt}
</button>
))}
</>
)}
</div>
);
}

export default App;

86
FSD – 2 Lab Record

87

You might also like