0% found this document useful (0 votes)
39 views

Exercise-4 Msd Lab Programs (1)

The document outlines exercises for implementing middleware in an Express.js application and connecting to MongoDB using Mongoose. It details the steps to create middleware for handling POST submissions, logging, and error handling, as well as instructions for setting up a Mongoose schema to interact with a MongoDB database. Additionally, it provides source code examples and installation procedures for required tools and libraries.

Uploaded by

hariniivalluri
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)
39 views

Exercise-4 Msd Lab Programs (1)

The document outlines exercises for implementing middleware in an Express.js application and connecting to MongoDB using Mongoose. It details the steps to create middleware for handling POST submissions, logging, and error handling, as well as instructions for setting up a Mongoose schema to interact with a MongoDB database. Additionally, it provides source code examples and installation procedures for required tools and libraries.

Uploaded by

hariniivalluri
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
You are on page 1/ 13

MEAN STACK DEVELOPMENT LAB

Exercise -4 (Express.js-Middleware, MongoDB)


a). Implement Middleware for myNotes application:
(i) we want to handle POST submissions.
(ii) display customized error messages. (iii) perform logging.
b). Write a Express.js program to write a Mongoose schema to connect with MongoDB

Exercise -4(a) : Express.js - Middleware


AIM:
Implement Middleware for myNotes application:
(i) we want to handle POST submissions.
(ii) display customized error messages. (iii) perform logging.

Description:
Express is a routing and Middleware framework for handling the different routing of the
webpage and it works between the request and response cycle. Middleware in Express.js is a
function that is executed between the incoming request and the outgoing response. The main
arguments of a middleware function are the request object, response object, and also
the next middleware function defined in the application.

Any middleware can be loaded in an Express application using the app.use() method.
The app.use() method accepts one string parameter path, which is optional, and one function
parameter callback which is the mandatory middleware function.
app.use(PATH, CALLBACK)

PROCEDURE STEPS:
Step 1: Create a midelware.js file in VSCODE.
Step 2: Creating a package.json file using following command:
PS D:\MSD LAB\ Exercise-4 >npm init
Is this OK? (yes) yes
Step 3: Install Express.js using following command:
PS D:\Project> npm i express -g
Step 4: To use middleware in the Express application, we need to install it.
PS D:\MSD LAB\ Exercise-4 >npm install morgan
Step5: Install path using following command:
//This is an exact copy of the NodeJS ’path’ module published to the NPM registry.
PS D:\MSD LAB\ Exercise-4 >npm i path
Step 6: Install morgan-body using following command:
PS D:\MSD LAB\ Exercise-4 >npm i morgan-body
Step 7: Start the server using the following node command.
PS D:\MSD LAB\ Exercise-4 >node midelware.js press enter button then server starts.
Step 8: Open the browser and enter URL as http://localhost:5000 then output will be
displayed on the webpage.

SOURCE CODE: midelware.js


var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var morgan = require('morgan');
const morganBody= require( 'morgan-body');
//Simple app that will log all requests in the Apache combined format to the file access.log.
var LogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' });
app.use(morgan('combined', { stream: LogStream }));
morganBody(app, {
noColors: true,
stream: LogStream,
});
app.use((req, res,next)=> {
if(10<20) {
next();
}
});
//Handle Get Submission in Express.js
app.get('/getRequest', (req, res)=> {
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Express.js </title>
</head>
<body style="background-color:#F0E68C;">
<br><br><br><center><h1><font color="red" size="25">Hello World! Welcome To
CSE!</font></h1>
<h1><font color="red" size="25"> Develop Middleware in Express.js</font></h1>
<h1><font color="blue" size="24"> Handle Get Submission in
Express.js-Middleware</font></h1>
</center></body>
</html>
`);
next();
});
//Handle Post Submission in Express.js
app.post('/postRequest', (req, res)=> {
res.send("Handle Post Submission in Express.js-Middleware")
next();
});
app.use(function(err, req, res, next) {
// Do logging and user-friendly error message display
console.error(err);
res.send({status:500, message: 'internal error', type:'internal'});
})
app.listen(5000, () => {
console.log(`Server is running on http://localhost:5000`);
});

OUTPUT: 4(a)

• Morgan middleware also supports writing logs to a file (access.log)


postRequest output 1:

 Now, if you want to see the postRequest output, Open the postman tool and select the
post method and enter the URL http://localhost:5000/postRequest and click on the send
button.
 Then, select the Body and click on preview then output will be displayed.

To install Postman S/W(Testing tool) on Windows, we have to use following steps:


1. Visit the https://www.postman.com/ website using any web browser.
2. Click on windows icon as shown in below webpage

:
3. Click on Windows 64 – bit button then downloaded as shown in below webpage.

4. Select the executable file in downloads in your system and right click on it and click on Run
as administrator then postman s/w is installed in your PC and postman icon placed on
desktop.

postRequest output 2:
Exercise-4(b): Express.js -Mongoose, MongoDB
AIM: Write a Express.js program to write a Mongoose schema to connect with MongoDB

Description:
 Mongo DB is a document-oriented database. It is an open source product, developed and
supported by a company named 10gen. MongoDB is a document database. It stores data
in a type of JSON format called BSON.
 MongoDB is a scalable, open source, high performance, document-oriented database.
 MongoDB is the most popular NoSQL database. The term ‘NoSQL’ means ‘non-
relational’. It means that MongoDB isn’t based on the table-like relational database
structure but provides an altogether different mechanism for storage and retrieval of data.
This format of storage is called BSON ( similar to JSON format).
 Mongoose is an Object Data Modeling (ODM) tool, which is created to work on an
asynchronous MongoDB environment. It imposes the structure and constraints by
mapping JavaScript objects to documents in the database.
 It also provides the functionality for validating field values and methods for selecting,
adding, modifying, and deleting documents in the collection.

DOWNLOAD AND INSTALL MONGODB COMPASS DATABASE ON WINDOWS:

Step1: Enter https://www.mongodb.com/try/download/community in address bar and press


enter button.
Step 2: Click on the MongoDB Community Edition.
 After clicking on the Community Server Edition, scroll down the web page and you can
able to see the page as below: select version 5.0.25, Windows 64 and click on Download.

Step 3: Select mongoDB software and right click on it and click on Install.
 Once download is complete open the msi file. Click Next in the start up screen.
Step 4: Accept the End-User License Agreement and click on the next button.

Step 5: Click on the “complete” button to install all of the components.


Step 6: Service Configuration
 Select “Run service as Network Service user” and Click Next button.

Step 7: Select the MongoDB compas and Click on the Install button to start the installation.

Step 8: Click Next once completed.


Step 9: Once complete the installation, Click on the Finish button

Step 10; Set the path for MongoDB in Winwods mode


 Select Edit the system environment variables from search box and click on
Environment variables.

 Select the Path from System variables and click on Edit button

 Select New and paste the mongoDB URL C:\Program Files\MongoDB\Server\7.0\bin


and click on ok button.
 Click on ok button. Again click on ok.

PROCEDURE STEPS:
Step1: Installing two packages express and mongoose for mongodb database:
 For installing the Mongoose library, issue the below command in the Node command
prompt.
PS D:\MSD LAB\ Exercise-4 > npm i express mongoose
Step2:Connecting to MongoDB using Mongoose(open mongoDB database):
 To establish a connection to the MongoDB database, create a connection object using
Mongoose. This is done through the below code:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/Database_Name');
Step3: Create a notes.js file in VSCODE or Node.js command prompt .
Step4: Start the server using the following node command.
PS D:\MSD LAB\ Exercise-4 > node notes.js press enter button then server starts.
Step 5: Open the postman and select the POST from the list box and enter the URL
http://localhost:5000/users
Step 6: Open the Body, click on the none list box and select the raw and select JSON from
second list box.
Step 7: Type the following code
{
“name”: “Karth”,
“email”: “[email protected]
}
Step 8: Click on the send button and click on Preview then output will be displayed
in JSON format.
Step 9: Now, open the MongoDB database, see your database, collection and document.
(The output data is transferred from server to client and also to MongoDB database).

SOURCE CODE: notes.js


const express = require('express');
const mongoose = require('mongoose');
const app = express();
// Define Mongoose schema
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
}
});

// Create Mongoose model


const User = mongoose.model('User', userSchema);

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/Meanstack', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log('Connected to MongoDB');
})
.catch((err) => {
console.error('Error connecting to MongoDB:', err);
process.exit(1); // Exit the application if unable to connect to MongoDB
});

// Middleware to parse JSON bodies


app.use(express.json());

// Define route to create a new user


app.post('/users', async (req, res) => {
try {
// Check if the name and email fields are present in the request body
if (!req.body.name || !req.body.email) {
// If either field is missing, return a 400 Bad Request response with an error message
return res.status(400).json({ error: 'Name and email are required fields' });
}

// Create a new user document with name and email from request body
const newUser = new User({
name: req.body.name,
email: req.body.email
});

// Save the new user document to the database


const savedUser = await newUser.save();
res.json(savedUser);
} catch (error) {
console.error('Error creating user:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
// Start the server
app.listen(5000, () => {
console.log(`Server is running on http://localhost:5000`);
});
OUTPUT: 4(b)

You might also like