8.
a
Course Name: [Link]
Module Name: CRUD Operations
AIM: Write a program to perform various CRUD (Create-Read-Update-
Delete) operations using Mongoose library functions.
Procedure Steps:
Step 1: Create a file [Link] in [Link] command prompt or VSCODE.
Step 2: Start the server using the following node command.
PS D:\Project> node [Link] press enter button then server starts.
Step 3: Open the postman and select the POST and enter the URL [Link]
Step 4: Open the Body, click on the none list box and select the raw and select JSON from
second list box.
Step 5: Type the following code and click on the Send button.
{
“name”: “atp”,
“email”: “tiru@[Link]”
}
Step 6: Click on the send button and click on the below Body then output will be displayed
in JSON format .
Step 7: Read the users data from the data base.
Open the browser, enter the [Link] then read the data from
data base and output displayed on browser.
Step 8: Retrieve the data by ID from the data base.
Open the browser, enter the [Link]
then read the data from data base and output displayed on browser.
Step 9: Update the data by ID into data base
Open the postman and select the PUT and enter the URL
[Link]
Type the following update code and click on the Send button then existing data is
update by new data and transfer updated to data base.
{
“name”: “cse”,
“email”: “atp@[Link]”
}
Step 10: Delete the data by ID from data base.
Open the postman and select the DELETE and enter the URL
[Link] and click on the Send
button then above ID document is delete from data base.
Step 11: Open the MongoDB database, and verify all CRUD Operations.
SOURCE CODE: [Link]
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const PORT = [Link] || 5000;
// Connect to MongoDB
[Link]('mongodb://localhost:27017/sacet', {
useNewUrlParser: true,
useUnifiedTopology: true,
//useFindAndModify: true // To avoid deprecation warning for
findOneAndUpdate()
})
.then(() => {
[Link]('Connected to MongoDB');
})
.catch((err) => {
[Link]('Error connecting to MongoDB:', err);
[Link](1); // Exit the application if unable to connect to MongoDB
});
// Middleware to parse JSON bodies
[Link]([Link]());
// Define User model
const User = [Link]('User', {
name: String,
email: String
});
// Create a new user
[Link]('/users', async (req, res) => {
try {
const { name, email } = [Link];
const newUser = new User({ name, email });
const savedUser = await [Link]();
[Link](savedUser);
} catch (error) {
[Link]('Error creating user:', error);
[Link](400).json({ error: 'Could not create user' });
}
});
// Get all users
[Link]('/users', async (req, res) => {
try {
const users = await [Link]();
[Link](users);
} catch (error) {
[Link]('Error fetching users:', error);
[Link](500).json({ error: 'Internal Server Error' });
}
});
// Get a user by ID
[Link]('/users/:id', async (req, res) => {
try {
const user = await [Link]([Link]);
if (!user) {
return [Link](404).json({ error: 'User not found' });
}
[Link](user);
} catch (error) {
[Link]('Error fetching user:', error);
[Link](500).json({ error: 'Internal Server Error' });
}
});
// Update a user by ID
[Link]('/users/:id', async (req, res) => {
try {
const { name, email } = [Link];
const updatedUser = await [Link]([Link], { name,
email }, { new: true });
if (!updatedUser) {
return [Link](404).json({ error: 'User not found' });
}
[Link](updatedUser);
} catch (error) {
[Link]('Error updating user:', error);
[Link](500).json({ error: 'Internal Server Error' });
}
});
// Delete a user by ID
[Link]('/users/:id', async (req, res) => {
try {
const deletedUser = await [Link]([Link]);
if (!deletedUser) {
return [Link](404).json({ error: 'User not found' });
}
[Link](deletedUser);
} catch (error) {
[Link]('Error deleting user:', error);
[Link](500).json({ error: 'Internal Server Error' });
}
});
// Start the server
[Link](PORT, () => {
[Link](`Server is running on port ${PORT}`);
});
8.a OUTPUT:
CRUD-Create or Insert Operation Output:
CRUD-Read Operation Output:
CRUD-Read Operation (Get a user by ID ) Output:
CRUD-Update Operation(Update a user by ID) Output :
CRUD-Delete Operation (Delete a user by ID) Output :
8.b
Course Name: [Link]
Module Name: API Development
AIM: In the myNotes application, include APIs based on the requirements provided.
(i) API should fetch the details of the notes based on a notesID which is provided in the
URL.
(ii) API should update the details based on the name which is provided in the URL and the data in
the request body.
iii). API should delete the details based on the name which is provided in the URL.
Description:
API is a set of rules and protocols that allow different software applications to
communicate with each other.
Making use of an API reduces the developer’s efforts as we need not code all the
features but instead consume from the existing services.
We can make use of the code from another application with the help of an API to
access the features provided.
Procedure Steps: 8.b.i (Read the data based on ID)
Step 1: Create a [Link] file in [Link] command prompt or VSCODE.
Step 2: Start the server using the following node command.
PS D:\Project> node [Link] press enter button then server starts.
Step 3: If we want to see output , open the postman tool and select the GET and enter the
URL [Link] and click on the Send button.
Step 4: Open the Body, then id1 output will be displayed.
SOURCE CODE: 8.b.i [Link]
const express = require('express');
const app1 = express();
// Sample notes data (replace this with your actual data source)
const notes = [
{ id: 1, title: 'Go A Head', content: 'Three individuals unrelated by blood
but become each others family' },
{ id: 2, title: 'The Crown', content: 'The crown focuses on the life Queen
Elizabeth' }
];
// API endpoint to fetch details of a note based on ID
[Link]('/api/notes/:id', (req, res) => {
const id = parseInt([Link]);
const note = [Link](note => [Link] === id);
if (note) {
[Link](note);
} else {
[Link](404).json({ error: 'Note not found' });
}
});
// Start the server
[Link](7000, () => {
[Link](`Server is running on [Link]
});
8.b. i) OUTPUT
8.b. ii &iii (Update & Delete the data based on Name)
Procedure Steps:
Step 1: Create a [Link] file in [Link] command prompt or VSCODE.
Step 2: Install body-parser using following command:
PS D:\Project> npm i body-parser
Step 3: Start the server using the following node command.
PS D:\Project> node [Link] press enter button then server starts.
Step 4: If we want to see all notes output , open the postman tool and select the GET and
enter the URL [Link] and click on the Send button.
Step 5: Open the Body, then all notes output will be displayed.
Step 6: API endpoint to delete a specific note by name, open the postman tool and select the
DELETE and enter the URL [Link] 1 and click on the
Send button. Then Note 1 is deleted.
Step 7: API endpoint to update details of a note based on name, open the postman tool and
select the GET and enter the URL [Link] and click on the Send
button. Then Note 2 content will be displayed.
SOURCE CODE: [Link] &iii [Link]
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// Sample notes data (replace this with your actual data source)
let notes = [
{ name: 'Note 1', content: 'This is the content of Note 1' },
{ name: 'Note 2', content: 'This is the content of Note 2' }
];
// Middleware to parse JSON bodies
[Link]([Link]());
// API endpoint to update details of a note based on name
[Link]('/api/notes/:name', (req, res) => {
const name = [Link](); // Trim the note name
const { content } = [Link];
// Trim note names for comparison
const noteIndex = [Link](note => [Link]() === name);
if (noteIndex !== -1) {
notes[noteIndex].content = content;
[Link]({ message: `Note '${name}' updated successfully` });
} else {
[Link](404).json({ error: `Note '${name}' not found` });
}
});
// API endpoint to get all notes
[Link]('/api/notes', (req, res) => {
[Link](notes);
});
// API endpoint to delete a specific note by name
[Link]('/api/notes/:name', (req, res) => {
const name = [Link](); // Trim the note name
// Remove the note with the specified name
const filteredNotes = [Link](note => [Link]() !== name);
if ([Link] < [Link]) {
notes = filteredNotes;
[Link]({ message: `Note '${name}' deleted successfully` });
} else {
[Link](404).json({ error: `Note '${name}' not found` });
}
});
const port = 5000; // Start the server
[Link](port, () => {
[Link](`Server is running on [Link]
});
8.b ii & iii (UPDATION & DELETION) OUTPUT:
8.c
Course Name: [Link]
Module Name: Why Session management, Cookies
AIM: Write a program to explain session management using cookies.
Procedure Steps:
Step 1: Create a file [Link] in [Link] command prompt or VSCODE.
Step 2: Install the cookie-parser using following command:
PS D:\Project> npm i cookie-parser
Step 3: Start the server using the following node command.
PS D:\Project> node [Link] press enter button then server starts.
Step 4: Open the browser and enter URL as [Link] then output displayed.
Step 5: Open the browser and enter URL as [Link] then Cookie is
set.
Step 6: Open the browser and enter URL as [Link] then Cookies
are retrieved..
SOURCE CODE: [Link]
var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
[Link](cookieParser());
[Link]('/cookieset',function(req, res){ // create or set cookies
[Link]('College', 'Stanns'); // cookie-name and value
[Link]('Dept', 'CSE');
//[Link]('cookie_name'); // remove cookie
[Link]('<h1><font color="red">Cookie is set</font></h1>');
});
[Link]('/cookieget', function(req, res) { // get cookies
[Link]([Link]);
});
[Link]('/', function (req, res) {
[Link]('<h1><font color="blue">Welcome to Cookies in Express </font></h1>');
});
// Start the server
[Link](5000, () => {
[Link](`Server is running on [Link]
});
2. API should update the deta
ils
on the name which is provide in the URL and the data in the request body.
Test URL - h
ttp:/
/localhost:3000/notes/Mathan
N
8.d
Course Name: [Link]
Module Name: Sessions
AIM: Write a program to explain session management using sessions.
Procedure Steps:
Step 1: Create a file [Link] in [Link] command prompt or VSCODE.
Step 2: Install the expression-session using following command:
PS D:\Project> npm i expression-session
Step 3: Start the server using the following node command.
PS D:\Project> node [Link] press enter button then server starts.
Step 4: Open the browser and enter URL as [Link] then Session is set.
Step 5: Open the browser and enter URL as [Link] then Session is
retrieved.
SOURCE CODE: [Link]
const express = require("express")
const session = require('express-session')
const app = express()
// Session Setup
[Link](session({
secret: 'Your_Secret_Key', // It holds the secret key for session
// Forces the session to be saved & back to the session store
resave: true,
// Forces a session that is "uninitialized" to be saved to the store
saveUninitialized: true
}))
[Link]("/", function(req, res){
[Link] = '<h1>Welcome to Sessions in Express<h1>'
[Link]("<h1>Session is Set</h1>")
})
[Link]("/session", function(req, res){
var name = [Link]
[Link](name)
//To destroy session you can use this function
[Link](function(error){
[Link]("Session Destroyed")
})
})
// Start the server
[Link](5000, () => {
[Link](`Server is running on [Link]
});
8.d OUTPUT:
8.e
Course Name: [Link]
Module Name: Why and What Security, Helmet Middleware
AIM: Implement security features in myNotes application
Description:
Express applications can be secured by using a middleware called a helmet. The helmet
middleware is a set of 14 small middleware functions that help in setting up security-
related HTTP headers with default values and also remove unnecessary headers which
expose the application-related information. To install helmet in any Express application,
use node package manager and run the following command, npm install helmet
Procedure Steps:
1. Create a file [Link] in [Link] command prompt or VSCODE before adding helmet
middleware.
2: Install the helmet using following command:
PS D:\Project> npm i helmet
3 Create a file [Link] file content
4. Create a file [Link] to demonstrate a clickjacking attack. Clickjacking is a malicious
technique of tricking the user thereby rendering a page inside an iframe.
4. Open a command prompt and start the server using following command:
D:/Project> node [Link] press enter button then server starts.
5. Open the [Link] file in the browser. Thus, the page gets loaded in the iframe and display
output. D:/Project/[Link] and press the Enter button.
6. Modify the [Link] file by adding the helmet configuration as shown below.
7. Again starts the server using following command:
D:/Project> node [Link]
8. Now open the page [Link] and observe the output. The page fails to load in the iframe
due to the headers set by helmet middleware.
9. Now access the developer tools in the browser (F12) and click on the "Network" tab and
observe the headers set as part of the response from the server. The helmet then sets an
'X-Frame-Options' header to value "SAMEORIGIN', which instructs the browser to not
allow framing from other domains.
SOURCE CODE: [Link]
const express = require('express');
const routing = require('./route1');
const app = express();
[Link]('/', routing);
[Link](3000);
[Link]('Server listening in port 3000');
[Link]
const express = require('express');
const router = [Link]();
[Link]('/', function (req, res) {
[Link]('<h1>Express Helmet Middleware</h1>');
});
[Link] = router;
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
p{
color: red;
}
iframe {
width: 80%;
height: 90%
}
</style>
</head>
<body>
<h1><p>Clickjacked</p></h1>
<iframe src="[Link]
</body>
</html>
Output:
Modify the [Link] file by adding the helmet configuration as shown below.
const express = require('express');
const helmet = require('helmet');
const routing = require('./route1');
const app = express();
[Link](helmet());
[Link]('/', routing);
[Link](3000);
[Link]('Server listening in port 3000');
Modified Output: