Full Stack Development Lab Manual
Full Stack Development Lab Manual
Prepared By
Mr. G Nagi Reddy Dr. P Shyam Sunder Mr. Y.Pavan Narasimha Rao
Asst. Professor, C SE Asst. Professor, CSE Asst. Professor, CSE
L T P C
0 0 2 1
VI Semester Syllabus
CS753PE: Full Stack Development Lab
(Professional Elective-III)
(Common to CSE & IT)
Pre-Requisites:
Course Objectives:
Introduce fast, efficient, interactive and scalable web applications using run time
environment provided by the full stack components.
Course Outcomes:
Design flexible and responsive Web applications using Node JS, React, Express
and Angular.
Perform CRUD operations with MongoDB on huge amount of data.
Develop real time applications using react components.
Use various full stack modules to handle http requests and responses.
List of Experiments
TEXT BOOKS:
1. Brad Dayley, Brendan Dayley, Caleb Dayley., Node.js, MongoDB and
REFERENCE BOOKS:
1. Vasan Subramanian, Pro MERN Stack, Full Stack Web App
Development with Mongo, Express, React, and Node, 2nd Edition,
Apress,2019.
2. Chris Northwood, The Full Stack Developer: Your Essential Guide to
the Everyday Skills Expected of a Modern Full Stack Web Developer’,
1st edition, Apress, 2018.
3. Brad Green& Seshadri. Angular JS. 1st Edition. O'Reilly Media, 2013.
4. Kirupa Chinnathambi, Learning React: A Hands-On Guide to Building
Web Applications Using React and Redux, 2nd edition, Addison-Wesley
Professional, 2018.
EXP1.
AIM: Create an application to setup node JS environment and display “Hello World.”
hello1.js
http = require('http');
listener = function (req, res) {
server = http.createServer(listener);
server.listen(8080);
output:
>node hello1.js
hello2.js
//Create an application to setup node JS environment and display “Hello World.” on
webpage
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>hello world....</h1>');
res.end();
}).listen(8080);
output:
node hello1.js
EXP2.
function factorial(num) {
// Base case
if (num === 0) {
return 1;
// Recursive case
console.log(factorial(5));
Output:
120
EXP3.
AIM: Write a java script to check the given number is prime or not
OUTPUT:
11 is a prime number
Exp4.
function reverseString(str) {
// empty string
newString += str[i];
return newString;
console.log(result)
Output:
tigm
EXP5.
Aim: Write a Node JS program to perform read, write and other operations on a file.
readFile.js
//READ FILE
var fs = require('fs');
res.write(data);
return res.end();
});
}).listen(8080);
File1.txt
Output:
writeFile.js
var fs = require('fs');
console.log('Replaced!');
});
Output:
Replaced!
appendFile.js
var fs = require('fs');
console.log('Saved!');
});
Output:
Saved!
Deletefile.js
//DELETE FILE
var fs = require('fs');
console.log('File deleted!');
});
Output:
'File deleted!
EXP6.
Calc.js
//calc functions
exports.add = function (x, y) {
return x + y;
};
exports.sub = function (x, y) {
return x - y;
};
exports.mult = function (x, y) {
return x * y;
};
exports.div = function (x, y) {
return x / y;
};
Module.js
output:
Subtraction of 50 and 10 is 40
Division of 50 and 10 is 5
Exp7:
Aim: Write a Node JS program to demonstrate accessing static files using http
webserver and client.
Httpstaticfileserver.js
In termimal1:
modules>node httpstaticfileserver.js
Output:
Httpstaticfileclient.js
// Basic web client retrieving static files
var http = require('http');
var options = {
hostname: 'localhost',
port: '8080',
path: '/hello.html'
};
function handleResponse(response) {
var serverData = '';
response.on('data', function (chunk) {
serverData += chunk;
});
response.on('end', function () {
console.log(serverData);
});
}
http.request(options, function(response){
handleResponse(response);
}).end()
html/hello.html
<html>
<head>
<title>Static Example</title>
</head>
<body>
</body>
</html>
Output:
In terminal2:
modules>node httpstaticfileclient.js
<html>
<head>
<title>Static Example</title>
</head>
<body>
<h1>Hello from a Static File</h1>
</body>
</html>
Exp8:
Httpserverget.js
var messages = [
'Hello World',
'Take Luck'];
res.setHeader("Content-Type", "text/html");
res.writeHead(200);
res.write('<body>');
res.end('\n</body></html>');
}).listen(8080)
Output: In terminal1:
Modules>node httpserverget.js
Httpsclientget.js
Output: In Terminal2:
Exp9:
AIM: write a Node JS program to read form data from query string and generate
response using NodeJS
Modules/url5.js
//write a Node JS program to read form data from query string and generate response using
NodeJS
var q= url.parse(req.url,true).query;
console.log(q);
res.end(txt);
}).listen(8080);
OUTPUT:
Exp10:
AIM: write a Node JS program to demonstrate events and call back functions.
//events.js
// Importing events
// Registering to myEvent
console.log(msg);
});
// Triggering myEvent
// Triggering myEvent
console.log("program ended...")
output:
node events1.js
First event
Second event
program ended...
//callback.js
})
output:
file.text
call back functions
Exp11: Implement a program with basic commands on databases and collections using
MongoDB.
1. D:\MONGODB\DB>mongod --version
db version v8.0.0
Build Info: {
"version": "8.0.0",
"gitVersion": "d7cd03b239ac39a3c7d63f7145e91aca36f93db6",
"modules": [],
"allocator": "tcmalloc-gperf",
"environment": {
"distmod": "windows",
"distarch": "x86_64",
"target_arch": "x86_64"
}
}
2.D:\MONGODB\DB>mongosh
Current Mongosh Log ID: 66f252c9808c7f3e6bc73bf7
Connecting to: mongodb://127.0.0.1:27017/?
directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.3.1
Using MongoDB: 8.0.0
Using Mongosh: 2.3.1
------
The server generated these startup warnings when booting
2024-09-23T14:31:32.621+05:30: Access control is not enabled for the database. Read and
write access to data and configuration is unrestricted
------
test>
3.test> show dbs
admin 40.00 KiB
config 72.00 KiB
local 72.00 KiB
5.MYDB1> db.createCollection("students")
{ ok: 1 }
9.MYDB1> db.students.find().pretty()
[
{
_id: ObjectId('66f255ec808c7f3e6bc73bf8'),
rollno: 501,
name: 'cse1'
}
]
11.MYDB1> db.students.find().pretty()
[
{
_id: ObjectId('66f255ec808c7f3e6bc73bf8'),
rollno: 501,
name: 'cse1'
},
{
_id: ObjectId('66f2577b808c7f3e6bc73bf9'),
rollno: 502,
name: 'cse2'
}
]
12.MYDB1> db.students.updateOne({rollno:502},{$set:{name:"cse3"}})
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
13.MYDB1> db.students.find().pretty()
[
{
_id: ObjectId('66f255ec808c7f3e6bc73bf8'),
rollno: 501,
name: 'cse1'
},
{
_id: ObjectId('66f2577b808c7f3e6bc73bf9'),
rollno: 502,
name: 'cse3'
}
]
14. MYDB1> db.students.deleteOne({rollno:111})
{ acknowledged: true, deletedCount: 1 }
MYDB1> db.students.find().pretty()
[
{
_id: ObjectId('670ca9a53fede232f9c73bf9'),
rollno: 222,
name: 'cccccc'
}
]
15.MYDB1> db.students.drop()
True
16.MYDB1> show collections
17.MYDB1> db.dropDatabase()
{ ok: 1, dropped: 'MYDB1' }
18MYDB1> show dbs
admin 40.00 KiB
config 108.00 KiB
local 72.00 KiB
MYDB1> load('d:\db1.js')
True
MYDB1> db.students.find().pretty()
[
{
_id: ObjectId('670ca9a53fede232f9c73bf9'),
rollno: 222,
name: 'cccccc'
},
{
_id: ObjectId('670ded507a61ecab52c73bf8'),
name: 'Karthik',
rollno: 101,
marks: 98
},
{
_id: ObjectId('670ded507a61ecab52c73bf9'),
name: 'Ravi',
rollno: 102,
marks: 99
},
{
_id: ObjectId('670ded507a61ecab52c73bfa'),
name: 'Shiva',
rollno: 103,
marks: 100
},
{
_id: ObjectId('670ded507a61ecab52c73bfb'),
name: 'Pavan',
rollno: 104,
marks: 80
}
]
MYDB1> db.students.findOne()
{
_id: ObjectId('670ca9a53fede232f9c73bf9'),
rollno: 222,
name: 'cccccc'
}
MYDB1> db.students.findOne({'name':'cccccc'})
{
_id: ObjectId('670ca9a53fede232f9c73bf9'),
rollno: 222,
name: 'cccccc'
}
Exp12: Implement CRUD operations on the given dataset using MongoDB.
found 0 vulnerabilities
Connect.js
Output:
MONGODB> node connect.js
Connected Successfully!
Exiting..
Insertdb.js
// to insert one document
const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Insert to database
client.db('MYDB').collection('students').insertOne({
name: 'cse1',
email: '[email protected]'
})
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))
Output:
MONGODB> node insertdb.js
acknowledged: true,
insertedId: new ObjectId('674aeea8b3bc707da2d4559f')
}
Finddb.js
//to find one document
const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Insert to database
client.db('MYDB').collection('students')
.findOne({name:'cse1'})
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))
Output:
MONGODB>node finddb.js
{
_id: new ObjectId('674aeea8b3bc707da2d4559f'),
name: 'cse1',
email: '[email protected]'
}
Updatedb.js
//to update one document
const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Insert to database
client.db('MYDB').collection('students')
.updateOne({ name: 'cse1' },
{
$set:
{ email: '[email protected]' }
})
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))
Output:
{
acknowledged: true,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0,
matchedCount: 1
}
Deletedb.js
// Insert to database
client.db('MYDB').collection('students')
.deleteOne({ name: 'cse1' })
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))
Output:
Exp13: Perform Count, Limit, Sort, and Skip operations on the given collections using
MongoDB.
MYDB2> db.createCollection("employees");
{ ok: 1 }
MYDB2> db.employees.find().pretty()
[
{
_id: ObjectId('6713c7d9b34f42f350c73bfc'),
id: 111,
name: 'aaaa',
salary: 10000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfd'),
id: 222,
name: 'bbbb',
salary: 30000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfe'),
id: 333,
name: 'cccc',
salary: 20000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bff'),
id: 444,
name: 'dddd',
salary: 10000
}
]
MYDB2> db.employees.find().count()
4
MYDB2> db.employees.find({salary:10000}).count()
2
MYDB2> db.employees.find().pretty().limit(1)
[
{
_id: ObjectId('6713c7d9b34f42f350c73bfc'),
id: 111,
name: 'aaaa',
salary: 10000
}
]
MYDB2> db.employees.find().pretty().limit(2)
[
{
_id: ObjectId('6713c7d9b34f42f350c73bfc'),
id: 111,
name: 'aaaa',
salary: 10000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfd'),
id: 222,
name: 'bbbb',
salary: 30000
}
]
MYDB2> db.employees.find().pretty().skip(2)
[
{
_id: ObjectId('6713c7d9b34f42f350c73bfe'),
id: 333,
name: 'cccc',
salary: 20000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bff'),
id: 444,
name: 'dddd',
salary: 10000
}
]
MYDB2> db.employees.find().pretty().skip(3)
[
{
_id: ObjectId('6713c7d9b34f42f350c73bff'),
id: 444,
name: 'dddd',
salary: 10000
}
]
MYDB2> db.employees.find().pretty().sort({id:1})
[
{
_id: ObjectId('6713c7d9b34f42f350c73bfc'),
id: 111,
name: 'aaaa',
salary: 10000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfd'),
id: 222,
name: 'bbbb',
salary: 30000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfe'),
id: 333,
name: 'cccc',
salary: 20000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bff'),
id: 444,
name: 'dddd',
salary: 10000
}
]
MYDB2> db.employees.find().pretty().sort({id:-1})
[
{
_id: ObjectId('6713c7d9b34f42f350c73bff'),
id: 444,
name: 'dddd',
salary: 10000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfe'),
id: 333,
name: 'cccc',
salary: 20000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfd'),
id: 222,
name: 'bbbb',
salary: 30000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfc'),
id: 111,
name: 'aaaa',
salary: 10000
}
]
Exp.14:
Index.js
// to print the msg ‘Hello world!’
var express = require('express');
var app = express();
const PORT=3000
app.get('/', function(req, res){
res.send("Hello world!");
});
app.listen(PORT,()=>
{
console.log('server is running at port:'+PORT)
});
Output:
>node index.js
Localhost:3000
Exp.15:
Output:
Localhost:3000
Localhost:3000/login
Localhost:3000/save
Exp.16:
Index.js
//to demonstrate Applying Route Parameters in Express JS
var express = require('express');
var url = require('url');
var app = express();
app.listen(4000);
app.get('/', function (req, res) {
res.send("Get Index");
});
app.get('/find', function(req, res){
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var response = 'Finding Book: Author: ' + query.author +
' Title: ' + query.title;
console.log('\nQuery URL: ' + req.originalUrl);
console.log(response);
res.send(response);
});
app.get(/^\/book\/(\w+)\:(\w+)?$/, function(req, res){
var response = 'Get Book: Chapter: ' + req.params[0] +
' Page: ' + req.params[1];
console.log('\nRegex URL: ' + req.originalUrl);
console.log(response);
res.send(response);
});
app.get('/user/:userid', function (req, res) {
res.send("Get User: " + req.param("userid"));
});
Output:
http://localhost:4000
http://localhost/find?author=shyam&title=FSD
http://localhost/book/05:65
http://localhost/user/0565
Exp.17:
AIM: Commands For Angular Installation, Create and Running Angular Apps.
ANGULAR JS
added 1 package in 1s
D:\ANGULAR>tsc -v
Version 5.6.3
D:\ANGULAR>ng v
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
Angular:
...
Package Version
------------------------------------------------------
@angular-devkit/architect 0.1802.10 (cli-only)
@angular-devkit/core 18.2.10 (cli-only)
@angular-devkit/schematics 18.2.10 (cli-only)
@schematics/angular 18.2.10 (cli-only)
Would you like to share pseudonymous usage data about this project with the Angular Team
at Google under Google's Privacy Policy at https://policies.google.com/privacy. For more
details and how to change this setÝng, see https://angular.dev/cli/analytics.
yes
Thank you for sharing pseudonymous usage data. Should you change your mind, the following
command will disable this feature entirely:
Would you like to share pseudonymous usage data about this project with the Angular
Team
at Google under Google's Privacy Policy at https://policies.google.com/privacy. For
more
details and how to change this setÝng, see https://angular.dev/cli/analytics.
Would you like to share pseudonymous usage data about this project with the Angular
Team
at Google under Google's Privacy Policy at https://policies.google.com/privacy. For
more
details and how to change this setÝng, see https://angular.dev/cli/analytics.
yes
Thank you for sharing pseudonymous usage data. Should you change your mind, the following
command will disable this feature entirely:
ng analytics disable
Server bundles
Initial chunk files | Names | Raw size
polyfills.server.mjs | polyfills.server | 572.91 kB |
Server bundles
Initial chunk files | Names | Raw size
polyfills.server.mjs | polyfills.server | 572.91 kB |
Initial chunk files | Names | Raw size
polyfills.server.mjs | polyfills.server | 572.91 kB |
polyfills.server.mjs | polyfills.server | 572.91 kB |
main.server.mjs | main.server | 23.23 kB |
main.server.mjs | main.server | 23.23 kB |
render-utils.server.mjs | render-utils.server | 472 bytes |
render-utils.server.mjs | render-utils.server | 472 bytes |
Localhost:4200
First/src/app/app.component.ts
Output:
Exp.18
Second/src/app/app.component.ts
Output:
Exp.19
Third/src/app/app.component.ts
//to demonstrate Using Inline CSS and HTML in Angular Applications
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
template: `
<span>welcome to cse1 students</span>
`,
styles:[`
span {
font-weight: bold;
font-size: 25px;
border: 1px ridge blue;
padding: 5px;
}
`]
})
export class AppComponent {
title = 'third';
}
Output:
Exp.20
Fourth/src/app/app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'fourth';
}
Fourth/src/app/app.component.html
<h1>Congratulations</h1>
<p>
You've successfully loaded an external html file.
<span>
If I'm red then You managed to get the styles in there as well
</span>
</p>
Fourth/src/app/app.component.css
span{
color: red;
border: 2px solid red;
}
Output:
Exp.21
Expressions/src/app/app.component.ts
@Component({
selector: 'app-root',
standalone:true,
template: `
<h1>Expressions</h1>
Number:<br>
{{5}}<hr>
String:<br>
{{'My String'}}<hr>
Adding two strings together:<br>
{{'String1' + ' ' + 'String2'}}<hr>
Adding two numbers together:<br>
{{5+5}}<hr>
Adding strings and numbers together:<br>
{{5 + '+' + 5 + '='}}{{5+5}}<hr>
Comparing two numbers with each other:<br>
{{5===5}}<hr>
Reading title value from the class:<br>
{{title}}
`,
})
export class AppComponent {
title='basic expressions'
}
output:
Exp.22
AIM: To demonstrate creating different components like header and footer in Angular.
Note: use the following command to create the application and components
>ng new component1
>component1> ng g c header
>component1> ng g c footer
Component1/src/app/app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet,HeaderComponent,FooterComponent],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'component1';
}
Component1/src/app/app.component.html
<hr>
<h1> CREATING TWO COMPONENTS </h1>
<hr>
<app-header> </app-header>
<hr>
<app-footer> </app-footer>
<hr>
Component1/src/app/header/header.component.html
Component1/src/app/header/header.component.css
h1
{
color: red
}
Component1/src/app/footer/footer.component.html
<h1>Welcome to the FOOTER COMPONENT</h1>
Component1/src/app/footer/footer.component.css
h1{
color: violet
}
Output:
Exp.23
AIM: To demonstrate data binding (string interpolation, property binding & class
binding) in Angular.
Databinding/src/app/app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css’
})
export class AppComponent {
title = 'databinding';
isdisabled:boolean=true;
isactive:boolean=true;
Databinding/src/app/app.component.html
Databinding/src/app/app.component.css
.active{
color:blue
}
.inactive{
color:green
}
Output:
Exp.24
Events/src/app/app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'events';
counter:number=0;
name:any="null"
increment()
{
this.counter+=1;
}
decrement()
{
this.counter-=1;
}
changeName(e:any)
{
this.name=e.target.value
}
}
Events/src/app/app.component.html
<h1> count:{{counter}}</h1>
<button (click)="increment()"> increment</button>
<button (click)="decrement()"> decrement</button>
<br>
<br>
Name:<input type="text"(input)="changeName($event)">
<h2> Your name:{{name}}</h2>
Output:
Exp.25
Src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
src/app/app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrl: './app.component.css’
})
export class AppComponent {
title = 'twowaybinding';
city="hyderabad"
src/app/app.component.html
<div>
<h2>Two-Way Data Binding Example</h2>
<p>You entered: {{ text }}</p> <!-- Display the text entered by the user -->
</div>
Output:
Exp.26
Src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
src/app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
isVisible = true; // Boolean variable to control visibility
toggleVisibility() {
this.isVisible = !this.isVisible; // Toggle the visibility of the element
changeColor(newColor: string) {
}
}
src/app/app.component.html
</li>
</ul>
<button (click)="changeColor('red')">Red</button>
<button (click)="changeColor('blue')">Blue</button>
<button (click)="changeColor('green')">Green</button>
<button (click)="changeColor('yellow')">Yellow</button>
Output:
Exp.27
function App() {
return (
<div className="App">
<h1>Hello World</h1>
</div>
);
}
├── node_modules/
├── public/
│ └── index.html
├── src/
│ ├── App.css
│ ├── App.js
│ ├── index.js
│ └── logo.svg
├── package.json
├── package-lock.json
└── README.md
The src/App.js file contains the main code for your app.
index.js is where React is hooked into the HTML DOM.
public/index.html is the HTML template that React will render the app into.
DEFAULT OUTPUT
EXP28.
NOTE:
1)Create two files in the folder ‘src’ with CBC.js and FBC.js
2) use rcc and rfc to get the class and functional based syntax in the files.
Src/CBC.js
import React, { Component } from 'react'
Src/FBC.js
import React from 'react'
Src/App.js
import CBC from "./CBC";
import FBC from "./FBC";
function App() {
return (
<div>
<h1>hello world- main component</h1>
<CBC></CBC>
<FBC></FBC>
</div>
);
}
EXP29.
function Counter() {
// Declare a state variable 'count' and a function to update it 'setCount'
const [count, setCount] = useState(0);
};
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h1>Counter: {count}</h1>
<button onClick={decrement}>Decrement</button>
<button onClick={increment}>Increment</button>
</div>
);
}
output:
</div>
);
}
export default App;
React-props/src/Greeting.js
function Greeting(props) {
return(
<h2>Hello, Your name:{props.name} and id:{props.id} </h2>
);
output:
EXP30.
AIM: Develop a form with a field an email address and validate it using React.
Form-validate/Src/App.js
//email validation
import React, { useState } from 'react';
export default function ValidatedForm() {
const [email, setEmail] = useState('');
const [error, setError] = useState('');
// Simple validation
if (!/\S+@\S+\.\S+/.test(value)) {
setError('Invalid email address');
} else {
setError('');
}
};
return (
<form onSubmit={handleSubmit}>
<label>
Email:
<input type="email" value={email} onChange={handleChange} />
</label>
{error && <p style={{ color: 'red' }}>{error}</p>}
<button type="submit" disabled={!!error}>
Submit
</button>
</form>
);
}
Output:
Ex.no: 31
Aim: Reading form data consisting of email and password in react
Form-reading/src/App.js
import React, { useState } from "react";
function App() {
const [formData, setFormData] = useState({
username: "",
password: "",
});
return (
<form onSubmit={handleSubmit}>
<label>
Username:
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
</label> <br/>
<label>
Password:
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
/>
</label> <br/>
<button onClick={()=>
console.log("email and password submitted...") }>
Submit
</button>
</form>
);
}
export default App;
output:
EXP32.
AIM: Develop a form with fields for a phone number and an email address, and
validate them using React.
Form-validation/src/App.js
function IndianPhoneAndEmailForm() {
const [formData, setFormData] = useState({
email: '',
phone: '',
});
// Submit data
console.log('Form Data Submitted:', formData);
alert('Form submitted successfully!');
};
return (
<div>
<h2>Indian Phone and Email Validation Form</h2>
<form onSubmit={handleSubmit}>
<div>
<label>Email:</label>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
{errors.email && <p style={{ color:
'red' }}>{errors.email}</p>}
</div>
<div>
<label>Phone:</label>
<input
type="text"
name="phone"
value={formData.phone}
onChange={handleChange}
/>
{errors.phone && <p style={{ color:
'red' }}>{errors.phone}</p>}
</div>
<button type="submit" disabled={!!errors.email || !!
errors.phone}>
Submit
</button>
</form>
</div>
);
}
export default IndianPhoneAndEmailForm;
OUTPUT:
Sample1
Sample2
Ex.no: 33
Aim: to demonstrate life cycle methods in react.
Src/App.js
import React from 'react';
output:
Ex.no: 34
Aim: to demonstrate routing in react.
Src/app.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
Src/Home.js
import React from 'react';
Src/About.js
Src/Contact.js
output :
Ex.no: 35
Src/App.js
import React, { useState } from "react";
import "./App.css";
function App() {
const [input, setInput] = useState("");
return (
<div className="App">
<h1>React Calculator</h1>
<div className="calculator">
<div className="display">{input || "0"}</div>
<div className="buttons">
{["7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "C", "+"].map((btn) => (
<button key={btn} onClick={() => handleButtonClick(btn)}>
{btn}
</button>
))}
<button className="equals" onClick={() => handleButtonClick("=")}>
=
</button>
</div>
</div>
</div>
);
}
Src/App.css
.App {
text-align: center;
font-family: Arial, sans-serif;
}
.calculator {
display: inline-block;
background: #f0f0f0;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}
.display {
width: 200px;
height: 40px;
margin-bottom: 10px;
background: #fff;
text-align: right;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 18px;
overflow-x: auto;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 50px);
gap: 10px;
}
button {
width: 50px;
height: 50px;
font-size: 18px;
background: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background 0.3s;
}
button:hover {
background: #0056b3;
}
.equals {
grid-column: span 4;
background: #28a745;
}
.equals:hover {
background: #1e7e34;
}
Output:
Ex.no: 36
function App() {
const [candidates, setCandidates] = useState([
{ name: "CSE1", votes: 0 },
{ name: "CSE2", votes: 0 },
{ name: "CSE3", votes: 0 },
]);
return (
<div className="App">
<h1>Voting Application</h1>
<div className="candidates">
{candidates.map((candidate, index) => (
<div key={index} className="candidate">
<span>{candidate.name}</span>
<span>{candidate.votes} votes</span>
<button onClick={() => handleVote(index)}>Vote</button>
</div>
))}
</div>
<button className="reset" onClick={resetVotes}>
Reset Votes
</button>
</div>
);
}
export default App;
Src/App.css
.App {
text-align: center;
font-family: Arial, sans-serif;
padding: 20px;
}
h1 {
margin-bottom: 20px;
font-size: 2em;
}
.candidates {
display: flex;
flex-direction: column;
gap: 10px;
align-items: center;
}
.candidate {
display: flex;
justify-content: space-between;
align-items: center;
width: 300px;
padding: 10px;
background: #f9f9f9;
border: 1px solid #ddd;
border-radius: 5px;
}
.candidate button {
padding: 5px 10px;
background: #007bff;
color: #fff;
border: none;
border-radius: 3px;
cursor: pointer;
transition: background 0.3s;
}
.candidate button:hover {
background: #0056b3;
}
.reset {
margin-top: 20px;
padding: 10px 20px;
background: #dc3545;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background 0.3s;
}
.reset:hover {
background: #c82333;
}
Output:
Ex.no: 37
Src/App.js
import React, { useState } from "react";
import "./App.css";
function App() {
const initialLeaveBalance = {
CasualLeave: 12,
MedicalLeave: 10,
EarnedLeave: 8,
};
return (
<div className="App">
<h1>Leave Management System</h1>
<div className="leave-balance">
<h2>Leave Balance</h2>
<ul>
{Object.entries(leaveBalance).map(([type, days]) => (
<li key={type}>
{type}: {days} days
</li>
))}
</ul>
</div>
<div className="apply-leave">
<h2>Apply Leave</h2>
<label>
Leave Type:
<select
value={selectedLeaveType}
onChange={(e) => setSelectedLeaveType(e.target.value)}
>
{Object.keys(leaveBalance).map((type) => (
<option key={type} value={type}>
{type}
</option>
))}
</select>
</label>
<label>
Number of Days:
<input
type="number"
min="1"
value={leaveDays}
onChange={(e) => setLeaveDays(parseInt(e.target.value))}
/>
</label>
<div className="leave-history">
<h2>Leave History</h2>
{leaveHistory.length > 0 ? (
<ul>
{leaveHistory.map((leave, index) => (
<li key={index}>
{leave.type}: {leave.days} day(s) on {leave.date}
</li>
))}
</ul>
):(
<p>No leave history available.</p>
)}
</div>
Src/App.css
.App {
text-align: center;
font-family: Arial, sans-serif;
padding: 20px;
}
h1 {
font-size: 2em;
margin-bottom: 20px;
}
.leave-balance,
.apply-leave,
.leave-history {
margin: 20px 0;
padding: 20px;
border: 1px solid #ddd;
border-radius: 5px;
background-color: #f9f9f9;
}
h2 {
margin-bottom: 10px;
}
ul {
list-style: none;
padding: 0;
}
li {
margin: 5px 0;
}
label {
display: block;
margin: 10px 0;
}
input,
select {
margin-left: 10px;
padding: 5px;
font-size: 16px;
}
button {
margin-top: 10px;
padding: 10px 15px;
font-size: 16px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background 0.3s;
}
button:hover {
background-color: #0056b3;
}
.reset-button {
background-color: #dc3545;
}
.reset-button:hover {
background-color: #c82333;
}
Output:
Ex.no: 38
AIM: Build a music store application using react components and provide
routing among the web pages
Src/app.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Header from './Header';
import Footer from './Footer';
import Home from './Home';
import Store from './Store';
import About from './About';
import NotFound from './NotFound';
Src/Header.js
import React from 'react';
import { Link } from 'react-router-dom';
Src/Home.js
import React from 'react';
Src/Store.js
import React from 'react';
return (
<main>
<h1>Store</h1>
<ul>
{products.map((product) => (
<li key={product.id}>
{product.name} - {product.price}
</li>
))}
</ul>
</main>
);
};
Src/About.js
import React from 'react';
Src/NotFound.js
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
src/index.css
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
header nav ul {
display: flex;
list-style: none;
background-color: #333;
padding: 0;
margin: 0;
}
header nav ul li {
margin: 0;
}
header nav ul li a {
color: white;
text-decoration: none;
padding: 10px 20px;
display: block;
}
footer {
text-align: center;
background: #333;
color: white;
padding: 10px 0;
position: fixed;
bottom: 0;
width: 100%;
}
main {
padding: 20px;
}
Output:
Ex.no: 38
AIM: Create a react application for an online store which consists of registration,
login, product information pages and implement routing to navigate through these
pages.
Structure:
src/
├── components/
│ ├── Header.js
│ ├── Footer.js
│ ├── Home.js
│ ├── Login.js
│ ├── Register.js
│ ├── Product.js
│ ├── NotFound.js
├── App.js
├── index.js
components/ Header.js
import React from 'react';
import { Link } from 'react-router-dom';
components/ Footer.js
import React from 'react';
components/ Home.js
import React from 'react';
components/ Login.js
import React, { useState } from 'react';
components/ Register.js
import React, { useState } from 'react';
components/ Product.js
import React from 'react';
return (
<main>
<h1>Products</h1>
<ul>
{products.map((product) => (
<li key={product.id}>
<h2>{product.name}</h2>
<p>{product.description}</p>
<p>Price: {product.price}</p>
</li>
))}
</ul>
</main>
);
};
components/ NotFound.js
import React from 'react';
App.js
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Output:
Ex.no: 39
AIM:
Create a food delivery website where users can order food from a
particular restaurant listed in the website for handling http requests and
responses using NodeJS.
Server.js
const http = require('http');
const url = require('url');
if (orderItem) {
res.statusCode = 200;
res.end(JSON.stringify({ message: `Order placed for ${orderItem.name}` }));
} else {
res.statusCode = 404;
res.end(JSON.stringify({ error: 'Item not found' }));
}
} else {
res.statusCode = 404;
// Create server
const server = http.createServer(requestListener);
Output:
Ex.no: 40
AIM: Create a Node JS application for user login system.
Server.js
const http = require("http");
const url = require("url");
const querystring = require("querystring");
const successPage = `
<!DOCTYPE html>
<html>
<head>
<title>Success</title>
</head>
<body>
<h1>Login Successful!</h1>
<a href="/">Go back</a>
</body>
</html>
`;
const failurePage = `
<!DOCTYPE html>
<html>
<head>
<title>Failure</title>
</head>
<body>
<h1>Login Failed</h1>
<p>Invalid username or password.</p>
<a href="/">Try Again</a>
</body>
</html>
`;
req.on("end", () => {
const { username, password } = querystring.parse(body);
} else {
// Handle 404
res.writeHead(404, { "Content-Type": "text/html" });
res.end("<h1>404 Not Found</h1>");
}
});
Output: