0% found this document useful (0 votes)
648 views54 pages

Full Stack Development Lab Syllabus

The document outlines the syllabus for a Full Stack Development Lab course under JNTU Hyderabad, detailing prerequisites, course objectives, and outcomes. It includes a list of experiments focusing on web application development using Node JS, React, Express, and Angular, along with MongoDB operations. Reference books for further reading are also provided.
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)
648 views54 pages

Full Stack Development Lab Syllabus

The document outlines the syllabus for a Full Stack Development Lab course under JNTU Hyderabad, detailing prerequisites, course objectives, and outcomes. It includes a list of experiments focusing on web application development using Node JS, React, Express, and Angular, along with MongoDB operations. Reference books for further reading are also provided.
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

R22 [Link].

CSE Syllabus JNTU Hyderabad

CS611PE: FULL STACK DEVELOPMENT LAB (Professional Elective – III)

[Link]. III Year II Sem. LT P C


00 21
Pre-Requisites:
[Link] Oriented Programming
[Link] Technologies
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

[Link] an application to setup node JS environment and display “Hello


World”.
[Link] a Node JS application for user login system.
[Link] a Node JS program to perform read, write and other operations on
a file.
[Link] a Node JS program to read form data from query string and
generate response using NodeJS
[Link] 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.
[Link] a program with basic commands on databases and collections
using MongoDB.
[Link] CRUD operations on the given dataset using MongoDB.
[Link] Count, Limit, Sort, and Skip operations on the given collections
using MongoDB.
[Link] an angular JS form to apply CSS and Events.
10. Develop a Job Registration form and validate it using angular JS.
11. Write an angular JS application to access JSON file data of an
employee from a server using $http service.
12. Develop a web application to manage student information using
Express and Angular JS.
13. Write a program to create a simple calculator Application using React
JS.
14. Write a program to create a voting application using React JS
15. Develop a leave management system for an organization where users
can apply different types of leaves such as casual leave and medical leave.
They also can view the available number of days using react application.
16. Build a music store application using react components and provide
routing among the web pages.
17. Create a react application for an online store which consist of
registration, login, product information pages and implement routing to3
navigate through these pages.

REFERENCE BOOKS:

[Link] Subramanian, Pro MERN Stack, Full Stack Web App


Developmentwith Mongo,
Express, React, and Node, 2ndEdition, Apress,2019.
[Link] Northwood, The Full Stack Developer: Your Essential Guide to the
Everyday Skills
Expected of a Modern Full Stack Web Developer’, 1stedition, Apress, 2018.
[Link] Green& Seshadri. Angular JS. 1st Edition. O'Reilly Media, 2013.
[Link] Chinnathambi, Learning React: A Hands-On Guide to Building
Web Applications Using
React and Redux, 2ndedition, Addison-Wesley Professional, 2018.
1. Create an application to setup node JS environment and display “Hello
World”.

var http = require('http');


[Link](function (req, res) {
[Link](200, {'Content-Type': 'text/html'});
[Link]('<h1>hello world....</h1>');
[Link]();
}).listen(8080);

Another way :
http = require('http');
listener = function (req, res) {
[Link](200, {'Content-Type': 'text/html'});
[Link]('Hello World......');
};
server = [Link](listener);
[Link](8080);

output :

>node [Link]

2. Create a Node JS application for user login system.

[Link]
const http = require('http');
const url = require('url');
const querystring = require('querystring');
// Mock user data (in-memory storage)
const users = {
'vamshi': '123456', // username: password
};

// HTML pages for responses


const loginPage = `
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form method='POST' action='/login'>
<label for='username'>Username:</label><br>
<input type='text' id='username' name='username' required><br><br>
<label for='password'>Password:</label><br>
<input type='password' id='password' name='password' required><br><br>
<button type='submit'>Login</button>
</form>
</body>
</html>
`;
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>
`;
// Create HTTP server
const server = [Link]((req, res) => {
const parsedUrl = [Link]([Link]);
const method = [Link];
if ([Link] === '/'&amp;&amp; method === 'GET') {
// Serve the login page
[Link](200, { 'Content-Type': 'text/html' });
[Link](loginPage);
} else if ([Link] === '/login'&amp;&amp; method === 'POST') {
// Handle login form submission

let body = '';


// Collect POST data
[Link]('data', (chunk) => {
body += [Link]();
});
[Link]('end', () => {
const { username, password } = [Link](body);
if (users[username] &amp;&amp; users[username] === password) {
// Login successful
[Link](200, { 'Content-Type': 'text/html' });
[Link](successPage);
} else {
// Login failed
[Link](401, { 'Content-Type': 'text/html' });
[Link](failurePage);
}
});
} else {
// Handle 404
[Link](404, { 'Content-Type': 'text/html' });
[Link]('<h1>404 Not Found</h1>');
}
});
// Start the server
const PORT = 3000;
[Link](PORT, () => {
[Link](`Server running at [Link]

});
3. Write a Node JS program to perform read, write and other
operations on a file.
[Link]
//READ FILE
var http = require('http');
var fs = require('fs');
[Link](function (req, res) {
[Link]('[Link]', function(err, data) {
[Link](200, {'Content-Type': 'text/html'});
[Link](data);
return [Link]();
});
}).listen(8080);

[Link]
WELCOME TO MGIT CSE1 FULL STACK DEVELOPMENT

Output:
file1 content:WELCOME TO MGIT CSE1 FULL STACK DEVELOPMENT

[Link]
//WRITE FILE ASYNCHRONOUS CALL
var fs = require('fs');
[Link]('[Link]', 'This is my text', function (err) {
if (err) throw err;
[Link]('Replaced!');
});
Output:
Replaced!

[Link]
//APPEND FILE ASYNCHRONOUS CALL
var fs = require('fs');
[Link]('[Link]', 'FULL STACK DEVELOPMENT', function (err) {
if (err) throw err;
[Link]('Saved!');
});

Output:
Saved!
[Link]
//DELETE FILE
var fs = require('fs');
[Link]('[Link]', function (err) {
if (err) throw err;
[Link]('File deleted!');
});

Output:
'File deleted!
4. Write a Node JS program to read form data from query string and generate
response using NodeJS

var http = require('http');


var url = require('url');
[Link](function (req, res) {
[Link](200, {'Content-Type': 'text/html'});
var q= [Link]([Link],true).query;
[Link](q);
var txt = [Link] + "" + [Link];
[Link](txt);
}).listen(8080);

OUTPUT :
[Link] 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.

[Link]
const http = require('http');
const url = require('url');
// Sample menu data
const menu = [
{ id: 1, name: 'Pizza', price: 10 },
{ id: 2, name: 'Burger', price: 5 },
{ id: 3, name: 'Pasta', price: 8 },
];
// Handle HTTP requests
const requestListener = (req, res) => {
const { method, url: reqUrl } = req;
// Set content type to JSON
[Link]('Content-Type', 'application/json');
// Parse the URL to handle routing
const parsedUrl = [Link](reqUrl, true);
const pathname = [Link];
if (method === 'GET') {
if (pathname === '/menu') {
// Send the menu items
[Link] = 200;
[Link]([Link](menu));
} else if ([Link]('/order')) {
// Extract the order ID from the URL
const orderId = [Link]('/')[2];
const orderItem = [Link](item => [Link] === parseInt(orderId));
if (orderItem) {
[Link] = 200;
[Link]([Link]({ message: `Order placed for ${[Link]}` }));
} else {
[Link] = 404;
[Link]([Link]({ error: 'Item not found' }));
}
} else {
[Link] = 404;
[Link]([Link]({ error: 'Route not found' }));
}
} else {
[Link] = 405; // Method Not Allowed
[Link]([Link]({ error: 'Method not allowed' }));
}
};
// Create server
const server = [Link](requestListener);
// Start server on port 3000
[Link](3000, () => {
[Link]('Server running on [Link]
});
OUTPUT :
6. Implement a program with basic commands on databases and
collections using MongoDB.

MONGODB COMMANDS (CRUD OPERATIONS):


C-CREATE
R-READ/RETRIVE
U-UPDATE
D-DELETE

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://[Link]:27017/?
directConnection=true&serverSelectionTimeoutMS=2000&appName=mongos
h+2.3.1
Using MongoDB: 8.0.0
Using Mongosh: 2.3.1
For mongosh info see: [Link]
------
The server generated these startup warnings when booting
2024-09-23T[Link].621+[Link] Access control is not enabled for the
database. Read and
write access to data and configuration is unrestricted
------
test>

[Link]> show dbs


admin 40.00 KiB
config 72.00 KiB
local 72.00 KiB

[Link]> use MYDB1


switched to db MYDB1
MYDB1> show dbs
admin 40.00 KiB
config 72.00 KiB
local 72.00 KiB

5.MYDB1> [Link]("students")
{ ok: 1 }

6.MYDB1> show dbs


MYDB1 8.00 KiB
admin 40.00 KiB
config 108.00 KiB
local 72.00 KiB

7.MYDB1> [Link]({"rollno":501 , "name":"cse1"})


{
acknowledged: true,
insertedId: ObjectId('66f255ec808c7f3e6bc73bf8')
}

8.MYDB1> show collections


Students

9.MYDB1> [Link]().pretty()
[
{
_id: ObjectId('66f255ec808c7f3e6bc73bf8'),
rollno: 501,
name: 'cse1'
}
]

10.MYDB1> [Link]({"rollno":502 , "name":"cse2"})


{
acknowledged: true,
insertedId: ObjectId('66f2577b808c7f3e6bc73bf9')
}

11.MYDB1> [Link]().pretty()
[
{
_id: ObjectId('66f255ec808c7f3e6bc73bf8'),
rollno: 501,
name: 'cse1'
},
{
_id: ObjectId('66f2577b808c7f3e6bc73bf9'),
rollno: 502,
name: 'cse2'
}
]

12.MYDB1> [Link]({rollno:502},{$set:{name:"cse3"}})
{
acknowledged: true,
insertedId: null,
matchedCount: 1
modifiedCount: 1,
upsertedCount: 0
}

13.MYDB1> [Link]().pretty()
[
{
_id: ObjectId('66f255ec808c7f3e6bc73bf8'),
rollno: 501,
name: 'cse1'
},
{
_id: ObjectId('66f2577b808c7f3e6bc73bf9'),
rollno: 502,
name: 'cse3'
}
]
14. MYDB1> [Link]({rollno:111})
{ acknowledged: true, deletedCount: 1 }
MYDB1> [Link]().pretty()
[
{
_id: ObjectId('670ca9a53fede232f9c73bf9'),
rollno: 222,
name: 'cccccc'
}
]

15.MYDB1> [Link]()
True

16.MYDB1> show collections

17.MYDB1> [Link]()
{ ok: 1, dropped: 'MYDB1' }

18.MYDB1> show dbs


admin 40.00 KiB
config 108.00 KiB
local 72.00 KiB

inserting documents from java scripts:


[Link]
[Link]({name: "Karthik", rollno: 101, marks: 98 })
[Link]({name: "Ravi", rollno: 102, marks: 99 })
[Link]({name: "Shiva", rollno: 103, marks: 100 })
[Link]({name: "Pavan", rollno: 104, marks: 80 })
MYDB1> load('d:\[Link]')
True

MYDB1> [Link]().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> [Link]()
{
_id: ObjectId('670ca9a53fede232f9c73bf9'),
rollno: 222,
name: 'cccccc'
}
MYDB1> [Link]({'name':'cccccc'})
{
_id: ObjectId('670ca9a53fede232f9c73bf9'),
rollno: 222,
name: 'cccccc'
}

[Link] CRUD operations on the given dataset using MongoDB.


Adding the MongoDB Driver to [Link]

[Link] install mongodb


added 12 packages, and audited 30 packages in 2s
found 0 vulnerabilities
[Link]

// Connect to database and close the database connection


const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Connect to database
[Link]()
.then(() => {
[Link]('Connected Successfully!')
//Close the database connection
[Link]('Exiting..')
[Link]()
})
.catch(error => [Link]('Failed to connect!', error))

Output:
MONGODB> node [Link]
Connected Successfully!
Exiting..

[Link]

// to insert one document


const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Insert to database
[Link]('MYDB').collection('students').insertOne({
name: 'cse1',
email: 'cse1@[Link]'
})
.then((res) => {
[Link](res)
[Link]()
})
.catch((err) => [Link](err))

Output:

MONGODB> node [Link]


{
acknowledged: true,
insertedId: new ObjectId('674aeea8b3bc707da2d4559f')
}

[Link]

//to find one document


const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Insert to database
[Link]('MYDB').collection('students')
.findOne({name:'cse1'})
.then((res) => {
[Link](res)
[Link]()
})
.catch((err) => [Link](err))

Output:

MONGODB>node [Link]
{
_id: new ObjectId('674aeea8b3bc707da2d4559f'),
name: 'cse1',
email: 'cse1@[Link]'
}
[Link]

//to update one document


const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Insert to database
[Link]('MYDB').collection('students')
.updateOne({ name: 'cse1' },
{
$set:
{ email: 'cse123@[Link]' }
})
.then((res) => {
[Link](res)
[Link]()
})
.catch((err) => [Link](err))

Output:
MONGODB> node [Link]

{
acknowledged: true,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0,
matchedCount: 1
}

[Link]

//to delete one document


const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Insert to database
[Link]('MYDB').collection('students')
.deleteOne({ name: 'cse1' })
.then((res) => {
[Link](res)
[Link]()
})
.catch((err) => [Link](err))

Output:

MONGODB> node [Link]


{ acknowledged: true, deletedCount: 1 }
8. Perform Count, Limit, Sort, and Skip operations on the given collections using
MongoDB.

test> use MYDB2


switched to db MYDB2

MYDB2> [Link]("employees");
{ ok: 1 }
MYDB2> [Link]([{'id':111, 'name':'aaaa', 'salary':10000},
{'id':222,'name':'bbbb', 'salary':30000},{'id':333, 'name':'cccc',
'salary':20000},{'id':444,'name':'dddd', 'salary':10000}])
{
acknowledged: true,
insertedIds: {
'0': ObjectId('6713c7d9b34f42f350c73bfc'),
'1': ObjectId('6713c7d9b34f42f350c73bfd'),
'2': ObjectId('6713c7d9b34f42f350c73bfe'),
'3': ObjectId('6713c7d9b34f42f350c73bff')
}
}
MYDB2> [Link]().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> [Link]().count()
4
MYDB2> [Link]({salary:10000}).count()
2
MYDB2> [Link]().pretty().limit(1)
[
{
_id: ObjectId('6713c7d9b34f42f350c73bfc'),
id: 111,
name: 'aaaa',
salary: 10000
}
]
MYDB2> [Link]().pretty().limit(2)
[
{
_id: ObjectId('6713c7d9b34f42f350c73bfc'),
id: 111,
name: 'aaaa',
salary: 10000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bfd'),
id: 222,
name: 'bbbb',
salary: 30000
}
]
MYDB2> [Link]().pretty().skip(2)
[
{
_id: ObjectId('6713c7d9b34f42f350c73bfe'),
id: 333,
name: 'cccc',
salary: 20000
},
{
_id: ObjectId('6713c7d9b34f42f350c73bff'),
id: 444,
name: 'dddd',
salary: 10000
}
]
MYDB2> [Link]().pretty().skip(3)
[
{
_id: ObjectId('6713c7d9b34f42f350c73bff'),
id: 444,
name: 'dddd',
salary: 10000
}
]
MYDB2> [Link]().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> [Link]().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
}
]

9. Develop an angular JS form to apply CSS and Events.

HTML
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS Form with CSS and Events</title>
<script
src="[Link]
script>
<style>
.error {
color: red;
font-size: 0.8em;
}
.valid {
color: green;
}
.highlight {
background-color: yellow;
}
.bold {
font-weight: bold;
}
</style>
</head>
<body ng-controller="FormController">

<h2>User Information Form</h2>

<form name="userForm" ng-submit="submitForm()" novalidate>


<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" ng-model="[Link]" required
ng-class="{'error': [Link].$invalid && [Link].
$touched, 'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()">
<div ng-show="[Link].$invalid && [Link].$touched"
class="error">Name is required.</div>
</div>

<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" ng-model="[Link]" required
ng-class="{'error': [Link].$invalid && [Link].
$touched, 'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()">
<div ng-show="[Link].$[Link] && [Link].$touched"
class="error">Email is required.</div>
<div ng-show="[Link].$[Link] && [Link].$touched"
class="error">Invalid email format.</div>
</div>

<div>
<label for="age">Age:</label>
<input type="number" id="age" name="age" ng-model="[Link]" min="18"
ng-class="{'error': [Link].$invalid && [Link].$touched,
'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()">
<div ng-show="[Link].$[Link] && [Link].$touched"
class="error">Age must be at least 18.</div>
</div>

<div>
<label for="city">City:</label>
<select id="city" name="city" ng-model="[Link]"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"
ng-change="cityChanged()">
<option value="">-- Select City --</option>
<option value="Karimnagar">Karimnagar</option>
<option value="Hyderabad">Hyderabad</option>
<option value="Warangal">Warangal</option>
<option value="Other">Other</option>
</select>
</div>

<div>
<label>Gender:</label>
<input type="radio" name="gender" value="male" ng-model="[Link]"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"> Male
<input type="radio" name="gender" value="female" ng-model="[Link]"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"> Female
</div>

<div>
<label>Interests:</label>
<input type="checkbox" name="interests" value="sports" ng-
model="[Link]"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"> Sports
<input type="checkbox" name="interests" value="music" ng-
model="[Link]"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"> Music
<input type="checkbox" name="interests" value="reading" ng-
model="[Link]"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"> Reading
</div>

<button type="submit" ng-disabled="userForm.$invalid"


