6th Sem
6th Sem
Course objectives:
● To understand the essential JavaScript concepts for web development.
● To style Web applications using bootstrap.
● To utilize React JS to build front end User Interface.
● To understand the usage of API’s to create web applications using Express JS.
● To store and model data in a no sql database.
Module-1
Text Book 1: Chapter 2
o Basic JavaScript Instructions,
o Statements,
o Comments,
o Variables,
o Data Types,
o Arrays,
o Strings,
Text Book 1: Chapter 3
o Functions, Methods & Objects,
Text Book 1: Chapter 4
o Decisions & Loops.
Module-3
Text Book 2: Chapter 1
Introduction to MERN:
o MERN components,
Text Book 2: Chapter 2
o Server less Hello world.
Text Book 2: Chapter 3
o React Components:
o Issue Tracker, React Classes,
o Composing Components,
o Passing Data Using Properties,
o Passing Data Using Children,
o Dynamic Composition.
Module-4
3. Create an object student with properties: name (string), grade (number), subjects (array), displayInfo()
(method to log the student's details)
Write a script to dynamically add a passed property to the student object, with a value of true or false based
on their grade. Create a loop to log all keys and values of the student object.
6. Create a component Counter with A state variable count initialized to 0. Create Buttons to increment and
decrement the count. Simulate fetching initial data for the Counter component using useEffect (functional
component) or componentDidMount (class component). Extend the Counter component to Double the
count value when a button is clicked. Reset the count to 0 using another button.
7. Install Express (npm install express).
Set up a basic server that responds with "Hello, Express!" at the root endpoint (GET /).
Create a REST API. Implement endpoints for a Product resource: GET : Returns a list of products. POST :
Adds a new product. GET /:id: Returns details of a specific product. PUT /:id: Updates an existing product.
DELETE /:id: Deletes a product. Add middleware to log requests to the console. Use express.json() to
parse incoming JSON payloads.
8. Install the MongoDB driver for Node.js. Create a Node.js script to connect to the shop database.
Implement insert, find, update, and delete operations using the Node.js MongoDB driver. Define a product
schema using Mongoose. Insert data into the products collection using Mongoose. Create an Express API
with a /products endpoint to fetch all products. Use fetch in React to call the /products endpoint and
display the list of products. Add a POST /products endpoint in Express to insert a new product. Update the
Product List, After adding a product, update the list of products displayed in React.
Semester-End Examination:
Theory SEE will be conducted by University as per the scheduled timetable, with common question papers for the
course (duration 03 hours).
1. The question paper will have ten questions. Each question is set for 20 marks.
2. There will be 2 questions from each module. Each of the two questions under a module (with a maximum of 3
sub-questions), should have a mix of topics under that module.
3. The students have to answer 5 full questions, selecting one full question from each module.
4. Marks scored shall be proportionally reduced to 50 marks
Full-stack development with Node.js (backend) and MongoDB (database) involves building web
applications that cover both frontend (client-side) and backend (server-side) development. Below is a
point-by-point explanation:
Experiments
Experiment 1:
1. a. Write a script that Logs "Hello, World!" to the console. Create a script that calculates the sum of
two numbers and displays the result in an alert box.
Log the total number of cities. Add a new city at the end. Remove the first city. Find and log the
index of a specific city.
1. Install Node.js:
o Download: Go to the Node.js official website and download the latest version
suitable for Windows.
o Install: Run the downloaded installer and follow the on-screen instructions to install
Node.js. This will also install npm (Node Package Manager), which is useful for
managing JavaScript packages.
2. Set Up Your
Environment:
o
Text Editor: Use a text editor like Visual Studio Code or any other text editor of your
choice.
o
Command Line:Use the Command Prompt or PowerShell to run your JavaScript files.
3. Running the Script:
o Save Your Script: Save the above JavaScript code in a file with a .js extension, e.g.,
script.js.
o Execute the Script:
By following these steps, you can run and test the JavaScript programs on your Windows
desktop.
Experiment1a.js
o Script to log "Hello, World!" to the console
console.log("Hello, World!");
o Script to calculate the sum of two numbers and display the result in an alert box
function calculateSum(a, b)
return sum = a + b;
}
Experiment usage
o/p:
just click on index.html icon to see the result.
Program:
<!DOCTYPE html>
<head>
<title>Dynamic Input Experiment</title>
<script>
// Script to log "Hello, World!" to the console
console.log("Hello, World!");
// Script to calculate the sum of two numbers and display the result
in an alert box
// Read numbers from user input
let num1 = parseFloat(prompt("Enter the first number:"));
let num2 = parseFloat(prompt("Enter the second number:"));
// Validate input
let sum = num1 + num2;
alert("The sum is: " + sum);
// Experiment usage
</script>
</head>
</html>
● 1bb.html
● Program:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Dynamic Cities Array</title>
</head>
<body>
● Execution
First install node js
● Next run
npm install prompt-sync
node 1b.js
Read a string from the user, Find its length. Extract the word "JavaScript" using substring() or
slice(). Replace one word with another word and log the new string. Write a function
isPalindrome(str) that checks if a given string is a palindrome (reads the same backward).
Program:
<!DOCTYPE html>
<head>
<title>String Manipulation</title>
<script>
// Function to check if a string is a palindrome
function isPalindrome1(str) {
for (let i = 0; i < str.length / 2; i++)
{
if (str.charAt(i) != str.charAt(str.length - 1 - i))
{
return false;
}
}
return true;
}
function isPalindrome(str)
{
let cleanedStr = str.replace(/[^A-Za-z0-9]/g,
'').toLowerCase();
return cleanedStr ===
cleanedStr.split('').reverse().join('');
}
// Display alerts
alert(`Length: ${lengthOfString}\nExtracted Word: ${extractedWord}\nNew
String: ${newString}\nPalindrome: ${palindromeCheck}`);
</script>
</head>
</html>
o/p:
Give the input string as-------------I love JavaScript, it is awesome!
Create an object student with properties: name (string), grade (number), subjects (array),
displayInfo() (method to log the student's details) Write a script to dynamically add a passed
property to the student object, with a value of true or false based on their grade. Create a loop
to log all keys and values of the student object.
One student
<!DOCTYPE html>
<head>
<title>Dynamic Student Object</title>
<script>
// Function to create a student object
function createStudent()
{
// Collect inputs for the student object
let student =
{
name: prompt("Enter the student's name:"),
grade: parseInt(prompt("Enter the student's grade:")),
subjects: prompt("Enter the student's subjects
separated by commas:").split(',').map(subject => subject.trim()),
};
return student;
}
Many students:
<!DOCTYPE html>
<head>
<title>Dynamic Student Object</title>
<script>
// Function to create a student object
function createStudent()
{
// Collect dynamic inputs for the student object
let student =
{
name: prompt("Enter the student's name:"),
grade: parseFloat(prompt("Enter the student's grade:")),
subjects: prompt("Enter the student's subjects separated by
commas:").split(',').map(subject => subject.trim()),
// Loop through the properties of the student object and log the
keys and values
for (let key in student)
{
if (typeof student[key] !== 'function')
{
</script>
</head>
</html>
<!DOCTYPE html>
<head>
<script>
// Event listener for the button click
document.getElementById('clickButton').addEventListener('click'
, function()
{
console.log("Button clicked!");
});
</script>
</body>
</html>
o/p:
1. mkdir exp6
2. cd exp6
3. npm create vite@latest 5
4. cd 5
5. npm install
Dept of ISE, HKBKCE
6. under src folder create Issuelist.jsx file
IssueList.jsx
const issues = [
{ id: 1, title: 'Bug in Login', description: 'Error 404 on login',
status: 'Open' },
{ id: 2, title: 'UI Issue on Dashboard', description: 'Misaligned
elements', status: 'Closed' },
{ id: 3, title: 'API Timeout', description: 'Delayed response from
server', status: 'Open' },
];
function IssueList() {
return (
<div>
<h1>Issue Tracker</h1>
<ul> {/* Wrap list items inside an unordered list */}
{issues.map(issue => (
<li key={issue.id}> {/* Correctly assign 'key' inside <li> */}
<h2>{issue.title}</h2> {/* Use curly braces to display the
title */}
<p>{issue.description}</p> {/* Use curly braces to display
the description */}
<p>Status: {issue.status}</p> {/* Use curly braces to display
the status */}
</li>
))}
</ul>
</div>
);
}
export default IssueList;
App.jsx
function App() {
return (
<div>
<IssueList />
</div>
);
Dept of ISE, HKBKCE
}
export default App;
Or
VITE v6.0.11 ready in 1957 ms
➜ Local: http://localhost:5173/
function App() {
return (
<div className="App">
<h1>Welcome to Counter App</h1>
<Counter />
</div>
);
}
export default App;
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => setCount(count +
1)}>Increment</button>
<button onClick={() => setCount(count -
1)}>Decrement</button>
<button onClick={() => setCount(count * 2)}>Double</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
};
Options to Select:
TypeScript? No
ESLint? Yes
Tailwind CSS? No
Code inside `src/`? Yes
App Router? Yes
Turbopack for `next dev`? Yes
Import alias customization? No
Procedure
1. put Counter.jsx code In the folder like by creating Counter.js in src/app/Counter.js. and also
add 'use client'; as first line in this file.
2. Moify the page.js content with src/App.Jsx by removing importing of App.jsx
3. create a folder like mkdir 6
4. cd 6
5. npm create vite@latest count
6. npm install
7. under src folder
8. App.jsx
function App() {
return (
<div>
)
}
return (
<div><h1>number</h1>
<h1>{number}</h1>
<br></br>
<button onClick={incrememt}>increment</button>
<button onClick={decrememt}>decrement</button>
<button onClick={double}>double</button>
<button onClick={reset}>reset</button>
</div>
)
}
increment = () => {
const value = this.state.number + 1;
this.setState({ number: value });
};
decrement = () => {
if (this.state.number > 0) { }
const value = this.state.number - 1;
this.setState({ number: value });
};
reset = () => {
this.setState({ number: 0 });
};
double = () => {
const value = this.state.number * 2;
this.setState({ number: value });
};
render() {
return (
<div>
<h1>Number</h1>
<h1>{this.state.number}</h1>
<br />
<button onClick={this.increment}>Increment</button>
<button onClick={this.decrement}>Decrement</button>
<button onClick={this.double}>Double</button>
<button onClick={this.reset}>Reset</button>
</div>
);
}
}
Install Express (npm install express). Set up a basic server that responds with "Hello,
Express!" at the root endpoint (GET /). Create a REST API. Implement endpoints for a
Product resource: GET : Returns a list of products. POST : Adds a new product. GET /:id:
Returns details of a specific product. PUT /:id: Updates an existing product. DELETE /:id:
Deletes a product. Add middleware to log requests to the console. Use express.json() to
parse incoming JSON payloads.
Step-by-Step Process:
server.js
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Under package.json ensure all the following things are there or not
{
"name": "expressjs",
"version": "1.0.0",
"description": "",
"license": "ISC",
"author": "",
"type": "module",
o/p:
npm run server
Install Postman
1. Visit the Postman website and download the application for your operating system
(Windows, Mac, or Linux).
Next click on new there select http after selecting http here you can see the all apis like get, get/id,
put/id, post, delete/id…etc
Get: http://localhost:3000/products
Post: http://localhost:3000/addproducts
Put/id: http://localhost:3000/updateproducts/2
Get/id: http://localhost:3000/products/2
Delete: http://localhost:3000/deleteproducts/1
{
"id": 1,
"name": "Laptop"
}
Install the MongoDB driver for Node.js. Create a Node.js script to connect to the shop
database. Implement insert, find, update, and delete operations using the Node.js MongoDB
driver. Define a product schema using Mongoose. Insert data into the products collection
using Mongoose. Create an Express API with a /products endpoint to fetch all products. Use
fetch in React to call the /products endpoint and display the list of products. Add a POST
/products endpoint in Express to insert a new product. Update the Product List, After adding
a product, update the list of products displayed in React.
3. Edit package.json
add “type”: “module”
products.js
// API Endpoints
// Get all the products
router.get('/', async (req, res) => {
try {
const products = await Product.find();
res.json(products);
} catch (error) {
res.status(500).send(error.message);
// Update a product
router.put('/:id', async (req, res) => {
try {
const updatedProduct = await
Product.findByIdAndUpdate(req.params.id, req.body, {
new: true,
});
res.json(updatedProduct);
} catch (error) {
res.status(500).send(error.message);
}
});
// Delete a product
router.delete('/:id', async (req, res) => {
try {
await Product.findByIdAndDelete(req.params.id);
res.status(204).send();
} catch (error) {
res.status(500).send(error.message);
}
});
// MongoDB connection
mongoose.connect(DB_URL);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'Connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
});
server.js
// MongoDB connection
mongoose.connect(DB_URL);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'Connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
});
2. Run
npm create vite@latest client --- --template react
ProductList.jsx
return (
<>
<h2>Add New Product</h2>
<div>
<input
type="text"
placeholder="Name"
value={newProduct.name}
onChange={(e) =>
setNewProduct({
...newProduct,
name: e.target.value
})
}
Dept of ISE, HKBKCE
/>
<input
type="text"
placeholder="Description"
value={newProduct.description}
onChange={(e) =>
setNewProduct({
...newProduct,
description: e.target.value
})
}
/>
<input
type="number"
placeholder="Price"
value={newProduct.price}
onChange={(e) =>
setNewProduct({
...newProduct,
price: e.target.value
})
}
/>
<button onClick={handleAddProduct}>Add Product</button>
</div>
</>
);
};
// Fetch products
useEffect(() => {
fetchProducts();
}, []);
return (
<div style={{ padding: "20px" }}>
<ProductList products={products} />
<AddProduct fetchProducts={fetchProducts} />
</div>
);
};
thead {
Outcome
1. The React app displays a list of products fetched from the /products endpoint.
If your Node.js API is running, you can fetch the products using your GET endpoint:
browser. http://localhost:5000/products
2. Adding a new product updates the list dynamically without refreshing the
o Run mongosh (for modern versions) or mongo (for older versions) in your terminal.
Collection: db.products.find().pretty()
o Download and install MongoDB Compass if you don’t already have it.
o Click on the products collection, and all the documents (data) will be displayed in a
tabular format.