Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views43 pages

FSD - II - Lab Manual

This lab manual provides a comprehensive guide for installing and using Express.js in full stack development. It includes instructions for setting up Node.js, initializing projects, and implementing routing, middleware, and templating with Express. Additionally, it offers example code for handling HTTP methods and form data processing.

Uploaded by

bengwen1221
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)
4 views43 pages

FSD - II - Lab Manual

This lab manual provides a comprehensive guide for installing and using Express.js in full stack development. It includes instructions for setting up Node.js, initializing projects, and implementing routing, middleware, and templating with Express. Additionally, it offers example code for handling HTTP methods and form data processing.

Uploaded by

bengwen1221
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
You are on page 1/ 43

FULL STACK DEVELOPMENT – II

(SKILL ENHANCEMENT COURSE)


LAB MANUAL

B.Tech - III Year - I Semester


Department of Computer Science and Engineering

SREE VAHINI INSTITUTE OF SCIENCE AND TECHNOLOGY


(AUTONOMOUS)
Sai Vahini Nagar, NH-30, Tiruvuru - NTR Dist, A.P.
How to Install Express.js

1. Install Node.js and npm


If not already installed:
sudo apt update
sudo apt install nodejs npm
Check versions to confirm:
node -v
npm -v

Expected: You should see v16.x.x, v18.x.x, or higher.


If it's something like v12.x.x or v14.x.x, you're still using the old version.
Fully Remove the Old Node.js
Run these commands to clean up the old version:

sudo apt purge nodejs

sudo rm -rf /usr/local/bin/node /usr/local/bin/npm /usr/bin/node /usr/bin/npm

Check again:

node -v
# should say "command not found"

Reinstall Node.js (Stable LTS version)

Install Node.js 18 (or latest LTS):

curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -


sudo apt install -y nodejs

Now check the version:

node -v
# should be v18.x.x

Clean your node_modules and reinstall dependencies

Now that you have the correct Node version:

cd ~/Desktop/23MG1A0593
rm -rf node_modules package-lock.json
npm install

Then run your program again:

node Program1.js

Full Stack Development – II 1 kkvprasad@CSE


1. Initialize your project (if you haven’t already)
Open your terminal and navigate to your project folder. Then run:
npm init -y
This creates a package.json file with default settings.

2. Install Express
Run the following command in your terminal:
npm install express
This downloads and installs Express and adds it to your package.json dependencies.

3. Steps to Install Node.js using NVM (Linux/macOS)


1. Install NVM
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
2. Load NVM into Terminal
source ~/.bashrc
Note: You may need to restart the terminal after installation.
3. Install and Use Node.js v20 (or any version)
nvm install 20
nvm use 20

4. Verify installation (optional)


You can check package.json and see express listed under dependencies:
"dependencies": {
"express": "^4.x.x"
}

6. Run your server


node app.js
Visit http://localhost:3000 in your browser, and you should see "Hello World!".

Full Stack Development – II 2 kkvprasad@CSE


1) Express JS – Routing, HTTP Methods, Middleware.
a) Write a program to define a route, Handling Routes, Route Parameters, Query
Parameters and URL building.

const express = require('express');


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

// Middleware to log each request


app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next();
});

// Root Route
app.get('/', (req, res) => {
res.send('Welcome to the Express.js Demo!');
});

// Route with Parameters (e.g., /user/42)


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

// Route with Multiple Parameters (e.g., /user/42/post/99)


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

// Route with Query Parameters (e.g., /search?q=node&page=2)


app.get('/search', (req, res) => {
const { q, page = 1 } = req.query; // default page = 1
res.send(`Search query: ${q}, Page: ${page}`);
});

// Route for URL building example


app.get('/build-url', (req, res) => {
// Dynamically building a URL
const userId = 123;
const query = 'express';
const builtUrl = `/user/${userId}/profile?search=${query}`;
res.send(`URL built: ${builtUrl}`);
});

// 404 handler
app.use((req, res) => {
res.status(404).send('Route not found.');
});

Full Stack Development – II 3 kkvprasad@CSE


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

➢ http://localhost:3000/
➢ http://localhost:3000/user/42
➢ http://localhost:3000/user/42/post/88
➢ http://localhost:3000/search?q=express&page=2
➢ http://localhost:3000/build-url

Full Stack Development – II 4 kkvprasad@CSE


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

const express = require('express');


const app = express();
const PORT = 3000;
app.use(express.json()); // Needed to parse JSON body
let items = {};
let nextId = 1;

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


{ res.send('API is running!');
});

app.post('/items', (req, res) =>


{ console.log('POST /items body:',
req.body);

const { name } = req.body;


if (!name) return res.status(400).json({ error: 'Name is required' });

const id = String(nextId++);
const item = { id, name };
items[id] = item;

res.status(201).json({ message: 'Item created', item });


});

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


{ res.json(Object.values(items));
});

app.get('/items/:id', (req, res) =>


{ const item =
items[req.params.id];
if (!item) return res.status(404).json({ error: 'Item not found' });
res.json(item);
});

app.delete('/items/:id', (req, res) =>


{ const id = req.params.id;
if (!items[id]) return res.status(404).json({ error: 'Item not found' });

delete items[id];
res.json({ message: `Item ${id} deleted` });
});

app.listen(PORT, () => {
console.log(`✅ Server running at http://localhost:${PORT}`);
});

Full Stack Development – II 5 kkvprasad@CSE


Start your server in the terminal:
bash
node app.js
You should see:
Server running at http://localhost:3000

Open a new terminal window and try these commands:


● Add an item:
curl -X POST http://localhost:3000/items -H "Content-Type: application/json" -d
"{\"name\":\"Notebook\"}"

● Get all items:


curl http://localhost:3000/items

● Get item by ID (e.g., 1):


curl http://localhost:3000/items/1

● Delete item by ID (e.g., 1):


curl -X DELETE http://localhost:3000/items/1

Full Stack Development – II 6 kkvprasad@CSE


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

const express = require('express');


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

// 1. Simple middleware function logging request details


app.use((req, res, next) => {
console.log(`[Middleware] ${req.method} request to ${req.url}`);
next(); // Pass control to the next middleware or route handler
});

// 2. Middleware to check for a custom header (authorization simulation)


app.use((req, res, next) => {
if (!req.headers['x-api-key']) {
return res.status(401).send('Unauthorized: x-api-key header missing');
}
console.log('[Middleware] x-api-key header found:', req.headers['x-api-key']);
next();
});

// 3. Route handler for root path


app.get('/', (req, res) =>
{ res.send('Hello from the root route!');
});

// 4. Another route
app.get('/test', (req, res) => {
res.send('Hello from /test route!');
});

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

What is middleware doing here?


1. The first middleware logs every incoming request.
2. The second middleware checks if the client sent an x-api-key header. If missing,
it responds with 401 Unauthorized and stops further processing.
3. If the key is present, the request passes to route handlers.
4. The routes respond accordingly.

● Start the server:


node app.js
Server listening on http://localhost:3000

Full Stack Development – II 7 kkvprasad@CSE


● Without API key header (should get unauthorized):
curl http://localhost:3000/
[Middleware] GET request to /

● With API key header:


curl -H "x-api-key: mysecretkey" http://localhost:3000/
[Middleware] GET request to /
[Middleware] x-api-key header found: mysecretkeys

Full Stack Development – II 8 kkvprasad@CSE


2. Express JS – Templating, Form Data
a) Write a program using templating engine.

Install the required dependencies in your project folder:


npm init -y
npm install express ejs body-parser

Folder Structure
project-folder/

├── views/
│ ├── form.ejs # Input form
│ └── result.ejs # Display submitted data

└── app.js # Express app
app.js
c
o
n
st
e
x
p
r
e
s
s
=
r
e
q
u
ir
e
('
e
x
p
r
e
s
s'
);
c
o

Full Stack Development – II 9 kkvprasad@CSE


n p
st .s
a e
p t(
p 'v
= i
e e
x w
p
r e
e n
s g
s i
() n
; e'
const port = 3000; ,
'e
// js
S ')
e ;
t
E // Middleware to parse form data (no need for
J body-parser as Express has it built-in)
S app.use(express.urlencoded({ extended: true }));
a
s /
t /
h
e R
t o
e u
m t
p e
l
a t
ti o
n
g s
e h
n o
g w
i
t
n
h
e
e
a
p
f
Full Stack Development – II 10 kkvprasad@CSE
o r
r m
m '
)
a ;
p });
p
. //
g R
e o
t u
( t
' e
/ t
' o
, h
a
( n
r d
e l
q e
, f
o
r r
e m
s
) s
u
= b
> m
is
{
si
o
r
n
e
a
s
p
.
p
r
.
e
p
n
o
d
st
e
('
r
/s
(
u
'
b
f
m
o
Full Stack Development – II 11 kkvprasad@CSE
it 'r
', e
(r s
e u
q lt
, ',
r {
e n
s a
) m
= e,
> e
{ m
c a
o il
n }
st );
{ });
n
a /
m /
e,
e S
m t
a a
il r
} t
=
r t
e h
q e
.
b s
o e
d r
y v
; e
r r
e
s. a
r p
e p
n .
d l
e i
r( s

Full Stack Development – II 12 kkvprasad@CSE


t
e
n
(
p
o
r
t
,

(
)

=
>

{
console.log(`Server is running at http://localhost:
${port}`);
});

Full Stack Development – II 13 kkvprasad@CSE


views/form.ejs
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Enter Your Details</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>

<button type="submit">Submit</button>
</form>
</body>
</html>

views/result.ejs
<!DOCTYPE html>
<html>
<head>
<title>Result</title>
</head>
<body>
<h1>Form Submitted</h1>
<p><strong>Name:</strong> <%= name %></p>
<p><strong>Email:</strong> <%= email %></p>
</body>
</html>
How to Run
npm init -y
npm install express ejs
1. Start your server:
node app.js
2. Open your browser and visit: http://localhost:3000

Full Stack Development – II 14 kkvprasad@CSE


b) Write a program to work with form data.

const express = require('express');


const bodyParser = require('body-parser');
const app = express();
const port = 3000;

// Middleware to parse form data


app.use(bodyParser.urlencoded({ extended: true }));

// Serve form at root path


app.get('/', (req, res) => {
res.send(`
<h1>User Form</h1>
<form method="POST" action="/submit">
<label>Name:</label><br>
<input type="text" name="name" required><br><br>
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
<button type="submit">Submit</button>
</form>
`);
});

// Handle form submission


app.post('/submit', (req, res) => {
const { name, email } = req.body;
res.send(`
<h1>Form Received</h1>
<p><strong>Name:</strong> ${name}</p>
<p><strong>Email:</strong> ${email}</p>
`);
});

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

1. Save the code in app.js.


2. Make sure you're in the project folder.
3. Install dependencies if not already:
● npm install express body-parser
4. Start the server:
● node app.js
5. Open your browser and visit: http://localhost:3000

Full Stack Development – II 15 kkvprasad@CSE


3. Express JS – Cookies, Sessions, Authentication

npm init -y
npm install express express-session cookie-parser

a) Write a program for session management using cookies and sessions.

const express = require('express');


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

const app = express();


const PORT = 3000;

// Middleware to parse form data and cookies


app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

// Session configuration
app.use(session({
secret: 'mySecretKey', // Secret for signing the session ID cookie
resave: false, // Don't save session if unmodified
saveUninitialized: false, // Don't create session until something is stored
cookie: { maxAge: 60000 } // Session expires after 1 minute
}));

// Dummy credentials
const USERNAME = 'admin';
const PASSWORD = '12345';

// Home/Login Page
app.get('/', (req, res) => {
if (req.session.username)
{ res.send(`
<h2>Welcome, ${req.session.username}</h2>
<p>Last Login: ${req.cookies.lastLogin || 'First time!'}</p>
<a href="/logout">Logout</a>
`);
} else {
res.send(`
<h2>Login</h2>
<form method="POST" action="/login">
Username: <input type="text" name="username" required /><br><br>
Password: <input type="password" name="password" required /><br><br>
<button type="submit">Login</button>

Full Stack Development – II 16 kkvprasad@CSE


});
`);
} </form>
// Login Handler
app.post('/login', (req, res) => {
const { username, password } = req.body;

if (username === USERNAME && password === PASSWORD) {


// Store username in session
req.session.username = username;

// Store last login time in cookie (client-side)


res.cookie('lastLogin', new Date().toLocaleString(), { maxAge: 60000 });

res.redirect('/');
} else {
res.send('Invalid credentials. <a href="/">Try again</a>');
}
});

// Logout Handler
app.get('/logout', (req, res) => {
res.clearCookie('lastLogin'); // Clear cookie
req.session.destroy(() => { // Destroy session
res.redirect('/');
});
});

// Start Server
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});

Full Stack Development – II 17 kkvprasad@CSE


b) Write a program for user authentication.
const express = require('express');
const session = require('express-session');
const cookieParser = require('cookie-parser');

const app = express();


const PORT = 3000;

// Middleware
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
secret: 'mySecretKey', // Secret to sign the session ID cookie
resave: false, // Don't save session if not modified
saveUninitialized: false, // Don't create empty sessions
cookie: { maxAge: 60000 } // Session expires in 1 minute
}));

// Dummy user credentials


const USERNAME = 'admin';
const PASSWORD = '12345';

// Home / Login Page


app.get('/', (req, res) => {
if (req.session.username)
{ res.send(`
<h2>Welcome, ${req.session.username}</h2>
<p>Last Login: ${req.cookies.lastLogin || 'First time!'}</p>
<a href="/logout">Logout</a>
`);
} else {
res.send(`
<h2>User Login</h2>
<form method="POST" action="/login">
Username: <input type="text" name="username" required /><br><br>
Password: <input type="password" name="password" required /><br><br>
<button type="submit">Login</button>
</form>
`);
}
});

// Login Handler
app.post('/login', (req, res) => {
const { username, password } = req.body;

Full Stack Development – II 18 kkvprasad@CSE


// Check credentials
if (username === USERNAME && password === PASSWORD) {
// Store username in session
req.session.username = username;

// Store last login time in a cookie


res.cookie('lastLogin', new Date().toLocaleString(), { maxAge: 60000 });

res.redirect('/');
} else {
res.send('Invalid username or password. <a href="/">Try again</a>');
}
});

// Logout Handler
app.get('/logout', (req, res) => {
res.clearCookie('lastLogin'); // Remove cookie
req.session.destroy(() => { // Remove session
res.redirect('/');
});
});

// Start server
app.listen(PORT, () => {
console.log(`Authentication app running at http://localhost:${PORT}`);
});

Full Stack Development – II 19 kkvprasad@CSE


4. Express JS – Database, RESTful APIs

project-folder/
├── public/
│ └── index.html ← (Your HTML file goes here)
├── server.js ← (Your Express + MongoDB server)
├── .env ← (Your environment variables)
└── package.json

Step 1: Place your HTML file

Save your HTML content in project-folder/public/index.html.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>MongoDB CRUD UI</title>
<style>
body { font-family: Arial, sans-serif; max-width: 700px; margin: 2em auto; }
input, button { padding: 0.5em; margin: 0.2em 0; width: 100%; }
.user-item { border-bottom: 1px solid #ccc; padding: 0.5em 0; }
</style>
</head>
<body>
<h1>Users CRUD Interface</h1>

<h2>Create User</h2>
<form id="createUserForm">
<input type="text" id="name" placeholder="Name" required />
<input type="email" id="email" placeholder="Email" required />
<input type="number" id="age" placeholder="Age" min="0" />
<button type="submit">Create User</button>
</form>

<h2>All Users</h2>
<button id="refreshBtn">Refresh List</button>
<div id="usersList"></div>

<script>
const apiBase = '/users';

// Fetch and show all users


async function fetchUsers() {
const res = await fetch(apiBase);
const users = await res.json();

const list = document.getElementById('usersList');


list.innerHTML = '';

users.forEach(user => {
const div = document.createElement('div');

Full Stack Development – II 20 kkvprasad@CSE


div.className = 'user-item';
div.innerHTML = `
<strong>${user.name}</strong> (${user.email}) - Age: ${user.age || 'N/A'}
<br/>
<button onclick="deleteUser('${user._id}')">Delete</button>
<button onclick="showUpdateForm('${user._id}', '${user.name}', '$
{user.email}', ${user.age || 0})">Update</button>
<div id="updateForm-${user._id}" style="display:none; margin-top:10px;">
<input type="text" id="updateName-${user._id}" value="${user.name}" />
<input type="email" id="updateEmail-${user._id}" value="${user.email}" />
<input type="number" id="updateAge-${user._id}" value="${user.age || 0}"
min="0" />
<button onclick="updateUser('${user._id}')">Save</button>
<button onclick="hideUpdateForm('${user._id}')">Cancel</button>
</div>
`;
list.appendChild(div);
});
}

// Create user
document.getElementById('createUserForm').addEventListener('submit', async e =>
{
e.preventDefault();
const name = document.getElementById('name').value.trim();
const email = document.getElementById('email').value.trim();
const age = parseInt(document.getElementById('age').value);

const res = await fetch(apiBase, {


method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ name, email, age: isNaN(age) ? undefined : age })
});

if (res.ok) {
alert('User created!');
e.target.reset();
fetchUsers();
} else {
const error = await res.json();
alert('Error: ' + error.error);
}
});

// Delete user
async function deleteUser(id) {
if (!confirm('Delete this user?')) return;
const res = await fetch(`${apiBase}/${id}`, { method: 'DELETE' });
if (res.ok) {
alert('User deleted');
fetchUsers();
} else {
alert('Delete failed');

Full Stack Development – II 21 kkvprasad@CSE


}
}

// Show update form


function showUpdateForm(id, name, email, age) {
document.getElementById(`updateForm-${id}`).style.display = 'block';
}
function hideUpdateForm(id) {
document.getElementById(`updateForm-${id}`).style.display = 'none';
}

// Update user
async function updateUser(id) {
const name = document.getElementById(`updateName-${id}`).value.trim();
const email = document.getElementById(`updateEmail-${id}`).value.trim();
const age = parseInt(document.getElementById(`updateAge-${id}`).value);

const res = await fetch(`${apiBase}/${id}`, {


method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ name, email, age: isNaN(age) ? undefined : age })
});

if (res.ok) {
alert('User updated!');
hideUpdateForm(id);
fetchUsers();
} else {
const error = await res.json();
alert('Error: ' + error.error);
}
}

// Initial load
fetchUsers();

document.getElementById('refreshBtn').addEventListener('click', fetchUsers);
</script>
</body>
</html>

Full Stack Development – II 22 kkvprasad@CSE


The following is the Server.js

require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const path = require('path');

const app = express();

app.use(express.json());

// Serve static files (your HTML + frontend JS)


app.use(express.static(path.join(__dirname, 'public')));

// MongoDB connection URI from .env file


const mongoURI = process.env.MONGODB_URI;

if (!mongoURI) {
console.error('❌ MONGODB_URI not defined in .env');
process.exit(1);
}