ng-mouseover="toggleBold(true)" ng-mouseout="toggleBold(false)"
ng-class="{'bold': isBold}">Submit</button>

<div ng-show="submissionMessage"
class="{{submissionStatus}}">{{submissionMessage}}</div>
</form>

<script>
[Link]('myApp', [])
.controller('FormController', function($scope) {
$[Link] = {
name: '',
email: '',
age: null,
city: '',
gender: '',
interests: {
sports: false,
music: false,
reading: false
}
};

$[Link] = false;
$[Link] = false;
$[Link] = '';
$[Link] = '';

$[Link] = function() {
$[Link] = true;
};

$[Link] = function() {
$[Link] = false;
};

$[Link] = function(isMouseOver) {
$[Link] = isMouseOver;
};

$[Link] = function() {
[Link]('Selected city:', $[Link]);
// You can perform actions based on the selected city here
};

$[Link] = function() {
if ($[Link].$valid) {
[Link]('Form submitted:', $[Link]);
$[Link] = 'Form submitted successfully!';
$[Link] = 'valid';
// You would typically send this data to a server here
} else {
[Link]('Form is invalid.');
$[Link] = 'Please correct the form errors.';
$[Link] = 'error';
}
};
});
</script>

</body>
</html>

10. Develop a Job Registration form and validate it using angular JS

HTML
<!DOCTYPE html>
<html ng-app="jobRegistrationApp">
<head>
<title>Job Registration Form</title>
<script
src="[Link]
script>
<style>
.error {
color: red;
font-size: 0.8em;
}
.valid {
color: green;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input[type="text"],
input[type="email"],
input[type="tel"],
select,
textarea {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
button[type="submit"] {
background-color: #007bff;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
button[type="submit"]:disabled {
background-color: #ccc;
cursor: not-allowed;
}
.success-message {
color: green;
margin-top: 10px;
}
</style>
</head>
<body ng-controller="JobRegistrationController">

<h2>Job Registration Form</h2>

<form name="jobForm" ng-submit="submitForm()" novalidate>


<div class="form-group">
<label for="name">Full Name:</label>
<input type="text" id="name" name="name" ng-model="[Link]"
required>
<div ng-show="[Link].$invalid && [Link].$touched"
class="error">Full Name is required.</div>
</div>

<div class="form-group">
<label for="email">Email Address:</label>
<input type="email" id="email" name="email" ng-
model="[Link]" required>
<div ng-show="[Link].$[Link] && [Link].
$touched" class="error">Email Address is required.</div>
<div ng-show="[Link].$[Link] && [Link].$touched"
class="error">Invalid email format.</div>
</div>

<div class="form-group">
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone" ng-model="[Link]"
pattern="[0-9]{10}" required>
<div ng-show="[Link].$[Link] && [Link].
$touched" class="error">Phone Number is required.</div>
<div ng-show="[Link].$[Link] && [Link].
$touched" class="error">Invalid phone number (10 digits).</div>
</div>

<div class="form-group">
<label for="jobTitle">Desired Job Title:</label>
<input type="text" id="jobTitle" name="jobTitle" ng-
model="[Link]" required>
<div ng-show="[Link].$invalid && [Link].
$touched" class="error">Desired Job Title is required.</div>
</div>

<div class="form-group">
<label for="experience">Years of Experience:</label>
<select id="experience" name="experience" ng-
model="[Link]" required>
<option value="">-- Select --</option>
<option value="0">0 Years</option>
<option value="1">1 Year</option>
<option value="2">2 Years</option>
<option value="3">3+ Years</option>
</select>
<div ng-show="[Link].$invalid && [Link].
$touched" class="error">Years of Experience is required.</div>
</div>

<div class="form-group">
<label for="skills">Key Skills:</label>
<textarea id="skills" name="skills" ng-model="[Link]"
rows="4" required></textarea>
<div ng-show="[Link].$invalid && [Link].$touched"
class="error">Key Skills are required.</div>
</div>

<button type="submit" ng-disabled="jobForm.$invalid">Register</button>

<div ng-if="submissionMessage" class="success-


message">{{ submissionMessage }}</div>
</form>

<script>
[Link]('jobRegistrationApp', [])
.controller('JobRegistrationController', function($scope) {
$[Link] = {};
$[Link] = '';

$[Link] = function() {
if ($[Link].$valid) {
// Process the form data (e.g., send to server)
[Link]('Form Data:', $[Link]);
$[Link] = 'Registration successful!';
// Optionally reset the form
$[Link] = {};
$[Link].$setPristine();
$[Link].$setUntouched();
} else {
[Link]('Form is invalid. Please correct the
errors.');
$[Link] = ''; // Clear success message
if there are errors
}
};
});
</script>

</body>
</html>

11. Write an angular JS application to access JSON file data of an


employee from a server using $http service.

HTML
<!DOCTYPE html>
<html ng-app="employeeApp">
<head>
<title>Employee Data</title>
<script
src="[Link]
script>
<style>
body {
font-family: sans-serif;
}
.container {
width: 500px;
margin: 20px auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
h2 {
text-align: center;
}
.employee-details {
margin-top: 20px;
border: 1px solid #eee;
padding: 15px;
border-radius: 3px;
}
.employee-details p {
margin: 5px 0;
}
.error {
color: red;
margin-top: 10px;
}
.loading {
font-style: italic;
color: gray;
}
</style>
</head>
<body ng-controller="EmployeeController">
<div class="container">
<h2>Employee Information</h2>

<button ng-click="fetchEmployeeData()">Fetch Employee Data</button>

<div ng-if="loading" class="loading">Loading employee data...</div>

<div ng-if="employee" class="employee-details">


<h3>{{ [Link] }}</h3>
<p><strong>ID:</strong> {{ [Link] }}</p>
<p><strong>Email:</strong> {{ [Link] }}</p>
<p><strong>Department:</strong> {{ [Link] }}</p>
<p><strong>Designation:</strong> {{ [Link] }}</p>
</div>

<div ng-if="error" class="error">Error fetching data: {{ error }}</div>


</div>

<script>
[Link]('employeeApp', [])
.controller('EmployeeController', ['$scope', '$http',
function($scope, $http) {
$[Link] = null;
$[Link] = null;
$[Link] = false;

$[Link] = function() {
$[Link] = true;
$[Link] = null;
$[Link] = null;

// Replace '[Link]' with the actual URL of


your JSON file on the server
$[Link]('[Link]')
.then(function(response) {
$[Link] = [Link];
$[Link] = false;
})
.catch(function(error) {
$[Link] = [Link] || 'An error
occurred while fetching data.';
$[Link] = false;
});
};
}]);
</script>

</body>
</html>

12. Develop a web application to manage student information using


Express and Angular JS.

Project Structure:

student-management/
├── server/
│ ├── [Link]
│ ├── routes/
│ │ └── [Link]
│ └── models/
│ └── [Link]
├── public/
│ ├── [Link]
│ ├── [Link]
│ ├── controllers/
│ │ └── [Link]
│ ├── services/
│ │ └── [Link]
│ └── css/
│ └── [Link]
└── [Link]

1. Backend ([Link]):

a) server/[Link]:

JSON
{
"name": "student-management-server",
"version": "1.0.0",
"description": "Backend for student management app",
"main": "[Link]",
"scripts": {
"start": "node [Link]"
},
"dependencies": {
"express": "^4.18.2",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"mongoose": "^8.0.3"
},
"devDependencies": {
"nodemon": "^3.0.2"
}
}

Run npm install in the server directory.

b) server/models/[Link]:

JavaScript
const mongoose = require('mongoose');

const studentSchema = new [Link]({


name: { type: String, required: true },
email: { type: String, required: true, unique: true },
major: String,
grade: Number
});

[Link] = [Link]('Student', studentSchema);

c) server/routes/[Link]:

JavaScript
const express = require('express');
const router = [Link]();
const Student = require('../models/student');

// GET all students


[Link]('/', async (req, res) => {
try {
const students = await [Link]();
[Link](students);
} catch (err) {
[Link](500).json({ message: [Link] });
}
});

// GET a specific student by ID


[Link]('/:id', async (req, res) => {
try {
const student = await [Link]([Link]);
if (!student) {
return [Link](404).json({ message: 'Student not found' });
}
[Link](student);
} catch (err) {
[Link](500).json({ message: [Link] });
}
});

// POST a new student


[Link]('/', async (req, res) => {
const student = new Student({
name: [Link],
email: [Link],
major: [Link],
grade: [Link]
});

try {
const newStudent = await [Link]();
[Link](201).json(newStudent);
} catch (err) {
[Link](400).json({ message: [Link] });
}
});

// PUT (update) an existing student


[Link]('/:id', async (req, res) => {
try {
const student = await [Link]([Link]);
if (!student) {
return [Link](404).json({ message: 'Student not found' });
}
if ([Link]) [Link] = [Link];
if ([Link]) [Link] = [Link];
if ([Link]) [Link] = [Link];
if ([Link]) [Link] = [Link];

const updatedStudent = await [Link]();


[Link](updatedStudent);
} catch (err) {
[Link](400).json({ message: [Link] });
}
});

// DELETE a student
[Link]('/:id', async (req, res) => {
try {
const student = await [Link]([Link]);
if (!student) {
return [Link](404).json({ message: 'Student not found' });
}
[Link]({ message: 'Student deleted successfully' });
} catch (err) {
[Link](500).json({ message: [Link] });
}
});

[Link] = router;

d) server/[Link]:

JavaScript
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const studentRoutes = require('./routes/students');

const app = express();


const port = 3000;

[Link](cors());
[Link]([Link]());
[Link]('/api/students', studentRoutes);

// MongoDB Connection
[Link]('mongodb://[Link]:27017/studentDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = [Link];
[Link]('error', [Link](console, 'MongoDB connection error:'));
[Link]('open', () => {
[Link]('Connected to MongoDB');
});

[Link](port, () => {
[Link](`Server listening on port ${port}`);
});

2. Frontend (AngularJS):

a) public/[Link]:

<!DOCTYPE html>
<html ng-app="studentApp">
<head>
<title>Student Management</title>
<link rel="stylesheet" href="css/[Link]">
<script
src="[Link]
script>
<script src="[Link]"></script>
<script src="controllers/[Link]"></script>
<script src="services/[Link]"></script>
</head>
<body>
<div ng-controller="StudentController">
<h1>Student Management</h1>

<div>
<h2>Add New Student</h2>
<form ng-submit="addStudent()">
<label for="name">Name:</label>
<input type="text" id="name" ng-model="[Link]"
required><br><br>

<label for="email">Email:</label>
<input type="email" id="email" ng-model="[Link]"
required><br><br>

<label for="major">Major:</label>
<input type="text" id="major" ng-model="[Link]"><br><br>

<label for="grade">Grade:</label>
<input type="number" id="grade" ng-model="[Link]"><br><br>

<button type="submit">Add Student</button>


</form>
<div ng-if="addError" class="error">{{ addError }}</div>
<div ng-if="addSuccess" class="success">{{ addSuccess }}</div>
</div>

<hr>

<div>
<h2>Student List</h2>
<ul ng-if="[Link] > 0">
<li ng-repeat="student in students">
{{ [Link] }} ({{ [Link] }}) - Major: {{ [Link] ||
'N/A' }}, Grade: {{ [Link] || 'N/A' }}
<button ng-click="editStudent(student._id)">Edit</button>
<button ng-click="deleteStudent(student._id)">Delete</button>
</li>
</ul>
<p ng-if="[Link] === 0">No students found.</p>
<div ng-if="fetchError" class="error">{{ fetchError }}</div>
</div>

<hr>

<div ng-if="editingStudent">
<h2>Edit Student</h2>
<form ng-submit="updateStudent()">
<label for="editName">Name:</label>
<input type="text" id="editName" ng-model="[Link]"
required><br><br>

<label for="editEmail">Email:</label>
<input type="email" id="editEmail" ng-model="[Link]"
required><br><br>

<label for="editMajor">Major:</label>
<input type="text" id="editMajor" ng-
model="[Link]"><br><br>

<label for="editGrade">Grade:</label>
<input type="number" id="editGrade" ng-
model="[Link]"><br><br>

<button type="submit">Update Student</button>


<button ng-click="cancelEdit()">Cancel</button>
</form>
<div ng-if="updateError" class="error">{{ updateError }}</div>
<div ng-if="updateSuccess" class="success">{{ updateSuccess }}</div>
</div>
</div>
</body>
</html>

b) public/[Link]:

JavaScript
[Link]('studentApp', []);

c) public/controllers/[Link]:

JavaScript
[Link]('studentApp')
.controller('StudentController', ['$scope', 'StudentService', function($scope,
StudentService) {
$[Link] = [];
$[Link] = {};
$[Link] = null;
$[Link] = null;
$[Link] = null;
$[Link] = null;
$[Link] = null;
$[Link] = null;

// Fetch all students


$[Link] = function() {
[Link]()
.then(function(response) {
$[Link] = [Link];
$[Link] = null;
})
.catch(function(error) {
$[Link] = 'Error fetching students: ' + [Link]
|| [Link];
$[Link] = [];
});
};

$[Link](); // Load students on page load

// Add a new student


$[Link] = function() {
$[Link] = null;
$[Link] = null;
[Link]($[Link])
.then(function(response) {
$[Link]([Link]);
$[Link] = {}; // Clear the form
$[Link] = 'Student added successfully!';
})
.catch(function(error) {
$[Link] = 'Error adding student: ' + [Link] ||
[Link];
});
};

// Edit a student
$[Link] = function(id) {
$[Link] = null;
$[Link] = null;
[Link](id)
.then(function(response) {
$[Link] = [Link]([Link]); // Create a copy
to avoid direct modification
})
.catch(function(error) {
[Link]('Error fetching student for edit:', error);
$[Link] = 'Error fetching student details.';
});
};

// Update a student
$[Link] = function() {
$[Link] = null;
$[Link] = null;
[Link]($[Link]._id,
$[Link])
.then(function(response) {
const index = $[Link](student => student._id ===
[Link]._id);
if (index !== -1) {
$[Link][index] = [Link];
}
$[Link] = null; // Hide edit form
$[Link] = 'Student updated successfully!';
})
.catch(function(error) {
$[Link] = 'Error updating student: ' + [Link]
|| [Link];
});
};

// Cancel edit
$[Link] = function() {
$[Link] = null;
};

// Delete a student
$[Link] = function(id) {
if (confirm('Are you sure you want to delete this student?')) {
[Link](id)
.then(function(response) {
$[Link] = $[Link](student => student._id !==
id);
})
.catch(function(error) {
[Link]('Error deleting student:', error);
});
}
};
}]);

d) public/services/[Link]:

JavaScript
[Link]('studentApp')
.service('StudentService', ['$http', function($http) {
const baseUrl = '/api/students';

[Link] = function() {
return $[Link](baseUrl);
};

[Link] = function(id) {
return $[Link](baseUrl + '/' + id);
};

[Link] = function(studentData) {
return $[Link](baseUrl, studentData);
};

[Link] = function(id, studentData) {


return $[Link](baseUrl + '/' + id, studentData);
};

[Link] = function(id) {
return $[Link](baseUrl + '/' + id);
};
}]);

e) public/css/[Link]:

CSS
body {
font-family: sans-serif;
margin: 20px;
}

.error {
color: red;
margin-top: 5px;
}

.success {
color: green;
margin-top: 5px;
}

label {
display: inline-block;
width: 100px;
text-align: right;
margin-right: 10px;
}

input[type="text"],
input[type="email"],
input[type="number"] {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
width: 200px;
}

button {
padding: 8px 15px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin-right: 5px;
}

button:hover {
background-color: #0056b3;
}

ul {
list-style-type: none;
padding: 0;
}

li {
padding: 8px 0;
border-bottom: 1px solid #eee;
}

li:last-child {
border-bottom: none;
}

How to Run the Application:

1. Navigate to the server directory in your terminal and run:

Bash

npm install
npm start

This will start the [Link] backend server on port 3000. Make sure you have MongoDB
running on mongodb://[Link]:27017.
2. Navigate to the student-management directory (the root of your project) and open the
public/[Link] file in your web browser.

13. Write a program to create a simple calculator Application using


React JS.

Src/[Link]

import React, { useState } from "react";


import "./[Link]";
function App() {
const [input, setInput] = useState("");
const handleButtonClick = (value) => {
if (value === "=") {
try {
setInput(eval(input).toString()); // Caution: Avoid `eval` in production apps.
} catch (error) {
setInput("Error");
}
} else if (value === "C") {
setInput("");
} else {
setInput(input + value);
}
};
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>
);
}
export default App;

Src/[Link]

.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 :
14. Write a program to create a voting application using React JS
Src/[Link]

import React, { useState } from "react";


import "./[Link]";
function App() {
const [candidates, setCandidates] = useState([
{ name: "CSE1", votes: 0 },
{ name: "CSE2", votes: 0 },
{ name: "CSE3", votes: 0 },
]);
const handleVote = (index) => {
const updatedCandidates = [...candidates];
updatedCandidates[index].votes += 1;
setCandidates(updatedCandidates);
};
const resetVotes = () => {
const resetCandidates = [Link]((candidate) => ({
...candidate,
votes: 0,
}));
setCandidates(resetCandidates);
};
return (
<div className="App">
<h1>Voting Application</h1>
<div className="candidates">
{[Link]((candidate, index) => (
<div key={index} className="candidate">
<span>{[Link]}</span>
<span>{[Link]} votes</span>
<button onClick={() => handleVote(index)}>Vote</button>
</div>
))}
</div>
<button className="reset" onClick={resetVotes}>
Reset Votes
</button>
</div>
);
}
export default App;

Src/[Link]
.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 :
15. Develop a leave management system for an organization where users can
apply different types of leaves such as casual leave and medical leave. They
also can view the available number of days using react application.

Src/[Link]

import React, { useState } from "react";


import "./[Link]";
function App() {
const initialLeaveBalance = {
CasualLeave: 12,
MedicalLeave: 10,
EarnedLeave: 8,
};
const [leaveBalance, setLeaveBalance] = useState(initialLeaveBalance);
const [leaveHistory, setLeaveHistory] = useState([]);
const [selectedLeaveType, setSelectedLeaveType] = useState("CasualLeave");
const [leaveDays, setLeaveDays] = useState(1);
const handleApplyLeave = () => {
if (leaveDays < 1 || isNaN(leaveDays)) {
alert("Please enter a valid number of days.");
return;
}
if (leaveBalance[selectedLeaveType] >= leaveDays) {
// Update leave balance
setLeaveBalance({
...leaveBalance,
[selectedLeaveType]: leaveBalance[selectedLeaveType] - leaveDays,
});
// Add to leave history
setLeaveHistory([
...leaveHistory,
{
type: selectedLeaveType,
days: leaveDays,
date: new Date().toLocaleDateString(),
},
]);
alert("Leave applied successfully!");
} else {
alert("Not enough leave balance!");
}
};
const handleResetLeaves = () => {
setLeaveBalance(initialLeaveBalance);
setLeaveHistory([]);
};
return (
<div className="App">
<h1>Leave Management System</h1>
<div className="leave-balance">
<h2>Leave Balance</h2>
<ul>
{[Link](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([Link])}
>
{[Link](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([Link]))}
/>
</label>
<button onClick={handleApplyLeave}>Apply Leave</button>
</div>
<div className="leave-history">
<h2>Leave History</h2>
{[Link] > 0 ? (
<ul>
{[Link]((leave, index) => (
<li key={index}>
{[Link]}: {[Link]} day(s) on {[Link]}
</li>
))}
</ul>
):(
<p>No leave history available.</p>
)}
</div>
<button className="reset-button" onClick={handleResetLeaves}>
Reset Leave Balances
</button>
</div>
);
}
export default App;

Src/[Link]

.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 :
16. Build a music store application using react components and provide routing
among the web pages.

Src/[Link]

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';
const App = () => (
<Router>
<Header />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/store" element={<Store />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<NotFound />} />
</Routes>
<Footer />
</Router>
);
export default App;
Src/[Link]
import React from 'react';
import { Link } from 'react-router-dom';
const Header = () => (
<header>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/store">Store</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
</nav>
</header>
);
export default Header;
Src/[Link]
import React from 'react';
const Footer = () => (
<footer>
<p>&copy; 2024 Music Store</p>
</footer>
);
export default Footer;
Src/[Link]
import React from 'react';
const Home = () => (
<main>
<h1>Welcome to the Music Store</h1>
<p>Your one-stop shop for musical instruments and gear!</p>
</main>
);
export default Home;
Src/[Link]
import React from 'react';
const Store = () => {
const products = [
{ id: 1, name: 'Acoustic Guitar', price: '$200' },
{ id: 2, name: 'Electric Guitar', price: '$400' },
{ id: 3, name: 'Drum Set', price: '$600' },
];
return (
<main>
<h1>Store</h1>
<ul>
{[Link]((product) => (
<li key={[Link]}>
{[Link]} - {[Link]}
</li>
))}
</ul>
</main>
);
};
export default Store;

Src/[Link]
import React from 'react';
const About = () => (
<main>
<h1>About Us</h1>
<p>We are passionate about music and dedicated to serving musicians
worldwide.</p>
</main>
);
export default About;

Src/[Link]
import React from 'react';
const NotFound = () => (
<main>
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
</main>
);
export default NotFound;
src/[Link]
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './[Link]';
[Link](
<[Link]>
<App />
</[Link]>,
[Link]('root')
);

src/[Link]
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;
}
header nav ul li a:hover {
background-color: #575757;
}
footer {
text-align: center;
background: #333;
color: white;
padding: 10px 0;
position: fixed;
bottom: 0;
width: 100%;
}
main {
padding: 20px;
}

output :
17. Create a react application for an online store which consist of registration,
login, product information pages and implement routing to navigate through
these pages.

Structure:
src/
├── components/
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
├── [Link]
├── [Link]
components/ [Link]
import React from 'react';
import { Link } from 'react-router-dom';
const Header = () => (
<header>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/login">Login</Link></li>
<li><Link to="/register">Register</Link></li>
<li><Link to="/product">Product</Link></li>
</ul>
</nav>
</header>
);
export default Header;
components/ [Link]
import React from 'react';
const Footer = () => (
<footer>
<p>&copy; 2024 Online Store</p>
</footer>
);
export default Footer;

components/ [Link]
import React from 'react';
const Home = () => (
<main>
<h1>Welcome to the Online Store</h1>
<p>Shop the best products here!</p>
</main>
);
export default Home;
components/ [Link]
import React, { useState } from 'react';
const Login = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = (e) => {
[Link]();
alert(`Logged in with email: ${email}`);
};
return (
<main>
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<label>
Email:
<input type="email" value={email} onChange={(e) =>
setEmail([Link])}
required />
</label>
<br />
<label>
Password:
<input type="password" value={password} onChange={(e) =>
setPassword([Link])} required />
</label>
<br />
<button type="submit">Login</button>
</form>
</main>
);
};
export default Login;
components/ [Link]
import React, { useState } from 'react';
const Register = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
});
const handleChange = (e) => {
setFormData({ ...formData, [[Link]]: [Link] });
};
const handleSubmit = (e) => {
[Link]();
alert(`Registered: ${[Link]} (${[Link]})`);
};
return (
<main>
<h1>Register</h1>
<form onSubmit={handleSubmit}>
<label>
Name:
<input name="name" type="text" value={[Link]}
onChange={handleChange} required />
</label>
<br />
<label>
Email:
<input name="email" type="email" value={[Link]}
onChange={handleChange} required />
</label>
<br />
<label>
Password:
<input name="password" type="password" value={[Link]}
onChange={handleChange} required />
</label>
<br />
<button type="submit">Register</button>
</form>
</main>
);
};
export default Register;
components/ [Link]
import React from 'react';
const Product = () => {
const products = [
{ id: 1, name: 'Laptop', price: '$1000', description: 'High-performance laptop.' },
{ id: 2, name: 'Headphones', price: '$200', description: 'Noise-cancelling
headphones.' },
{ id: 3, name: 'Smartphone', price: '$800', description: 'Latest-gen
smartphone.' },
];
return (
<main>
<h1>Products</h1>
<ul>
{[Link]((product) => (
<li key={[Link]}>
<h2>{[Link]}</h2>
<p>{[Link]}</p>
<p>Price: {[Link]}</p>
</li>
))}
</ul>
</main>
);
};
export default Product
components/ [Link]
import React from 'react';
const NotFound = () => (
<main>
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
</main>
);
export default NotFound;
[Link]
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Header from './components/Header';
import Footer from './components/Footer';
import Home from './components/Home';
import Login from './components/Login';
import Register from './components/Register';
import Product from './components/Product';
import NotFound from './components/NotFound';
const App = () => (
<Router>
<Header />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="/product" element={<Product />} />
<Route path="*" element={<NotFound />} />
</Routes>
<Footer />
</Router>
);
export default App;
[Link]
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './[Link]';
[Link](
<[Link]>
<App />
</[Link]>,
[Link]('root')
);

output:

Common questions

Powered by AI

React Router plays a critical role in developing multi-page React applications, particularly in e-commerce. It facilitates navigation by enabling client-side routing, improving performance as navigation between pages does not require full page reloads. By maintaining the application state and loading the necessary components dynamically, React Router provides smooth and quick transitions between pages, enhancing user experience. Furthermore, it allows developers to manage complex routing configurations intuitively, defining specific paths and components to render, thus ensuring optimal application flow and user interaction .

Error handling in AngularJS forms is crucial for user experience and data integrity. It involves displaying feedback immediately when a field does not meet validation criteria. AngularJS uses "ng-show" directives to conditionally display error messages when form inputs are invalid. The 'ng-form' directive's '$invalid' state prevents form submission until validation errors are corrected. This approach ensures users correct errors before submission, minimizing data corruption or incomplete entries. It also enhances user experience by guiding users with immediate feedback, reducing frustration and entry errors .

The AngularJS job registration form requires each input field to be validated for specific criteria: a name, email, phone number, job title, and experience years. Each field has validation rules. For example, the name and job title must not be empty. The email must be in a valid format, and the phone number must be exactly 10 digits long. The form uses AngularJS directives such as "ng-required" and "ng-pattern" to enforce these constraints. It also provides immediate feedback using "ng-show" to display error messages when the inputs are invalid or untouched. By being unable to submit the form until these conditions are met ("ng-disabled" directive), the data integrity is assured, preventing incomplete or incorrect submissions .

Express.js sets up a backend environment for an AngularJS application by defining a server-side framework to handle HTTP requests and responses. It enables routing to different endpoints through middleware functions that process requests and deliver responses based on client actions. This includes database operations (read/write) and returning appropriate JSON data for AngularJS to process. With its lightweight and flexible structure, Express.js abstracts many low-level network details, allowing developers to define concise and scalable code paths crucial for managing operations and interactions within an AngularJS-powered web application .

In AngularJS, form model binding allows seamless integration between the view (HTML templates) and the controller. This is achieved through the 'ng-model' directive that binds HTML input elements directly to properties on the controller's scope. Changes in the view automatically update the scope in the controller and vice versa, enabling real-time data synchronization without additional code. This two-way data binding simplifies the management of form data and state within an application, enhancing development efficiency and reducing the risk of synchronization bugs .

Express.js complements AngularJS by serving as a robust back-end framework that handles server-side operations, such as routing and data management, while AngularJS is used for building the client-side UI and handling user interactions. In managing student information, Express.js provides RESTful API endpoints that AngularJS can communicate with using HTTP requests. Express.js processes these requests, interacts with databases to perform CRUD operations, and returns data to AngularJS. This separation of front-end and back-end development allows each technology to excel in its domain, providing a scalable and maintainable architecture for a web application .

AngularJS uses the $http service to facilitate the integration with external data sources by allowing HTTP requests to fetch, send, or update data from external servers. By defining methods like $http.get(), $http.post(), and $http.put(), developers can easily interact with RESTful APIs to retrieve JSON data or submit form information to a server. This service handles the complexity of asynchronous data calls, providing a promise-based interface that simplifies the logic needed to process server responses and potential errors, offering efficient data exchange in web applications .

A React component in an e-commerce application is structured to manage state using React's state management tools, such as 'useState' for functional components. Each component, like 'Product', maintains its local state to store product attributes (e.g., product list). It renders product information by mapping through the state array, dynamically generating HTML elements for each product entry. This separation of data logic and UI components enhances maintainability, allowing updates to the state to trigger re-renders efficiently, providing a reactive and seamless user experience in displaying product data .

The 'ng-class' directive in AngularJS enhances user interaction by dynamically applying CSS classes based on the expression's evaluation. In form operations, it highlights input fields when they are focused ('highlight' class) and visually indicates validation errors ('error' class). This visual feedback guides users through the form-filling process, improving UX by making it intuitive to identify which fields require attention or are in error. Moreover, it allows developers to easily implement conditional styles that respond to user actions, providing a more interactive and responsive application interface .

In an AngularJS application managing student information, the application is structured with a separation of concerns between components: controllers handle user interaction and view logic, while services manage business logic and data persistence tasks. The StudentController coordinates user actions and view updates. It fetches, edits, and deletes student data through the StudentService. This service handles HTTP requests to a REST API, abstracting data operations (CRUD operations). This architecture enables reusability and modularity, allowing the application to scale efficiently with clearly defined interactions between UI and back-end data processes .

You might also like