0% found this document useful (0 votes)
6 views35 pages

Full Stack Development

The document outlines various experiments in Full Stack Development, focusing on Node.js, TypeScript, CSS, HTML5, and ExpressJS. It includes code examples for creating web servers, handling HTTP requests, file operations, and building a To-Do list application. Additionally, it covers routing, HTTP methods, and CRUD operations using ExpressJS.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views35 pages

Full Stack Development

The document outlines various experiments in Full Stack Development, focusing on Node.js, TypeScript, CSS, HTML5, and ExpressJS. It includes code examples for creating web servers, handling HTTP requests, file operations, and building a To-Do list application. Additionally, it covers routing, HTTP methods, and CRUD operations using ExpressJS.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

FSD2

FULLSTACK DEVELOPMENT - 2
Experiment 1: [Link]
a. Write a program to show the workflow of JavaScript code executable by
creating web server in [Link].

Description:
This program creates a basic [Link] server using the http module.
It listens on port 3000 and sends a plain text response to the browser.

Program:

const http = require('http'); // Import http module

// Create web server


const server = [Link]((req, res) => {
[Link](200, { 'Content-Type': 'text/plain' }); // Set header
[Link]('Hello! [Link] server is running'); // Response message
});

// Server listening on port 3000


[Link](3000, () => {
[Link]('Server is running at [Link]
});

Explanation:

 [Link]() creates server that listens to HTTP requests.


 [Link]() sets HTTP status and content-type.
 [Link]() sends the final response to the client.

b. Write a program to transfer data over http protocol using http module.

Description:
This program sends HTML content to the client browser using [Link] HTTP module.
It responds with a heading and paragraph.

Program:

const http = require('http');

[Link]((req, res) =>{


[Link](200, { 'Content-Type': 'text/html' }); // Set HTML response
[Link]('<h1>HTTP Module in [Link]</h1><p>Data transferred
successfully.</p>');
[Link](); // End response
})
.listen(4000, () => {
[Link]('Server running at [Link]
FSD2

});

Explanation:

 [Link]() sends HTML tags as part of response.


 Browser displays it as formatted HTML.
 Server runs at localhost:4000.

c. Create a text file [Link] and add the following content to it. (HTML, CSS,
Javascript, Typescript, MongoDB, [Link], [Link], [Link])

Description:
This program uses the [Link] fs module to create a file [Link] and write content into it.

Program:

const fs = require('fs'); // File system module

const content = 'HTML, CSS, Javascript, Typescript, MongoDB, [Link],


[Link], [Link]';

[Link]('[Link]', content, (err) => {


if (err) throw err;
[Link]('[Link] created with content successfully.');
});

Explanation:

 [Link]() creates a file or replaces it if it exists.


 content string is written into [Link].

d. Write a program to parse an URL using URL module.

Description:
This program demonstrates how to extract parts of a URL using the [Link] URL module.

Program:

const url = require('url');

const address = '[Link]

const parsedUrl = new URL(address);

[Link]('Host:', [Link]);
[Link]('Pathname:', [Link]);
[Link]('Query param (name):', [Link]('name'));
[Link]('Query param (city):', [Link]('city'));
FSD2

Explanation:

 new URL() parses the full URL string.


 [Link]() fetches query values like name, city.

e. Write a program to create a user-defined module and show the workflow of


modularization of application using [Link]

Description:
This example shows how to create your own module ([Link]) and import it into a
main file ([Link]).

Step 1 – [Link]

// [Link]
function greet(name) {
return 'Hello, ' + name + '!';
}

[Link] = { greet };

Step 2 – [Link]

// [Link]
const myModule = require('./myModule');

const message = [Link]('Student');


[Link](message);

Explanation:

 [Link] exports the function from one file.


 require() imports it in another file.
 This shows modularity in [Link].

Experiment 2: TypeScript
a. Write a program to understand simple and special types.

Description:
This program demonstrates TypeScript types like number, string, and the special type any.

Program:

let id: number = 101;


let name: string = "Aarav";
let anything: any = "Hello";
FSD2

[Link]("ID:", id);
[Link]("Name:", name);
[Link]("Any Type:", anything);

Explanation:

 number, string are strict types.


 any allows any value, useful in dynamic situations.

b. Write a program to understand function parameter and return types.

Description:
This function accepts two numbers and returns their sum, showing how parameter and return
types work.

Program:

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


return a + b;
}

let result = add(5, 3);


[Link]("Sum is:", result);

Explanation:

 a: number, b: number are typed parameters.


 : number after function shows return type.

c. Write a program to show the importance with Arrow function. Use


optional, default and REST parameters.

Description:
This arrow function shows how to use optional, default, and rest parameters in TypeScript.

Program:

const greet = (name: string = "Student", age?: number, ...skills:


string[]): void => {
[Link]("Name:", name);
if (age !== undefined) [Link]("Age:", age);
[Link]("Skills:", [Link](", "));
};

greet("Aadhiya", 22, "HTML", "CSS", "TS");

Explanation:
FSD2

 name = "Student" is a default parameter.


 age? is optional.
 ...skills gathers rest of arguments into an array.

d. Write a program to understand the working of typescript with class,


constructor, properties, methods and access specifiers.

Description:
This code defines a Person class with public and private members, constructor, and a
method.

Program:

class Person {
public name: string;
private age: number;

constructor(name: string, age: number) {


[Link] = name;
[Link] = age;
}

public greet(): void {


[Link]("Hi, my name is", [Link]);
}
}

const p = new Person("Aarav", 21);


[Link]();

Explanation:

 public → accessible everywhere


 private → accessible only inside class
 greet() is a method to print name

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

Description:
Namespaces group functions under a single name, helping organize large code.

Program:

namespace MathOperations {
export function square(x: number): number {
return x * x;
}
}
FSD2

[Link]("Square of 5:", [Link](5));

Explanation:

 namespace groups related code


 export makes function accessible outside namespace

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


constraints.

Description:
Generics let you write flexible, reusable code that works with different types.

Program:

function display<T>(value: T): void {


[Link]("Value:", value);
}

display<string>("Hello TypeScript");
display<number>(101);

Explanation:

 <T> is a generic placeholder


 Replaces T with actual type during function call

Experiment 3: CSS Program for 2D and 3D


Transformations
Question: Write a CSS program to apply 2D and 3D transformations in a web page.

Description:

This program creates a colored box that uses CSS transformations.


It demonstrates both 2D (rotate, scale) and 3D (rotateY) effects when hovered.

Full Program:
<!DOCTYPE html>
<html>
<head>
<title>2D and 3D Transformations</title>
<style>
body {
FSD2

font-family: Arial, sans-serif;


background-color: #f2f2f2;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}

.container {
perspective: 1000px; /* Enables 3D perspective */
}

.box {
width: 200px;
height: 200px;
background-color: coral;
color: white;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
transition: transform 0.6s;
transform: rotate(10deg) scale(1.1); /* 2D Transformation */
transform-style: preserve-3d; /* Keeps child 3D transforms */
}

.box:hover {
transform: rotateY(180deg); /* 3D Transformation on hover */
background-color: teal;
}
</style>
</head>
<body>

<div class="container">
<div class="box">
Hover Me!
</div>
</div>

</body>
</html>

Explanation:

 .box is a square box styled with a background and centered text


 rotate(10deg) and scale(1.1) apply 2D rotation and scaling
 perspective: 1000px in .container enables 3D view
 rotateY(180deg) flips the box around the Y-axis when hovered
 transition: transform 0.6s makes the animation smooth
FSD2

Experiment 4: Web Page with New Features of


HTML5 and CSS3
Question: Create a web page with new features of HTML5 and CSS3.

Description:

This program demonstrates new HTML5 semantic tags (header, section, article, footer)
and CSS3 features.
It includes form elements, layout styling, shadows, transitions, and media queries.

Full Program:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML5 + CSS3 Demo</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f9f9f9;
}

header {
background-color: #2c3e50;
color: white;
text-align: center;
padding: 20px;
}

nav {
background-color: #34495e;
padding: 10px;
text-align: center;
}

nav a {
color: white;
margin: 0 15px;
text-decoration: none;
font-weight: bold;
}

section {
padding: 20px;
}

article {
background: white;
padding: 15px;
margin-bottom: 20px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
transition: transform 0.3s;
FSD2

article:hover {
transform: scale(1.02);
}

footer {
background-color: #2c3e50;
color: white;
text-align: center;
padding: 10px;
position: fixed;
width: 100%;
bottom: 0;
}

@media screen and (max-width: 600px) {


nav a {
display: block;
margin: 10px 0;
}
}
</style>
</head>
<body>

<header>
<h1>My HTML5 + CSS3 Page</h1>
</header>

<nav>
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Contact</a>
</nav>

<section>
<article>
<h2>What is HTML5?</h2>
<p>HTML5 is the latest version of the HTML standard. It includes new
semantic tags, multimedia support, and form enhancements.</p>
</article>

<article>
<h2>What is CSS3?</h2>
<p>CSS3 adds modern styling features like transitions, transformations,
shadows, and media queries to enhance web design.</p>
</article>
</section>

<footer>
&copy; 2025 My Web Page
</footer>

</body>
</html>

Explanation:

 header, nav, section, article, footer are new semantic elements


FSD2

 CSS3 features:
o box-shadow, transition, transform (modern effects)
o media query makes the nav responsive on small screens
 Clean and modern layout for teaching real-world usage

Experiment 5: To-Do List Application Using


JavaScript
Question: Design a To-Do List application using JavaScript.

Description:

This application allows the user to type tasks and display them in a list.
It uses HTML for layout, CSS for design, and JavaScript to manage tasks.

Program:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do List App</title>
<style>
body {
font-family: Arial;
background: #f2f2f2;
text-align: center;
padding: 50px;
}

#todo-container {
background: white;
padding: 20px;
width: 300px;
margin: auto;
box-shadow: 0 0 10px rgba(0,0,0,0.2);
}

input {
padding: 10px;
width: 80%;
margin-bottom: 10px;
}

button {
padding: 10px;
background-color: teal;
color: white;
border: none;
cursor: pointer;
}

ul {
FSD2

list-style: none;
padding: 0;
}

li {
background: #e0e0e0;
padding: 10px;
margin: 5px 0;
}
</style>
</head>
<body>

<div id="todo-container">
<h2>My To-Do List</h2>
<input type="text" id="taskInput" placeholder="Enter your task here">
<button onclick="addTask()">Add Task</button>
<ul id="taskList"></ul>
</div>

<script>
function addTask() {
const input = [Link]("taskInput");
const task = [Link]();

if (task === "") {


alert("Please enter a task");
return;
}

const li = [Link]("li");
[Link] = task;

[Link]("taskList").appendChild(li);
[Link] = "";
}
</script>

</body>
</html>

Explanation:

 input field takes task name


 addTask() function creates <li> element and appends it to the list
 Simple design with shadows and spacing
 Fully client-side — no server or database needed
FSD2

Experiment 6: ExpressJS – Routing, HTTP


Methods, Middleware
(a) Question:

Write a program to define a route, Handling Routes, Route Parameters, Query


Parameters and URL building.

Description:

This program defines multiple routes using Express. It handles URL route parameters, query
strings, and shows how to build dynamic URLs.

Program:
// Filename: [Link]
const express = require('express');
const app = express();

// Route without parameters


[Link]('/', (req, res) => {
[Link]('Welcome to Home Page');
});

// Route with parameter


[Link]('/user/:name', (req, res) => {
[Link]('Hello ' + [Link]);
});

// Route with query parameter


[Link]('/search', (req, res) => {
const keyword = [Link].q;
[Link]('You searched for: ' + keyword);
});

[Link](3000, () => {
[Link]('Server running at [Link]
});

Explanation:

 [Link]: Gets value from URL /user/Alex → “Alex”


 [Link].q: Gets value from URL /search?q=nodejs → “nodejs”
 Routes respond with simple text for clarity.
FSD2

(b) Question:

Write a program to accept data, retrieve data and delete a specified resource using http
methods.

Description:

This code uses Express with GET, POST, and DELETE HTTP methods. It simulates basic
CRUD using in-memory array.

Program:
// Filename: [Link]
const express = require('express');
const app = express();
[Link]([Link]());

let users = ['Alice', 'Bob'];

// GET: retrieve data


[Link]('/users', (req, res) => {
[Link](users);
});

// POST: accept data


[Link]('/users', (req, res) => {
[Link]([Link]);
[Link]('User added');
});

// DELETE: delete by index


[Link]('/users/:id', (req, res) => {
[Link]([Link], 1);
[Link]('User deleted');
});

[Link](3001, () => {
[Link]('Server running at [Link]
});

Explanation:

 GET /users shows all users


 POST /users adds a new user (body: { "name": "Charlie" })
 DELETE /users/1 removes second user (Bob)

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

Description:

This example uses middleware to log each request before routing. Middleware can run before
route handlers.
FSD2

Program:
// Filename: [Link]
const express = require('express');
const app = express();

// Custom middleware
[Link]((req, res, next) => {
[Link]('Request URL:', [Link]);
next(); // move to next handler
});

[Link]('/', (req, res) => {


[Link]('Middleware example');
});

[Link](3002, () => {
[Link]('Server running at [Link]
});

Explanation:

 Middleware runs before route handlers


 Logs the URL of every request
 next() passes control to next handler

Experiment 7: ExpressJS – Templating, Form Data


(a) Question: Write a program using templating engine.

Description:

This program uses the EJS templating engine in ExpressJS to render HTML pages
dynamically with variables.

Program:

1. Install EJS (in terminal):

Bash :
npm install express ejs

2. Project Structure:

Pgsql :

project/
├── views/
│ └── [Link]
└── [Link]
FSD2

3. File: [Link]

const express = require('express');


const app = express();

[Link]('view engine', 'ejs');

[Link]('/', (req, res) => {


[Link]('index', { name: 'Student' });
});

[Link](3003, () => {
[Link]('Server running at [Link]
});

4. File: views/[Link]

<!DOCTYPE html>
<html>
<head><title>EJS Example</title></head>
<body>
<h1>Welcome, <%= name %>!</h1>
</body>
</html>

Explanation:

 EJS renders HTML with <%= variable %> syntax.


 Page shows "Welcome, Student!" dynamically using name.

(b) Question: Write a program to work with form data.

Description:

This ExpressJS program creates an HTML form and processes submitted data using POST
method.

Program:

1. Install Express & Body Parser:

Bash :
npm install express

2. File: [Link]

const express = require('express');


const app = express();
[Link]([Link]({ extended: true }));

[Link]('/', (req, res) => {


[Link](`
FSD2

<form action="/submit" method="post">


Name: <input type="text" name="name" />
<button type="submit">Submit</button>
</form>
`);
});

[Link]('/submit', (req, res) => {


[Link]('Hello, ' + [Link]);
});

[Link](3004, () => {
[Link]('Server running at [Link]
});

Explanation:

 / route shows a simple form


 On submit, POST /submit reads the name and replies "Hello, name"
 [Link]() helps to parse form data

Experiment 8: ExpressJS – Cookies, Sessions,


Authentication
(a) Question: Write a program for session management using cookies and
sessions.

Description:

This program uses cookies and session to store a user's visit count. It remembers the user
across requests.

Program:

1. Install required packages:

Bash :
npm install express express-session cookie-parser

2. File: [Link]

const express = require('express');


const session = require('express-session');
const cookieParser = require('cookie-parser');

const app = express();


[Link](cookieParser());
[Link](session({
secret: 'mysecret',
resave: false,
saveUninitialized: true
FSD2

}));

[Link]('/', (req, res) => {


if ([Link]) {
[Link]++;
[Link]('Visit count: ' + [Link]);
} else {
[Link] = 1;
[Link]('Welcome! This is your first visit.');
}
});

[Link](3005, () => {
[Link]('Server running at [Link]
});

Explanation:

 First visit → session sets views = 1


 Next visit → session remembers and increases count
 Uses cookies to track session ID

(b) Question: Write a program for user authentication.

Description:

This simple login system checks hardcoded credentials and creates a session if login is
successful.

Program:

1. Install required packages:

Bash :
npm install express express-session body-parser

2. File: [Link]

const express = require('express');


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

const app = express();


[Link]([Link]({ extended: true }));

[Link](session({
secret: 'secretKey',
resave: false,
saveUninitialized: true
}));

const user = { username: 'admin', password: '1234' };


FSD2

[Link]('/', (req, res) => {


if ([Link]) {
[Link]('Welcome, ' + [Link]);
} else {
[Link](`
<form method="post" action="/login">
Username: <input name="username" /><br>
Password: <input type="password" name="password" /><br>
<button type="submit">Login</button>
</form>
`);
}
});

[Link]('/login', (req, res) => {


const { username, password } = [Link];
if (username === [Link] && password === [Link]) {
[Link] = true;
[Link] = username;
[Link]('/');
} else {
[Link]('Invalid credentials');
}
});

[Link](3006, () => {
[Link]('Server running at [Link]
});

Explanation:

 User logs in with username: admin and password: 1234


 If correct → creates session and greets user
 If wrong → shows "Invalid credentials"

Experiment 9: ExpressJS – Database, RESTful APIs


(a) Question: Write a program to connect MongoDB database using
Mongoose and perform CRUD operations.

Description:

This program connects to MongoDB using Mongoose and performs simple Create, Read,
Update, and Delete (CRUD) operations on a student database.

Program (with steps):

1. Install required packages:

Bash :
npm install express mongoose body-parser
FSD2

2. File: [Link]

const express = require('express');


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

const app = express();


[Link]([Link]());

[Link]('mongodb://[Link]:27017/mydb')
.then(() => [Link]('Connected to MongoDB'))
.catch(err => [Link](err));

const studentSchema = new [Link]({


name: String,
age: Number
});
const Student = [Link]('Student', studentSchema);

// Create
[Link]('/students', async (req, res) => {
const student = new Student([Link]);
await [Link]();
[Link]('Student added!');
});

// Read
[Link]('/students', async (req, res) => {
const students = await [Link]();
[Link](students);
});

// Update
[Link]('/students/:id', async (req, res) => {
await [Link]([Link], [Link]);
[Link]('Student updated!');
});

// Delete
[Link]('/students/:id', async (req, res) => {
await [Link]([Link]);
[Link]('Student deleted!');
});

[Link](3009, () => {
[Link]('Server running on [Link]
});

Explanation:

 MongoDB stores students collection.


 We can add, view, update, or delete a student.
 Mongoose handles MongoDB operations easily.
FSD2

(b) Question: Write a program to develop a single page application using


RESTful APIs.

Description:

This example shows how frontend and backend connect using REST APIs to display student
data on a single HTML page.

Backend API ([Link]):


const express = require('express');
const cors = require('cors');
const app = express();
[Link](cors());

const students = [
{ id: 1, name: "Rahul", age: 20 },
{ id: 2, name: "Priya", age: 21 }
];

[Link]('/api/students', (req, res) => {


[Link](students);
});

[Link](3010, () => {
[Link]('Server running on [Link]
});

Frontend ([Link]):
<!DOCTYPE html>
<html>
<head><title>Student App</title></head>
<body>
<h2>Student List</h2>
<ul id="list"></ul>

<script>
fetch('[Link]
.then(res => [Link]())
.then(data => {
const ul = [Link]('list');
[Link](s => {
const li = [Link]('li');
[Link] = `${[Link]} - ${[Link]} years`;
[Link](li);
});
});
</script>
</body>
</html>

Explanation:

 Backend serves data using /api/students endpoint.


 Frontend fetches and displays the data dynamically.
FSD2

Experiment 10: ReactJS – Render HTML, JSX,


Components
(a) Question: Write a program to render HTML to a web page.

Description:

This program uses React to render a heading and paragraph on a webpage.

Program ([Link])
import React from 'react';
import ReactDOM from 'react-dom';

const App = () => {


return (
<div>
<h1>Welcome to React</h1>
<p>This is rendered using React.</p>
</div>
);
};

[Link](<App />, [Link]('root'));

(b) Question: Write a program for writing markup with JSX.

Description:

JSX allows HTML-like syntax in JavaScript. This program shows how JSX looks in React.

Program:
const element = (
<div>
<h2>Hello JSX!</h2>
<p>This is a JSX paragraph.</p>
</div>
);

[Link](element, [Link]('root'));

(c) Question: Write a program for creating and nesting components (function
and class).

Description:
FSD2

This example demonstrates function and class components nested inside another component.

Program:
import React from 'react';

function Header() {
return <h1>Welcome!</h1>;
}

class Message extends [Link] {


render() {
return <p>This is a class component.</p>;
}
}

function App() {
return (
<div>
<Header />
<Message />
</div>
);
}

export default App;

Experiment 11: ReactJS – Props, State, Styling, Events


(a) Question: Write a program to work with props and states.

Description:

Props are used to pass data. State holds data inside a component.

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

function Greeting(props) {
return <h2>Hello, {[Link]}!</h2>;
}

function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<Greeting name="Aadi" />
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

export default Counter;


FSD2

(b) Question: Write a program to add styles (CSS & Sass Styling) and display
data.

Description:

This program adds simple inline CSS and displays student data.

Program:
const style = {
color: 'blue',
fontSize: '20px'
};

function Student() {
const name = "Ravi";
return <p style={style}>Student Name: {name}</p>;
}

export default Student;

(c) Question: Write a program for responding to events.

Description:

This program shows how to handle button click events in React.

Program:
function EventDemo() {
const showMsg = () => {
alert('Button clicked!');
};

return (
<button onClick={showMsg}>Click Me</button>
);
}

export default EventDemo;


FSD2

Experiment 12: ReactJS – Conditional Rendering,


Rendering Lists, React Forms
(a) Question: Write a program for conditional rendering.

Description:
This React app conditionally renders content based on a logged-in state. It switches between
"Welcome" and "Please Login".

Program:
// File: [Link]
import React, { useState } from 'react';

function App() {
const [loggedIn, setLoggedIn] = useState(false);

return (
<div>
<h2>{loggedIn ? 'Welcome User!' : 'Please Login'}</h2>
<button onClick={() => setLoggedIn(!loggedIn)}>
{loggedIn ? 'Logout' : 'Login'}
</button>
</div>
);
}

export default App;

Explanation:

 loggedIn is a boolean state.


 Based on its value, the UI switches between two messages and button text.

(a) Question: Write a program for rendering lists.

Description:
This React app displays a list of fruits using map() to render them in an unordered list.

Program :
// File: [Link]
import React from 'react';

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

return (
<div>
<h2>Fruit List</h2>
<ul>
FSD2

{[Link]((fruit, index) => (


<li key={index}>{fruit}</li>
))}
</ul>
</div>
);
}

export default App;

Explanation:

 map() is used to loop through an array.


 Each item is shown as an <li> inside <ul>.

Experiment 13: ReactJS – React Router, Updating the


Screen
(a) Question: Write a program for routing to different pages using React Router.

Description :
React Router allows switching between pages without reloading the browser. It helps in
building a single-page application with multiple views.

Program ([Link]):
// Step 1: Install router
// npm install react-router-dom

import React from 'react';


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

function Home() {
return <h2>This is Home Page</h2>;
}

function About() {
return <h2>This is About Page</h2>;
}

function App() {
return (
<Router>
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
FSD2

export default App;

Explanation:
React Router handles page switching without refreshing the page. Route matches the URL,
and Link is used for navigation.

(b) Question : Write a program for updating the screen.

Description :
React updates the UI automatically when the state or props change. Here, we change the
screen by updating the state.

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

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

const handleClick = () => {


setMessage("You clicked the button!");
};

return (
<div>
<h2>{message}</h2>
<button onClick={handleClick}>Click Me</button>
</div>
);
}

export default App;

Explanation:
State is updated using setMessage(), which causes React to re-render the screen with the
new message.

Experiment 14 : ReactJS – Hooks, Sharing Data Between


Components
(a) Question : Write a program to understand the importance of using hooks.

Description:
Hooks like useState allow functional components to manage state. Before hooks, state was
only in class components. Now, it's easier and cleaner in functions.
FSD2

Program ([Link]):
import React, { useState } from 'react';

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

return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}

export default App;

Explanation:
The useState hook creates a count variable that updates when the button is clicked. The UI
updates automatically when state changes.

(b) Question : Write a program for sharing data between components.

Description :
Data is passed from parent to child using props. This is the simplest way to share data
between React components.

Program ([Link]):
import React from 'react';

function Child(props) {
return <h3>Hello, {[Link]}</h3>;
}

function App() {
return (
<div>
<h2>Welcome Message</h2>
<Child name="Student" />
</div>
);
}

export default App;

Explanation:
App sends the name to Child using props. The child component uses [Link] to show
personalized content.
FSD2

Experiment 15 : ReactJS Applications – To-do list and


Quiz
(a) Question : Design a to-do list application.

Description:
A to-do app helps users add and delete tasks. It uses React's state to manage the task list and
update the UI when tasks change.

Program ([Link]):
import React, { useState } from 'react';

function App() {
const [task, setTask] = useState(""); // stores input task
const [tasks, setTasks] = useState([]); // stores all tasks

// Adds new task to the list


const addTask = () => {
if (task !== "") {
setTasks([...tasks, task]);
setTask(""); // Clear input field
}
};

// Deletes task by index


const deleteTask = (index) => {
const newTasks = [Link]((t, i) => i !== index);
setTasks(newTasks);
};

return (
<div>
<h2>To-do List</h2>
<input
type="text"
value={task}
onChange={(e) => setTask([Link])}
placeholder="Enter task"
/>
<button onClick={addTask}>Add</button>

<ul>
{[Link]((t, index) => (
<li key={index}>
{t} <button onClick={() => deleteTask(index)}>❌</button>
</li>
))}
</ul>
</div>
);
}

export default App;


FSD2

Explanation:
We use useState for the input field and the task list. On clicking "Add", it stores the task
and updates the list. Clicking "❌" removes that task.

Experiment 16 : MongoDB – Installation, Configuration,


CRUD operations
(a) Question : Install MongoDB and configure ATLAS.

Description:
MongoDB Atlas is a cloud-based database service. We can store, manage, and access
MongoDB databases online without installing it locally.

Steps to Configure MongoDB Atlas:

1. Go to [Link]
2. Create a free account or log in.
3. Click "Create" → Choose Shared → Select AWS and region (like Mumbai).
4. Create a username and password.
5. Add IP address: Choose Allow access from anywhere ([Link]/0).
6. Click "Connect" → Choose Connect your application.
7. Copy the connection string like:

Bash :
mongodb+srv://<username>:<password>@[Link]/mydb?
retryWrites=true&w=majority

8. Replace <username> and <password> with your MongoDB credentials.

(b) Question : Write MongoDB queries to perform CRUD operations using


insert(), find(), update(), remove().

Description :
These queries help insert, read, update, and delete documents from a collection in MongoDB.

Program (Mongo Shell or MongoDB Compass):


// Switch to a database (creates if not exists)
use mydb

// CREATE – Insert one document


[Link]({ name: "Aarav", age: 21, branch: "CSE" })
FSD2

// READ – Find all documents


[Link]()

// UPDATE – Update a student's age


[Link](
{ name: "Aarav" },
{ $set: { age: 22 } }
)

// DELETE – Remove a document


[Link]({ name: "Aarav" })

Explanation:

 insertOne() adds a document.


 find() reads the collection.
 updateOne() modifies a document with $set.
 deleteOne() removes a document based on condition.

Experiment 17 : MongoDB – Databases, Collections, and


Records
(a) Question : Write MongoDB queries to create and drop databases and
collections.

Description:
MongoDB allows creation of databases and collections dynamically. It also provides
commands to delete (drop) them when not needed.

Program (Mongo Shell or MongoDB Compass):


// Create or switch to a database
use mycollege

// Create a collection by inserting a document


[Link]({ name: "Riya", age: 20 })

// Show current databases


show dbs

// Show collections in current DB


show collections

// Drop collection
[Link]()

// Drop database
[Link]()

Explanation:
FSD2

 use selects a database (and creates if doesn't exist).


 A collection is auto-created when you insert a document.
 drop() deletes a collection.
 dropDatabase() deletes the entire DB.

(b) Question : Write MongoDB queries to work with records using find(),
limit(), sort(), createIndex(), aggregate().

Description:
MongoDB supports powerful queries for filtering, limiting results, sorting, indexing for fast
search, and aggregation for data analysis.

Program (Mongo Shell):


// Insert multiple student records
[Link]([
{ name: "Anu", age: 22, branch: "ECE" },
{ name: "Kiran", age: 21, branch: "CSE" },
{ name: "Meena", age: 23, branch: "IT" }
])

// Find all students


[Link]()

// Limit to 2 students
[Link]().limit(2)

// Sort students by age descending


[Link]().sort({ age: -1 })

// Create index on name for faster search


[Link]({ name: 1 })

// Aggregate: Group by branch and count students


[Link]([
{ $group: { _id: "$branch", total: { $sum: 1 } } }
])

Explanation:

 limit() restricts number of results.


 sort() orders the documents.
 createIndex() improves search speed.
 aggregate() groups data, like SQL GROUP BY.
FSD2

Experiment 18 : Augmented Program – To-Do List using


NodeJS and ExpressJS
(a) Question : Design a to-do list application using NodeJS and ExpressJS.

Description:
This program creates a simple to-do list backend where you can add, view, and delete tasks
using RESTful APIs built with NodeJS and ExpressJS. Data is stored in memory for
simplicity.

Program (File: [Link]):


const express = require('express');
const app = express();
[Link]([Link]());

let todos = []; // In-memory task list


let idCounter = 1;

// Add a task
[Link]('/todos', (req, res) => {
const task = { id: idCounter++, text: [Link] };
[Link](task);
[Link]({ message: "Task added", task });
});

// Get all tasks


[Link]('/todos', (req, res) => {
[Link](todos);
});

// Delete a task by ID
[Link]('/todos/:id', (req, res) => {
const id = parseInt([Link]);
todos = [Link](task => [Link] !== id);
[Link]({ message: "Task deleted" });
});

// Server listening
[Link](3020, () => {
[Link]("To-Do server running at [Link]
});

Explanation:

 REST API endpoints:


POST /todos adds a task
GET /todos shows all tasks
DELETE /todos/:id removes a task
 Uses [Link]() middleware to parse request body.
FSD2

Experiment 19 : Augmented Program – Quiz App using


ReactJS
(a) Question : Design a Quiz App using ReactJS.

Description:
This is a simple quiz application built with ReactJS. It shows one question at a time and
tracks the user's score. The quiz ends after all questions are answered.

Program (File: [Link])


import React, { useState } from 'react';

const questions = [
{
question: "What is the capital of India?",
options: ["Mumbai", "Delhi", "Kolkata", "Chennai"],
answer: "Delhi"
},
{
question: "Which language runs in a web browser?",
options: ["Java", "C", "Python", "JavaScript"],
answer: "JavaScript"
}
];

function QuizApp() {
const [index, setIndex] = useState(0); // Current question index
const [score, setScore] = useState(0); // User score
const [showResult, setShowResult] = useState(false); // Show result flag

const handleOptionClick = (option) => {


if (option === questions[index].answer) {
setScore(score + 1); // Increment score if correct
}

const nextIndex = index + 1;


if (nextIndex < [Link]) {
setIndex(nextIndex); // Show next question
} else {
setShowResult(true); // End of quiz
}
};

return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h2>React Quiz App</h2>
{!showResult ? (
<div>
<h3>{questions[index].question}</h3>
{questions[index].[Link]((opt, i) => (
<button key={i} onClick={() => handleOptionClick(opt)} style={{
margin: '5px' }}>
{opt}
</button>
))}
</div>
FSD2

) : (
<div>
<h3>Quiz Finished!</h3>
<p>Your Score: {score} / {[Link]}</p>
</div>
)}
</div>
);
}

export default QuizApp;

Explanation:

 React state is used to track the current question, score, and whether to show results.
 On clicking an option, the app checks the answer and moves to the next question.
 After the last question, it displays the score.

Experiment 20 : MongoDB Certification


(a) Question : Complete the MongoDB certification from the MongoDB
University website.

Description:
This experiment requires students to enroll in an official MongoDB course provided by
MongoDB University. The certification helps build real-world knowledge of database
concepts, CRUD operations, indexing, aggregation, and performance tuning.

Steps to Complete Certification:

1. Visit the site:


Go to [Link]
2. Create a MongoDB Account:
Sign up using your email or GitHub account.
3. Enroll in a course:
Recommended beginner course:
o MongoDB Basics – Covers databases, collections, documents, CRUD, and
queries.
4. Follow video modules:
Learn through videos, quizzes, and hands-on labs.
5. Pass the final exam:
You must complete the final graded assessment to earn the certificate.
6. Download the certificate:
After completion, download your certificate and upload it to your portfolio or resume.

Explanation:
This task ensures students gain professional training directly from MongoDB experts.
Completing the certification proves skills in MongoDB and enhances job opportunities in
backend and full-stack development
FSD2

You might also like