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

Exercise-7 MST Programs

The document outlines a series of exercises related to building applications using Express.js, including routing for an Adventure Trails booking website, handling middleware for a myNotes application, and connecting to MongoDB with Mongoose. Each section provides detailed steps for setting up the project, installing necessary packages, and implementing code for various functionalities. The exercises culminate in creating a model object for the database schema, showcasing the integration of Express.js with MongoDB.
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)
7 views

Exercise-7 MST Programs

The document outlines a series of exercises related to building applications using Express.js, including routing for an Adventure Trails booking website, handling middleware for a myNotes application, and connecting to MongoDB with Mongoose. Each section provides detailed steps for setting up the project, installing necessary packages, and implementing code for various functionalities. The exercises culminate in creating a model object for the database schema, showcasing the integration of Express.js with MongoDB.
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/ 12

Exercise-7 MST Programs

7.a
Course Name: Express.js
Module Name: Defining a route, Handling Routes, Route Parameters, Query Parameters
AIM: Implement routing for the AdventureTrails application by embedding the necessary
code in the routes/route.js file.
Description:
Adventure Trails Application:
 Adventure Trails is a travel package booking website , focusing on adventure traveling,
school and corporate trip organizing, ticket booking, and holiday package services etc.,
This is created using express.js framework. To fetch the details from db, mongoDB is
used. This website has 4 different modules i.e. booking page, packagedetails page ,
contact us page and careers page.
 package.json: The package.json file is usually present in the root directory of a Node.js
project. This file helps npm to identify the project and handle its dependencies. It consists
of other metadata, vital to end-users, such as the description of the project, its version,
license information, other configuration data, etc.

Procedure Steps:
Step 1: Create your directory Project in D:/> and change your directory
and Open the VS CODE editor and create a file route.js
Step2: Open the Power Shell Terminal(… on the menu bar) in VS CODE.
Step3: Creating a package.json file using following command:
PS D:\Project> npm init
Is this OK? (yes) yes
Step4: Install Express.js using following command:
PS D:\Project> npm i express -g
Step5: Install nodemon using following command:
PS D:\Project> npm i -D nodemon
 Once the 'nodemon' is installed in the machine, the Node.js server code can be executed by
replacing the command "node" with "nodemon".
Step 6: Run the route.js using the following nodemon command.
PS D:\Project> nodemon route.js press enter button then server starts.
Step 4: Open the browser and enter URL as http://localhost:4000 then output displayed.

SOURCE CODE: route.js


const express=require('express');
const app=express();
//get method is used to request data from the server but mainly this method is used to read data.
app.get('/',(req, res) => {
res.send('<h1><font color="red">Adventure Trails Application</font></h1>');
});
const AdventureTrailsData=[
{
AdventureTrails:"Sahas Adventure Camp",
id:101,
Location:"Ramoji Film City, Hyderabad",
Prices:"INR 2000 per person",
BestTimeToVisit:"November to February",
TrekkingDistance:"70 km",
Difficultyleve:"Easy to Moderate",
Duration:"1-2 Days"
},
{
AdventureTrails:"Natures Nest Camp",
id:102,
Location:"North Goa Surla, Goa",
Prices:"INR 2,500 per person",
BestTimeToVisit:"November to March",
Duration:"2-3 Days",
TrekkingDistance:"25 km",
Difficultylevel:"Challenging"
}
]
app.get('/AdventureTrailsData',(req,res)=> {
res.json(AdventureTrailsData);
});
app.listen(4000, () => {
console.log(`Server is running on http://localhost:4000`);
});

package.json

{
"name": "project",
"version": "1.0.0",
"description": "Adventure Trails",
"main": "route.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Dr.ATP",
"license": "ISC",
"dependencies": {
"express": "^4.18.2"
}
}
7.a OUTPUT

7.b
Course Name: Express.js
Module Name: How Middleware works, Chaining of Middlewares, Types of Middlewares
AIM: In 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 gets executed
after the server receives the request and before the controller actions send the response.
Get and Post methods are standard HTTP requests to create REST APIs. Get method is
used to request data from the server but mainly this method is used to read data. It is more
efficient and popular than the POST method.
POST method is used to create new or to edit already existing data. This method allows
you to communicate massive amounts of data. The Post method is secure because the data is not
visible in the URL bar, it is not widely utilized as the GET method.
Step 1: Go to your project directory and enter the following command to create a NodeJs
project. Make sure that NodeJs is installed in your machine.
PS D:\Project> npm init -y
Step2: To use this middleware in the Express application, we need to install it.
PS D:\Project>npm install morgan
Step3: Install path using following command:
//This is an exact copy of the NodeJS ’path’ module published to the NPM registry.
PS D:\Project> npm i path
Step4: Install morgan-body using following command:
PS D:\Project> npm i morgan-body
Step 5: Run the midelware.js using the following node command.
PS D:\Project> nodemon midelware.js press enter button then server starts.
Step 4: Open the browser and enter URL as http://localhost:5000 then output displayed.

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,
});
//Handle Get Submission in Express.js
app.get('/getRequest', (req, res,next)=> {
res.send('<h1><font color="blue">Welcome to Express.js-Middleware</font></h1>');
next();
});
//Handle Post Submission in Express.js
app.post('/postRequest', (req, res,next)=> {
res.send('Handle Post Submission in Express');
next();
});
//Display customized error messages.
// Do logging and user-friendly error message display
// It doesn't work as expected: it launches always the same "Cannot GET" error instead of the customized one.
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`);
});
7.b OUTPUT:

getRequest output:

• Morgan middleware also supports writing logs to a file.


7.b output: access.log

postRequest output 1:

1. If we want to see 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.
2. Open the Body then output will be displayed.
postRequest output 2:

To install Postman tool(Testing tool) on Windows, you need to following steps:

1. Visit the https://www.postman.com/ website using any web browser or postman download.
2. Click on Windows 64 – bit button then downloaded and install it.

3. Click on Windows Button to download.


4. Check for the executable file in downloads in your system and run it.
5. Once the Postman download is completed, click on Run to start the installation.
7.C
Course Name: Express.js
Module Name: Connecting to MongoDB with Mongoose, Validation Types and Defaults
AIM: 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 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).

Download and Install MongoDB 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 7.0.6, 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 do not close application and Click on the Install button to start the installation.
Step 8: Click Next once completed.

Step 9: click on the start button

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

Step 11; 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.
Step 12; To check whether the MongoDB is installed or not
 Open the command prompt and enter the following command ;
C:/> mongo

Procedure steps:
Step1: Installing Mongoose:
 For installing the Mongoose library, issue the below command in the Node command
prompt.
D:/Project> npm install --save mongoose
Step2:Connecting to MongoDB using Mongoose:
 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: Run the valid.js using the following node command.
PS D:\Project> nodemon valid.js press enter button then server starts.
Step 4: Open the browser and enter URL as http://localhost:5000 then output displayed.

SOURECE CODE:
//Connecting to MongoDB database with Mongoose
const express = require('express');
mongoose = require('mongoose');
const app = express();
//Establish a connection to the MongoDB database IntellectNotes for storing details using the below code:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/IntellectNotes', {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
})
.then(() => console.log('Connected to MongoDB database.'))
.catch(err => console.error('Error connecting to MongoDB database:', err));

// Define the Note schema


const myNotesSchema = new mongoose.Schema(
{
notesID: {
type: Number,
unique: true,
required: [true, 'Required field'],
},
name: {
type: String,
required: [true, 'Required field'],
},
data: {
type: String,
},
},
{
timestamps: {
createdAt: true,
updatedAt: true,
},
}
);

//Start the Express server


app.listen(5000, () => {
console.log(`Server is running on http://localhost:5000`);
});

7.d
Course Name: Express.js
Module Name: Models
AIM: Write a program to wrap the Schema into a Model object.

You might also like