mongoose.connect(mongoURI)
.then(() => console.log('✅ MongoDB connected'))
.catch(err => {
console.error('❌ MongoDB connection error:', err.message);
process.exit(1);
});

// Mongoose schema and model


const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, min: 0 },
});

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

// API routes for CRUD

app.get('/users', async (_req, res) => {


try {
const users = await User.find();

Full Stack Development – II 23 kkvprasad@CSE


res.json(users);
} catch (err) {
res.status(500).json({ error: err.message });
}
});

app.post('/users', async (req, res) => {


try {
const user = await User.create(req.body);
res.status(201).json(user);
} catch (err) {
res.status(400).json({ error: err.message });
}
});

app.get('/users/:id', async (req, res) => {


try {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).json({ error: 'User not found' });
res.json(user);
} catch (err) {
res.status(400).json({ error: err.message });
}
});

app.put('/users/:id', async (req, res) => {


try {
const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true,
runValidators: true });
if (!user) return res.status(404).json({ error: 'User not found' });
res.json(user);
} catch (err) {
res.status(400).json({ error: err.message });
}
});

app.delete('/users/:id', async (req, res) => {


try {
const user = await User.findByIdAndDelete(req.params.id);
if (!user) return res.status(404).json({ error: 'User not found' });
res.json({ message: 'User deleted' });
} catch (err) {
res.status(400).json({ error: err.message });
}
});

Full Stack Development – II 24 kkvprasad@CSE


// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`🚀 Server running on http://localhost:${PORT}`);
});

The following is the .env file

MONGODB_URI=mongodb://127.0.0.1:27017/myd

Full Stack Development – II 25 kkvprasad@CSE


5.ReactJS – Render HTML, JSX, Components – function & Class
a)Write a program to render HTML to a web page.

Step-1. Install Node.js and npm


• sudo apt update
• sudo apt install nodejs npm

Step-2. Create a React Project


• npx create-react-app my-react-app
• cd my-react-app

Step-3. Replace src/index.js

import React from 'react';


import { createRoot } from 'react-dom/client';
createRoot(document.getElementById('root')).render
(<p>Hello, this is rendered HTML using React!</p>);

Step-4. Start the Development Server


• npm start

Step-5. Open in Browser


• Navigate to http://localhost:3000

Full Stack Development – II 26 kkvprasad@CSE


b)Write a program for writing markup with JSX.

Step-1.Install Node.js s npm (if not already installed)

▪ sudo apt update


▪ sudo apt install nodejs npm

Step-2.Create a React App

● npx create-react-app jsx-demo


● cd jsx-demo

Step-3. Replace src/index.js

//src/index.js
import React, { useState } from 'react'; function App() {
const [username, setUsername] = useState('');
const [submittedName, setSubmittedName] = useState('');
const handleChange = (event) => {
setUsername(event.target.value);
};
const handleSubmit = (event) =>
{ event.preventDefault();
setSubmittedName(username); setUsername('');
};
return (
<div>
{!submittedName ? (
<form onSubmit={handleSubmit}>
<input type="text"
placeholder="Enter your name"
value={username}
onChange={handleChang
e} required
/>
<button type="submit">Submit</button>
</form>
):(
<>
<h1>Welcome, {submittedName}!</h1>
<p>This is written using JSX syntax.</p>
</>
)}
</div>
);
}
export default App;

Full Stack Development – II 27 kkvprasad@CSE


Step-4. Start the React Server
● npm start
Step-5
● Open a browser to http://localhost:3000

Full Stack Development – II 28 kkvprasad@CSE


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

Step - 1.Install Node.js npm if needed:


● sudo apt update
● sudo apt install nodejs npm

Step - 2.Create Project:


● npx create-react-app nesting-demo
● cd nesting-demo

Step - 3.Edit/Add Files in src:


● Use nano or any editor to add Child.js, Sibling.js, Parent.js, and edit App.js

Child.js: (Function Component)

jsx
import React from 'react'; function Child() {
return <p>This is a Function Child Component!</p>;
}
export default Child;

Sibling.js: (Class Component)

jsx
import React, { Component } from 'react'; class Sibling extends Component {
render() {
return <p>This is a Class Sibling Component!</p>;
}
}
export default Sibling;

Parent.js: (Function Component - nests Child and Sibling)

jsx
import React from 'react'; import Child from './Child'; import Sibling from
'./Sibling'; function Parent() {
return (
<div>
<h2>This is the Parent Function Component</h2>
<Child />
<Sibling />
</div>
);
}
export default Parent;

Full Stack Development – II 29 kkvprasad@CSE


App.js: (Use Parent in App)

jsx
import React from 'react'; import Parent from './Parent'; function App() {
return (
<div>
<h1>React Component Nesting Example</h1>
<Parent />
</div>
);
}
export default App;

Step – 4.Start the App:


● npm start

Step - 5
● Visit http://localhost:3000

Full Stack Development – II 30 kkvprasad@CSE


6.ReactJS – Props and States, Styles, Respond to Events
a)Write a program to work with props and states.

Step-1
● sudo apt update
● sudo apt install nodejs npm

Step-2.Create React app:


● npx create-react-app my-props-states-app
● cd my-props-states-app

Step-3.Replace the contents of src/App.js


// src/App.js

import React, { useState } from "react"; function ChildComponent(props) {


return <h2>Message from parent: {props.message}</h2>;
}
function App() {
const [count, setCount] = useState(0); return (
<div>
<ChildComponent message="Hello from App component!" />
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default App;

Step-4.Start the React development server:


● npm start

Step-5
● Open browser at http://localhost:3000

Full Stack Development – II 31 kkvprasad@CSE


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

Step-1.Create React app (if not already):

● npx create-react-app my-styled-app


● cd my-styled-app

Step-2.Replace src/App.js and create src/App.css .


src/App.js
import React

from "react";

import

"./App.css";

function App() {
const data = ["React", "CSS", "Sass", "JavaScript"]; return (

<div className="container">
<h1 className="title">Styling in React</h1>
<ul>
{data.map((item) => (
<li key={item} className="list-item">{item}</li>
))}
</ul>
</div>
);
}
export default App;

src/App.css
.container {
background-color: #282c34; padding: 20px;

color: #61dafb;
font-family: Arial, sans-serif;
}
.title {
font-size: 2rem; margin-bottom: 10px;

}
.list-item {
font-size: 1.2rem; margin: 5px 0;

Step-3.For Sass support, install:


npm install sass

Full Stack Development – II 32 kkvprasad@CSE


Step.4.
Rename App.css to App.scss and update import in App.js to import "./App.scss";

Step-5.Run the React app:


● npm start
Step-6
Visit http://localhost:3000 to see styled data displayed.

Full Stack Development – II 33 kkvprasad@CSE


b) Write a program for responding to events.

Step-1.Create React app:


● npx create-react-app react-events-app
● cd react-events-app

Step-2.Replace src/App.js with below code.


import React, { useState } from "react"; function App() {
const [message, setMessage] = useState("Click the button!");
const handleClick = () => { setMessage("Button clicked!");
};
return (
<div>
<p>{message}</p>
<button onClick={handleClick}>Click Me</button>
</div>
);
}export default App;

Step-3.Start React development server:


npm start

Step-4
Open browser at http://localhost:3000

Full Stack Development – II 34 kkvprasad@CSE


7.ReactJS – Conditional Rendering, Rendering Lists, React Forms
a)Write a program for conditional rendering.
1. Install Node.js and npm
sudo apt update
sudo apt install nodejs npm
2. Create React app
npx create-react-app myapp
cd myapp
3. Replace the content of src/App.js .
// src/App.js
import React, { useState } from "react";

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

return (
<div>
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? "Log Out" : "Log In"}
</button>
<h1>{isLoggedIn ? "Welcome Back!" : "Please Sign In"}</h1>
</div>
);
}

export default App;

4. Run the React app:


npm start
5. App will open automatically in browser at http://localhost:3000

Full Stack Development – II 35 kkvprasad@CSE


b)Write a program for rendering lists.

1.Create React app


npx create-react-app myapp
cd myapp

2.Replace the content of src/App.js


// src/App.js
import React from "react";

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

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

export default App;

3.Run the React app:


npm start
4.App will open automatically in browser at http://localhost:3000

Full Stack Development – II 36 kkvprasad@CSE


C)Write a program for working with different form fields using react forms.
1.Create React app
npx create-react-app myapp
cd myapp

2.Replace the content of src/App.js

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

function App() {
const [formData, setFormData] = useState({
name: "",
email: "",
subscribe: false,
});

function handleChange(event) {
const { name, value, type, checked } = event.target;
setFormData((prevData) => ({
...prevData,
[name]: type === "checkbox" ? checked : value,
}));
}

function handleSubmit(event) {
event.preventDefault();
alert(`Form Data:\n${JSON.stringify(formData, null, 2)}`);
}

return (
<form onSubmit={handleSubmit}>
<div>
<label>
Name:
<input
name="name"
value={formData.name}
onChange={handleChange}
type="text"
/>
</label>
</div>
<div>
<label>
Email:
<input
name="email"
value={formData.email}
onChange={handleChange}
type="email"
/>

Full Stack Development – II 37 kkvprasad@CSE


</label>
</div>
<div>
<label>
Subscribe to newsletter:
<input
name="subscribe"
checked={formData.subscribe}
onChange={handleChange}
type="checkbox"
/>
</label>
</div>
<button type="submit">Submit</button>
</form>
);
}

export default App;

3.Run the React app:


npm start
4.App will open automatically in browser at http://localhost:3000

Full Stack Development – II 38 kkvprasad@CSE


8. ReactJS – React Router, Updating the Screen
a) Write a program for routing to different pages using react router.

1. Create a React Project


npx create-react-app my-router-app
cd my-router-app

2.Replace the code src/App.js


// Install react-router-dom first:
// npm install react-router-dom

import React from 'react';


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

// Home page component showing welcome info


function Home() {
return (
<div>
<h1>Home Page</h1>
<p>Welcome to the React Router demo!</p>
<nav>
<Link to="/page/React">React</Link> |{" "}
<Link to="/page/JavaScript">JavaScript</Link> |{" "}
<Link to="/page/Node">Node.js</Link>
</nav>
</div>
);
}

// Page component that receives 'topic' param from URL and displays info
function Page() {
const { topic } = useParams();
return (
<div>
<h1>Page for {topic}</h1>
<p>Here is some information about <strong>{topic}</strong>.</p>
<Link to="/">Back to Home</Link>
</div>
);
}

// Main App component with routes


function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/page/:topic" element={<Page />} />
</Routes>
</BrowserRouter>
);
}

Full Stack Development – II 39 kkvprasad@CSE


export default App;
3. Install React Router
npm install react-router-dom
4.Run the Application
npm start

Full Stack Development – II 40 kkvprasad@CSE


b)Write a program for updating the screen.

1. Create a React Project


npx create-react-app my-router-app
cd my-router-app

2.Replace the code src/App.js

import React, { useState } from 'react';

function Counter() {
// Declare a state variable 'count', initial value 0
const [count, setCount] = useState(0);

// Function to handle increment


const handleIncrement = () => setCount(count + 1);

return (
<div>
<h2>Counter Value: {count}</h2>
<button onClick={handleIncrement}>Increment</button>
</div>
);
}

export default Counter;

3. Install React Router


npm install react-router-dom
4.Run the Application
npm start

Full Stack Development – II 41 kkvprasad@CSE


9) 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.

10) 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()

11) 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().

12) 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.

Full Stack Development – II 42 kkvprasad@CSE

You might also like