MERN Lab-Manual (6)
MERN Lab-Manual (6)
S J C Institute of Technology
(VTU affiliated, AICTE approved, and NBA and NAAC Accredited)
MERN (BDSL456C)
Prepared by
Mr. Yashwantha N
Assistant Professor
Department of Artificial Intelligence and Data Science
SJCIT
2023-2024
MERN
4th Sem
1. Create a simple resume using HTML that includes sections for
personal information, education, work experience, and skills. Ensure
that each section is clearly labelled and styled appropriately.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Resume of Jane Doe</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f9f9f9;
}
.container {
max-width: 800px;
margin: auto;
background: white;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1, h2 {
text-align: center;
}
.section {
margin-bottom: 20px;
}
.section h2 {
border-bottom: 2px solid #ddd;
padding-bottom: 5px;
}
.section ul {
list-style-type: none;
padding: 0;
}
.section ul li {
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="container">
<h1>Yashwanth N</h1>
<p>Email: [email protected] | Phone: +91-7795373834 | LinkedIn:
https://www.linkedin.com/in/yashwantha-nagaraj-6400a0141/</p>
<div class="section">
<h2>Objective</h2>
<p>Motivated and enthusiastic computer science graduate seeking an entry-level software
development position to leverage my skills in coding, problem-solving, and teamwork to contribute to the
growth and success of a dynamic organization.</p>
</div>
<div class="section">
<h2>Education</h2>
<ul>
<li><strong>Bachelor of Engineering in Computer Science and Engineering</strong><br>SJB
Institute of Technology, Bengaluru</li>
<li><strong>Master of Technology in Computer Science and Engineering</strong><br>RNS
Institute of Technology, Bengaluru</li>
</ul>
</div>
<div class="section">
<h2>Projects</h2>
<ul>
<li><strong>Portfolio Website</strong><br>Developed a personal portfolio website using
HTML, CSS, and JavaScript to showcase projects and skills.</li>
<li><strong>Library Management System</strong><br>Created a library management system
using Python and MySQL to manage book inventories and user transactions.</li>
<li><strong>Weather App</strong><br>Built a weather application using React and
OpenWeatherMap API to display current weather conditions based on user location.</li>
</ul>
</div>
<div class="section">
<h2>Skills</h2>
<ul>
<li>Proficient in HTML, CSS, JavaScript</li>
<li>Experience with Python and Java</li>
<li>Knowledge of React.js and Node.js</li>
<li>Strong problem-solving and analytical skills</li>
<li>Excellent communication and teamwork abilities</li>
</ul>
</div>
<div class="section">
<h2>Certifications</h2>
<ul>
<li>Certified Java Developer - Oracle</li>
<li>Front-End Web Developer Nanodegree - Udacity</li>
</ul>
<ul>
<li>Certified Full Stack Developer - Oracle</li>
<li>Web Developer Nanodegree - Udemy</li>
</ul>
</div>
<div class="section">
<h2>Extracurricular Activities</h2>
<ul>
<li>Member of the Computer Science Club at VTU</li>
<li>Volunteer at local coding bootcamps for underprivileged youth</li>
<li>Participant in hackathons and coding competitions</li>
</ul>
</div>
</div>
</body>
</html>
Output:
MoviesDB> db.createCollection("Movies")
MoviesDB>db.Movies.insertMany([
{ title: "Inception", director: "Christopher Nolan", genre: "Science Fiction", year: 2010, ratings: { imdb:
8.8, rottenTomatoes: 87 } },
{ title: "The Matrix", director: "Wachowskis", genre: "Science Fiction", year: 1999, ratings: { imdb: 8.7,
rottenTomatoes: 87 } },
{ title: "The Godfather", director: "Francis Ford Coppola", genre: "Crime", year: 1972, ratings: { imdb: 9.2,
rottenTomatoes: 97 } },
{ title: "Pulp Fiction", director: "Quentin Tarantino", genre: "Crime", year: 1994, ratings: { imdb: 8.9,
rottenTomatoes: 92 } },
{ title: "The Shawshank Redemption", director: "Frank Darabont", genre: "Drama", year: 1994, ratings: {
imdb: 9.3, rottenTomatoes: 91 } },
{ title: "The Dark Knight", director: "Christopher Nolan", genre: "Action", year: 2008, ratings: { imdb: 9.0,
rottenTomatoes: 94 } },
{ title: "Fight Club", director: "David Fincher", genre: "Drama", year: 1999, ratings: { imdb: 8.8,
rottenTomatoes: 79 } }
]);
Step 2: Queries
a. Find any record where Name is Somu
mkdir file-system-crud
cd file-system-crud
npm init -y
2. Create index.js
3. Implement CRUD Operations
const fs = require('fs');
const path = require('path');
// Create a file
function createFile(filePath, content) {
fs.writeFile(filePath, content, (err) => {
if (err) {
console.error(`Error creating file: ${err}`);
} else {
console.log(`File created successfully at ${filePath}`);
}
});
}
// Read a file
function readFile(filePath) {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error(`Error reading file: ${err}`);
} else {
console.log(`File content: ${data}`);
}
});
}
// Update a file
function updateFile(filePath, newContent) {
fs.appendFile(filePath, newContent, (err) => {
if (err) {
console.error(`Error updating file: ${err}`);
} else {
console.log(`File updated successfully at ${filePath}`);
}
});
}
// Delete a file
function deleteFile(filePath) {
fs.unlink(filePath, (err) => {
if (err) {
console.error(`Error deleting file: ${err}`);
} else {
console.log(`File deleted successfully at ${filePath}`);
}
});
}
// Example usage
const filePath = path.join(__dirname, 'example.txt');
// Create a file
createFile(filePath, 'Hello, World!');
1. Create a file: The createFile function uses fs.writeFile to create a new file or overwrite
an existing file with the specified content.
2. Read a file: The readFile function uses fs.readFile to read the content of a file and log it
to the console.
3. Update a file: The updateFile function uses fs.appendFile to append new content to an
existing file.
4. Delete a file: The deleteFile function uses fs.unlink to delete a specified file.
Note
• Error Handling: Each function includes basic error handling that logs errors to the
console. In a real-world application, you might want to handle these errors more
gracefully.
• Delays: The setTimeout function is used to introduce delays between operations to
ensure that each operation has time to complete before the next one starts. This is for
demonstration purposes. In a production scenario, you would handle this more
robustly, possibly with promises or async/await syntax.
Step-by-Step Implementation:
Step 1: Initialize Node.js Project
mkdir student-mongo
cd student-mongo
npm init -y
npm install mongoose
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/studentDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log('Connected to MongoDB');
}).catch((err) => {
console.error('Error connecting to MongoDB:', err);
});
// Example usage
addStudent('1MS17CS101', 'John Doe', 6, 2017).then(() => {
mongoose.connection.close();
});
This script connects to MongoDB, defines a student schema, and adds a student record.
Step-by-Step Implementation:
Step 1: Update student.js to include the search functionality
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/studentDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log('Connected to MongoDB');
}).catch((err) => {
console.error('Error connecting to MongoDB:', err);
});
mongoose.connection.close();
})();
Step 2: Run the Script
node student.js
Explanation:
6. Develop the application that sends fruit name and price data from client
side to Node.js server using Ajax
First, ensure you have Node.js and npm installed. Then, create a new directory for your
project and initialize it with npm:
mkdir fruit-app
cd fruit-app
npm init -y
Next, install Express.js:
npm install express
Create a new file called server.js and add the following code:
const express = require('express');
const app = express();
const port = 3000;
Create a directory named public in the root of your project. Inside the public directory, create
an index.html file and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fruit App</title>
</head>
<body>
<h1>Fruit App</h1>
<form id="fruitForm">
<label for="name">Fruit Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="price">Price:</label>
<input type="number" id="price" name="price" required><br><br>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById('fruitForm').addEventListener('submit', function(event) {
event.preventDefault();
const data = {
name: name,
price: price
};
fetch('/add-fruit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
alert('Fruit data sent successfully');
})
.catch((error) => {
console.error('Error:', error);
});
});
</script>
</body>
</html>
Start your Express.js server by running the following command in your project directory:
node server.js
You should see a message in the console indicating that the server is running:
Server running at http://localhost:3000
Open a web browser and navigate to http://localhost:3000. You should see a simple form to enter
fruit name and price. Fill in the form and click the "Submit" button. The form data will be
sent to the server using an Ajax request, and you should see a confirmation message in the
browser and the server console log the received data.
If you haven't already set up a React application, you can do so using Create React App:
Create a new file called SearchFilter.js inside the src folder and add the following code:
item.toLowerCase().includes(searchQuery.toLowerCase())
);
return (
<div>
<h1>Search Filter</h1>
<input
type="text"
placeholder="Search..."
value={searchQuery}
onChange={handleSearchChange}
/>
<ul>
{filteredItems.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
};
function App() {
return (
<div className="App">
<header className="App-header">
<SearchFilter />
</header>
</div>
);
}
Explanation
1. State Management: We use the useState hook to manage the state for the search
query.
2. Search Input: An input field allows the user to enter a search query. The
handleSearchChange function updates the state whenever the input changes.
3. Filtering Logic: The filteredItems array is derived by filtering the items array. The filter
method checks if each item's name includes the search query (case-insensitive).
4. Rendering the List: The filtered items are displayed in an unordered list.
After setting up the above code, your React application should be running. Open your web
browser and navigate to http://localhost:3000. You should see a search input field and a list of
items. As you type into the search field, the list should dynamically filter to show only the
items that match the search query.
function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i < Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}
});
Explanation:
This code defines two routes that handle GET requests and respond with JSON data
containing the prime numbers and cubes less than 100. You can access these routes by
sending GET requests to http://localhost:3000/find_prime_100 and http://localhost:3000/find_cube_100
in your browser or using tools like Postman.
Run
1. npm install express
2. node filename.js
First, create a new directory for your project and initialize it with npm:
mkdir auth-app
cd auth-app
npm init -y
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
Create a file named index.html in the same directory with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Authentication Form</title>
</head>
<body>
<h2>Register</h2>
<form id="registerForm">
<label for="registerEmail">Email:</label>
<input type="email" id="registerEmail" name="email_id" required>
<label for="registerPassword">Password:</label>
<input type="password" id="registerPassword" name="password" required>
<button type="submit">Register</button>
</form>
<h2>Login</h2>
<form id="loginForm">
<label for="loginEmail">Email:</label>
<input type="email" id="loginEmail" name="email_id" required>
<label for="loginPassword">Password:</label>
<input type="password" id="loginPassword" name="password" required>
<button type="submit">Login</button>
</form>
<script>
document.getElementById('registerForm').addEventListener('submit', async function(event) {
event.preventDefault();
const email_id = document.getElementById('registerEmail').value;
const password = document.getElementById('registerPassword').value;
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email_id, password })
});
Start your Express server by running the following command in your terminal:
node server.js
Open your browser and navigate to http://localhost:3000. You should see the
registration and login forms. You can now register a new user and log in with
the credentials you provided.