FSD Manual
FSD Manual
List of Experiments
REFERENCE BOOKS:
Another way :
http = require('http');
listener = function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World......');
};
server = http.createServer(listener);
server.listen(8080);
output :
>node hello1.js
Server.js
const http = require('http');
const url = require('url');
const querystring = require('querystring');
// Mock user data (in-memory storage)
const users = {
'vamshi': '123456', // username: password
};
});
3. Write a Node JS program to perform read, write and other
operations on a file.
readFile.js
//READ FILE
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('file1.txt', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
File1.txt
WELCOME TO MGIT CSE1 FULL STACK DEVELOPMENT
Output:
file1 content:WELCOME TO MGIT CSE1 FULL STACK DEVELOPMENT
writeFile.js
//WRITE FILE ASYNCHRONOUS CALL
var fs = require('fs');
fs.writeFile('file1.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Replaced!');
});
Output:
Replaced!
appendFile.js
//APPEND FILE ASYNCHRONOUS CALL
var fs = require('fs');
fs.appendFile('file1.txt', 'FULL STACK DEVELOPMENT', function (err) {
if (err) throw err;
console.log('Saved!');
});
Output:
Saved!
Deletefile.js
//DELETE FILE
var fs = require('fs');
fs.unlink('file2.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
Output:
'File deleted!
4. Write a Node JS program to read form data from query string and generate
response using NodeJS
OUTPUT :
5.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');
// 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
res.setHeader('Content-Type', 'application/json');
// Parse the URL to handle routing
const parsedUrl = url.parse(reqUrl, true);
const pathname = parsedUrl.pathname;
if (method === 'GET') {
if (pathname === '/menu') {
// Send the menu items
res.statusCode = 200;
res.end(JSON.stringify(menu));
} else if (pathname.startsWith('/order')) {
// Extract the order ID from the URL
const orderId = pathname.split('/')[2];
const orderItem = menu.find(item => item.id === parseInt(orderId));
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;
res.end(JSON.stringify({ error: 'Route not found' }));
}
} else {
res.statusCode = 405; // Method Not Allowed
res.end(JSON.stringify({ error: 'Method not allowed' }));
}
};
// Create server
const server = http.createServer(requestListener);
// Start server on port 3000
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
OUTPUT :
6. 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=mongos
h+2.3.1
Using MongoDB: 8.0.0
Using Mongosh: 2.3.1
For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
------
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>
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
17.MYDB1> db.dropDatabase()
{ ok: 1, dropped: 'MYDB1' }
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'
}
Output:
MONGODB> node connect.js
Connected Successfully!
Exiting..
Insertdb.js
Output:
Finddb.js
Output:
MONGODB>node finddb.js
{
_id: new ObjectId('674aeea8b3bc707da2d4559f'),
name: 'cse1',
email: '[email protected]'
}
Updatedb.js
Output:
MONGODB> node updatedb.js
{
acknowledged: true,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0,
matchedCount: 1
}
Deletedb.js
Output:
MYDB2> db.createCollection("employees");
{ ok: 1 }
MYDB2> db.employees.insertMany([{'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> 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
}
]
HTML
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS Form with CSS and Events</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
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">
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" ng-model="user.email" required
ng-class="{'error': userForm.email.$invalid && userForm.email.
$touched, 'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()">
<div ng-show="userForm.email.$error.required && userForm.email.$touched"
class="error">Email is required.</div>
<div ng-show="userForm.email.$error.email && userForm.email.$touched"
class="error">Invalid email format.</div>
</div>
<div>
<label for="age">Age:</label>
<input type="number" id="age" name="age" ng-model="user.age" min="18"
ng-class="{'error': userForm.age.$invalid && userForm.age.$touched,
'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()">
<div ng-show="userForm.age.$error.min && userForm.age.$touched"
class="error">Age must be at least 18.</div>
</div>
<div>
<label for="city">City:</label>
<select id="city" name="city" ng-model="user.city"
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="user.gender"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"> Male
<input type="radio" name="gender" value="female" ng-model="user.gender"
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="user.interests.sports"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"> Sports
<input type="checkbox" name="interests" value="music" ng-
model="user.interests.music"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"> Music
<input type="checkbox" name="interests" value="reading" ng-
model="user.interests.reading"
ng-class="{'highlight': isHighlighted}"
ng-focus="highlightInput()" ng-blur="unhighlightInput()"> Reading
</div>
<div ng-show="submissionMessage"
class="{{submissionStatus}}">{{submissionMessage}}</div>
</form>
<script>
angular.module('myApp', [])
.controller('FormController', function($scope) {
$scope.user = {
name: '',
email: '',
age: null,
city: '',
gender: '',
interests: {
sports: false,
music: false,
reading: false
}
};
$scope.isHighlighted = false;
$scope.isBold = false;
$scope.submissionMessage = '';
$scope.submissionStatus = '';
$scope.highlightInput = function() {
$scope.isHighlighted = true;
};
$scope.unhighlightInput = function() {
$scope.isHighlighted = false;
};
$scope.toggleBold = function(isMouseOver) {
$scope.isBold = isMouseOver;
};
$scope.cityChanged = function() {
console.log('Selected city:', $scope.user.city);
// You can perform actions based on the selected city here
};
$scope.submitForm = function() {
if ($scope.userForm.$valid) {
console.log('Form submitted:', $scope.user);
$scope.submissionMessage = 'Form submitted successfully!';
$scope.submissionStatus = 'valid';
// You would typically send this data to a server here
} else {
console.log('Form is invalid.');
$scope.submissionMessage = 'Please correct the form errors.';
$scope.submissionStatus = 'error';
}
};
});
</script>
</body>
</html>
HTML
<!DOCTYPE html>
<html ng-app="jobRegistrationApp">
<head>
<title>Job Registration Form</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
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">
<div class="form-group">
<label for="email">Email Address:</label>
<input type="email" id="email" name="email" ng-
model="formData.email" required>
<div ng-show="jobForm.email.$error.required && jobForm.email.
$touched" class="error">Email Address is required.</div>
<div ng-show="jobForm.email.$error.email && jobForm.email.$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="formData.phone"
pattern="[0-9]{10}" required>
<div ng-show="jobForm.phone.$error.required && jobForm.phone.
$touched" class="error">Phone Number is required.</div>
<div ng-show="jobForm.phone.$error.pattern && jobForm.phone.
$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="formData.jobTitle" required>
<div ng-show="jobForm.jobTitle.$invalid && jobForm.jobTitle.
$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="formData.experience" 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="jobForm.experience.$invalid && jobForm.experience.
$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="formData.skills"
rows="4" required></textarea>
<div ng-show="jobForm.skills.$invalid && jobForm.skills.$touched"
class="error">Key Skills are required.</div>
</div>
<script>
angular.module('jobRegistrationApp', [])
.controller('JobRegistrationController', function($scope) {
$scope.formData = {};
$scope.submissionMessage = '';
$scope.submitForm = function() {
if ($scope.jobForm.$valid) {
// Process the form data (e.g., send to server)
console.log('Form Data:', $scope.formData);
$scope.submissionMessage = 'Registration successful!';
// Optionally reset the form
$scope.formData = {};
$scope.jobForm.$setPristine();
$scope.jobForm.$setUntouched();
} else {
console.log('Form is invalid. Please correct the
errors.');
$scope.submissionMessage = ''; // Clear success message
if there are errors
}
};
});
</script>
</body>
</html>
HTML
<!DOCTYPE html>
<html ng-app="employeeApp">
<head>
<title>Employee Data</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
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>
<script>
angular.module('employeeApp', [])
.controller('EmployeeController', ['$scope', '$http',
function($scope, $http) {
$scope.employee = null;
$scope.error = null;
$scope.loading = false;
$scope.fetchEmployeeData = function() {
$scope.loading = true;
$scope.employee = null;
$scope.error = null;
</body>
</html>
Project Structure:
student-management/
├── server/
│ ├── server.js
│ ├── routes/
│ │ └── students.js
│ └── models/
│ └── student.js
├── public/
│ ├── index.html
│ ├── app.js
│ ├── controllers/
│ │ └── studentController.js
│ ├── services/
│ │ └── studentService.js
│ └── css/
│ └── style.css
└── package.json
1. Backend (Express.js):
a) server/package.json:
JSON
{
"name": "student-management-server",
"version": "1.0.0",
"description": "Backend for student management app",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.18.2",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"mongoose": "^8.0.3"
},
"devDependencies": {
"nodemon": "^3.0.2"
}
}
b) server/models/student.js:
JavaScript
const mongoose = require('mongoose');
c) server/routes/students.js:
JavaScript
const express = require('express');
const router = express.Router();
const Student = require('../models/student');
try {
const newStudent = await student.save();
res.status(201).json(newStudent);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
// DELETE a student
router.delete('/:id', async (req, res) => {
try {
const student = await Student.findByIdAndDelete(req.params.id);
if (!student) {
return res.status(404).json({ message: 'Student not found' });
}
res.json({ message: 'Student deleted successfully' });
} catch (err) {
res.status(500).json({ message: err.message });
}
});
module.exports = router;
d) server/server.js:
JavaScript
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const studentRoutes = require('./routes/students');
app.use(cors());
app.use(bodyParser.json());
app.use('/api/students', studentRoutes);
// MongoDB Connection
mongoose.connect('mongodb://127.0.0.1:27017/studentDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
2. Frontend (AngularJS):
a) public/index.html:
<!DOCTYPE html>
<html ng-app="studentApp">
<head>
<title>Student Management</title>
<link rel="stylesheet" href="css/style.css">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></
script>
<script src="app.js"></script>
<script src="controllers/studentController.js"></script>
<script src="services/studentService.js"></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="newStudent.name"
required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" ng-model="newStudent.email"
required><br><br>
<label for="major">Major:</label>
<input type="text" id="major" ng-model="newStudent.major"><br><br>
<label for="grade">Grade:</label>
<input type="number" id="grade" ng-model="newStudent.grade"><br><br>
<hr>
<div>
<h2>Student List</h2>
<ul ng-if="students.length > 0">
<li ng-repeat="student in students">
{{ student.name }} ({{ student.email }}) - Major: {{ student.major ||
'N/A' }}, Grade: {{ student.grade || 'N/A' }}
<button ng-click="editStudent(student._id)">Edit</button>
<button ng-click="deleteStudent(student._id)">Delete</button>
</li>
</ul>
<p ng-if="students.length === 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="editingStudent.name"
required><br><br>
<label for="editEmail">Email:</label>
<input type="email" id="editEmail" ng-model="editingStudent.email"
required><br><br>
<label for="editMajor">Major:</label>
<input type="text" id="editMajor" ng-
model="editingStudent.major"><br><br>
<label for="editGrade">Grade:</label>
<input type="number" id="editGrade" ng-
model="editingStudent.grade"><br><br>
b) public/app.js:
JavaScript
angular.module('studentApp', []);
c) public/controllers/studentController.js:
JavaScript
angular.module('studentApp')
.controller('StudentController', ['$scope', 'StudentService', function($scope,
StudentService) {
$scope.students = [];
$scope.newStudent = {};
$scope.editingStudent = null;
$scope.addError = null;
$scope.addSuccess = null;
$scope.fetchError = null;
$scope.updateError = null;
$scope.updateSuccess = null;
// Edit a student
$scope.editStudent = function(id) {
$scope.updateError = null;
$scope.updateSuccess = null;
StudentService.getStudent(id)
.then(function(response) {
$scope.editingStudent = angular.copy(response.data); // Create a copy
to avoid direct modification
})
.catch(function(error) {
console.error('Error fetching student for edit:', error);
$scope.updateError = 'Error fetching student details.';
});
};
// Update a student
$scope.updateStudent = function() {
$scope.updateError = null;
$scope.updateSuccess = null;
StudentService.updateStudent($scope.editingStudent._id,
$scope.editingStudent)
.then(function(response) {
const index = $scope.students.findIndex(student => student._id ===
response.data._id);
if (index !== -1) {
$scope.students[index] = response.data;
}
$scope.editingStudent = null; // Hide edit form
$scope.updateSuccess = 'Student updated successfully!';
})
.catch(function(error) {
$scope.updateError = 'Error updating student: ' + error.data.message
|| error.statusText;
});
};
// Cancel edit
$scope.cancelEdit = function() {
$scope.editingStudent = null;
};
// Delete a student
$scope.deleteStudent = function(id) {
if (confirm('Are you sure you want to delete this student?')) {
StudentService.deleteStudent(id)
.then(function(response) {
$scope.students = $scope.students.filter(student => student._id !==
id);
})
.catch(function(error) {
console.error('Error deleting student:', error);
});
}
};
}]);
d) public/services/studentService.js:
JavaScript
angular.module('studentApp')
.service('StudentService', ['$http', function($http) {
const baseUrl = '/api/students';
this.getStudents = function() {
return $http.get(baseUrl);
};
this.getStudent = function(id) {
return $http.get(baseUrl + '/' + id);
};
this.addStudent = function(studentData) {
return $http.post(baseUrl, studentData);
};
this.deleteStudent = function(id) {
return $http.delete(baseUrl + '/' + id);
};
}]);
e) public/css/style.css:
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;
}
Bash
npm install
npm start
This will start the Express.js backend server on port 3000. Make sure you have MongoDB
running on mongodb://127.0.0.1:27017.
2. Navigate to the student-management directory (the root of your project) and open the
public/index.html file in your web browser.
Src/App.js
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 :
14. Write a program to create a voting application using React JS
Src/App.js
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 :
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/App.js
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 :
16. Build a music store application using react components and provide routing
among the web pages.
Src/app.js
Src/About.js
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/NotFound.js
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/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;
}
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/
│ ├── 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';
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/ Footer.js
import React from 'react';
const Footer = () => (
<footer>
<p>© 2024 Online Store</p>
</footer>
);
export default Footer;
components/ Home.js
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/ Login.js
import React, { useState } from 'react';
const Login = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
alert(`Logged in with email: ${email}`);
};
return (
<main>
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<label>
Email:
<input type="email" value={email} onChange={(e) =>
setEmail(e.target.value)}
required />
</label>
<br />
<label>
Password:
<input type="password" value={password} onChange={(e) =>
setPassword(e.target.value)} required />
</label>
<br />
<button type="submit">Login</button>
</form>
</main>
);
};
export default Login;
components/ Register.js
import React, { useState } from 'react';
const Register = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
});
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
alert(`Registered: ${formData.name} (${formData.email})`);
};
return (
<main>
<h1>Register</h1>
<form onSubmit={handleSubmit}>
<label>
Name:
<input name="name" type="text" value={formData.name}
onChange={handleChange} required />
</label>
<br />
<label>
Email:
<input name="email" type="email" value={formData.email}
onChange={handleChange} required />
</label>
<br />
<label>
Password:
<input name="password" type="password" value={formData.password}
onChange={handleChange} required />
</label>
<br />
<button type="submit">Register</button>
</form>
</main>
);
};
export default Register;
components/ Product.js
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>
{products.map((product) => (
<li key={product.id}>
<h2>{product.name}</h2>
<p>{product.description}</p>
<p>Price: {product.price}</p>
</li>
))}
</ul>
</main>
);
};
export default Product
components/ NotFound.js
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;
App.js
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;
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: