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

Unit-2 - Express Framework

The document discusses a course on web development using the MEAN stack. It includes details about the course units which cover topics like Node.js, Express, AngularJS, and connecting Angular with MongoDB.

Uploaded by

aryan rana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

Unit-2 - Express Framework

The document discusses a course on web development using the MEAN stack. It includes details about the course units which cover topics like Node.js, Express, AngularJS, and connecting Angular with MongoDB.

Uploaded by

aryan rana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 119

Noida Institute of Engineering and Technology, Greater Noida

WEB DEVELOPMENT USING


MEAN STACK

Unit: 2

Express Framework
Praveen Tomar
Course Details (Asst. Professor)
(B. Tech. 6th Sem)
CSE-AI Department

03/27/2024 SWETA PANDEY WEB DEVELOPMENT USING MEAN STACK Unit 2 1


Faculty Introduction

Name Praveen Tomar


Qualification M. Tech. (Computer Science & Engineering),M.C.A
Designation Assistant Professor
Department Computer Science & Engineering-A.I
Total Experience 14 years
NIET Experience 1 years
Subject Taught Web Technology, Data Structures, Artificial Intelligence, Soft
Computing, C Programming, C++, Java.

03/27/2024 Praveen Tomar WEB DEVELOPMENT USING MEAN STACK Unit I 2


Evaluation Scheme

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 3
Syllabus

UNIT-I: Introduction to Nodejs

Installing Nodejs, Node in-built packages (buffer, fs, http, os,


path, util, url)Node.js modules, File System Module,
Json data, Http Server and Client, Error handling with
appropriate HTTP, Callback function, asynchronous
programing REST API’s(GET, POST PUT, DELETE UPDATE),
GraphQL, Promises, Promise Chaining,
Introduction to template engine (EJS).

03/27/2024 SWETA PANDEY WEB DEVELOPMENT USING MEAN STACK Unit 2 4


Syllabus

UNIT-II: Express Framework

Configuring Express, Postman configuration, Environment


Variables, Routing, Defining pug templates, HTTP method of
Express, URL binding, middleware function, Serving static files,
Express sessions, REST full API’s, FORM data in Express, document
modeling with Mongoose.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 5
Syllabus

UNIT-III: Basics of Angular js

Typescript, Setup and installation, Power of Types , Functions


Function as types Optional and default parameters, Arrow
functions, Function overloading, Access modifiers, Getters and
setters, Read-only & static, Abstract classes, Interfaces,
Extending and Implementing Interface, Import and Export
modules.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 6
Syllabus

UNIT-IV: Building Single Page App with Angular js

MVC Architecture, One-way and Two-way data binding, AngularJS


Expressions, AngularJS Controllers, AngularJS Modules, adding
controller to a module, Component, Dependency Injection, Filters,
Tables, AngularJS Forms and Forms validation, Select using ng-
option, AngularJS AJAX.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 7
Syllabus

UNIT-V: Connecting Angular js with MongoDB

Environment Setup of Mongo dB , data modeling ,The current


SQL/NoSQL landscape, Create collection in Mongo dB, CRUD
Operations in MongoDB. Mongo's feature set, Introduction to
Mongoose, understanding mongoose schemas and datatypes,
Connecting Angular with mongo dB using API.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 8
Branch Wise Application

1. Real time web analytics


2. Digital Advertising
3. E-Commerce
4. Publishing
5. Massively Multiplayer Online Games
6. Backend Services and Messaging
7. Project Management & Collaboration
8. Real time Monitoring Services
9.Live Charting and Graphing
10. Group and Private Chat

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 9
Course Objective

In this semester, the students will

Study how to design and build static as well as dynamic webpages and
interactive web applications

Students examine advanced topics like Angular, nodejs, Mongodb for web
applications.

Also examine Express framework for interactive web applications that use rich
user interfaces .

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 10
Course Outcomes (COs)

At the end of course, the student will be able to:


CO1 : Explain, analyze and apply the role of
server-side scripting language like Nodejs .
CO2 : Demonstrate Express framework to design and implement dynamic web pages .

CO3 : Apply the knowledge of Typescript that are vital in understanding angular js.

CO4 : Analyze build and develop single page application using client-side programming.

CO5 : Understand the impact of web designing by database connectivity with Mongodb

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 11


T USING MEAN STACK Unit 2
Program Outcomes (POs)

Engineering Graduates will be able to:

PO1 : Engineering Knowledge


PO2 : Problem Analysis
PO3 : Design/Development of
solutions
PO4 : Conduct Investigations of
complex problems
PO5 : Modern tool usage
PO6 : The engineer and society
03/27/2024 SWETA PANDEY WEB DEVELOPMEN 12
T USING MEAN STACK Unit 2
Program Outcomes (POs)

Engineering Graduates will be able to:

PO7 : Environment and sustainability


PO8 : Ethics
PO9 : Individual and teamwork
PO10 : Communication
PO11 : Project management and
finance
PO12 : Life-long learning
03/27/2024 SWETA PANDEY WEB DEVELOPMEN 13
T USING MEAN STACK Unit 2
COs - POs Mapping

CO.K PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

CO1 2 2 2 3 3 - - - - - - -

CO2 3 2 3 2 3 - - - - - - -

CO3 3 2 3 2 3 - - - - - - -

CO4 3 2 3 2 3 - - - - - - -

CO5 3 2 3 3 3 - - - - - - -

AVG 2.8 2.0 2.8 2.4 3.0 - - - - - - -

SWETA PANDEY WEB DEVELOPMENT USING MEAN


03/27/2024 14
STACK Unit 2
Program Specific Outcomes(PSOs)
Program Specific
S. No. PSO Description
Outcomes (PSO)

1 PSO1 Understand to shows relationships and interactions


between classes or objects of a pattern.

2 PSO2 Study to speed up the development process by


providing well-tested, proven development

3 PSO3 Select a specific design pattern for the solution of a


given design problem

Create a catalogue entry for a simple design pattern


4 PSO4 whose purpose and application is understood.

SWETA PANDEY WEB DEVELOPMENT USING MEAN


03/27/2024 15
STACK Unit 2
COs - PSOs Mapping

CO.K PSO1 PSO2 PSO3 PSO4

CO1 3 - - -

CO2 3 3 - -

CO3 3 3 - -

CO4 3 3 - -

CO5 3 3 - -

SWETA PANDEY WEB DEVELOPMENT USING MEAN


03/27/2024 16
STACK Unit 2
Program Educational Objectives (PEOs)

Program Educational
PEOs Description
Objectives (PEOs)
To have an excellent scientific and engineering breadth so as to comprehend,
PEOs analyze, design and provide sustainable solutions for real-life problems using state-
of-the-art technologies.

To have a successful career in industries, to pursue higher studies or to support


PEOs entrepreneurial endeavors and to face the global challenges.

To have an effective communication skills, professional attitude, ethical values and a


PEOs desire to learn specific knowledge in emerging trends, technologies for research,
innovation and product development and contribution to society.

To have life-long learning for up-skilling and re-skilling for successful professional
PEOs career as engineer, scientist, entrepreneur and bureaucrat for betterment of society.

SWETA PANDEY WEB DEVELOPMENT USING MEAN


03/27/2024 17
STACK Unit 2
Result Analysis(Department Result & Subject Result & Individual result

Name of the faculty Subject code Result % of clear passed

Mr. Rahul Kumar ACSE0614

SWETA PANDEY WEB DEVELOPMENT USING MEAN


03/27/2024 18
STACK Unit 2
Pattern of Online External Exam Question Paper (100 marks)

SWETA PANDEY WEB DEVELOPMENT USING MEAN


03/27/2024 19
STACK Unit 2
Pattern of Online External Exam Question Paper (100 marks)

SWETA PANDEY WEB DEVELOPMENT USING MEAN


03/27/2024 20
STACK Unit 2
Pattern of Online External Exam Question Paper (100 marks)

SWETA PANDEY WEB DEVELOPMENT USING MEAN


03/27/2024 21
STACK Unit 2
Pattern of Online External Exam Question Paper (100 marks)

SWETA PANDEY WEB DEVELOPMENT USING MEAN


03/27/2024 22
STACK Unit 2
Pattern of Online External Exam Question Paper (100 marks)

SWETA PANDEY WEB DEVELOPMENT USING MEAN


03/27/2024 23
STACK Unit 2
Prerequisite / Recap

• Student should have knowledge of Web technology and terminology.

• Knowledge of HTML ,CSS and Java Script required .

• knowledge of Programing language such as C/C++/Python etc.

• Good problem solving Skill .

SWETA PANDEY WEB DEVELOPMENT USING MEAN


03/27/2024 24
STACK Unit 2
Brief Introduction about the Subject with videos

YouTube /Other Video Links

• https://youtu.be/BLl32FvcdVM

• https://youtu.be/v9ejT8FO-7I?list=PLrhzvIcii6GNjpARdnO4ueTUAVR9eMBpc

• https://youtu.be/VGLjQuEQgkI?list=PLt4nG7RVVk1h9lxOYSOGI9pcP3I5oblbx

SWETA PANDEY WEB DEVELOPMENT USING MEAN


03/27/2024 25
STACK Unit 2
Unit II Content

• Configuring Express, Postman configuration,


Environment Variables, Routing, Defining pug
templates, HTTP
• Method of Express, URL binding, middleware
function, Serving static files, Express sessions,
REST full API’s,
• FORM data in Express, document modeling with
Mongoose.

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 26


T USING MEAN STACK Unit 2
Unit II Objective

In Unit II, the students will be able to find


• Definitions of terms and concepts.
• The idea of Configuring Express.
• Routing, Defining pug templates.
• HTTP method of Express, URL binding, middleware function.
• Serving static files, Express sessions, REST full API’s,
• FORM data in Express, document modeling with Mongoose.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 27
Topic Objective

Topic : Configuring Express, Postman configuration, Environment


Variables, Routing, Defining pug templates,
In this topic, the students will gain , how to install Express and
POSTMAN . What are environment variables, routing and how to
define pug templates.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 28
MEAN STACK

 MEAN .js is designed for the developers who want to design the dynamic
website and web application using Mean.js.

 The Mean.js can be considered a collection of various technologies for


developing a dynamic website and web application.

 Mean.js is used for developing a web application where MongoDB is used


as a database system, Express.js is used as a back-end web framework,
node.js is used as a web server, and Angular.js is used as a front-end
framework.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 29
Express.js

 Express.js is a free and open-source software used as a back-end web


application framework.
 It is commonly used in the popular development stacks like MEAN with a
MongoDB database.
 The Express.js was developed by TJ Holowaychuk.
 Express is a fast, assertive, essential and moderate web framework of
Node.js.
 We can assume express as a layer built on the top of the Node.js that
helps manage a server and routes.
 It provides a robust set of features to develop web and mobile
applications.
SWETA PANDEY WEB DEVELOPMENT USING
03/27/2024 MEAN STACK Unit 2 30
Features of Express framework:

 It can be used to design single-page, multi-page and hybrid web


applications.

 It allows to setup middlewares to respond to HTTP Requests.

 It defines a routing table which is used to perform different actions based


on HTTP method and URL.

 It allows to dynamically render HTML Pages based on passing arguments


to templates.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 31
Use of Express.js

 Ultra fast I/O


 Asynchronous and single threaded
 MVC like structure
 Robust API makes routing easy

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 32
Advantages of Express.js

Advantages of Express.js

 It is simple and lightweight software. It is not heavy to get installed in the machine
and make the application running.

 It is easy to customize and configure as we can see it provides the flexibility that we
require.

 It is a better choice for creating the API as when the application requires various APIs
to communicate with different people then the Express.js is a good option..

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 33
Configure Express
Install Express.js

 Use the following command to install express:

 npm install express --save

 The above command install express in node_module directory and create a


directory named express inside the node_module.

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 34


T USING MEAN STACK Unit 2
Configure Express Conti....

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 35
Configure Express Conti...

 You should install some other important modules along with express.

 Following is the list:

 body-parser: This is a node.js middleware for handling JSON, Raw, Text and URL
encoded form data.

 cookie-parser: It is used to parse Cookie header and populate req.cookies with an


object keyed by the cookie names.

 multer: This is a node.js middleware for handling multipart/form-data.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 36
Configure Express Conti...

body-parser: This is a node.js middleware for handling JSON, Raw, Text and URL
encoded form data.

COMMAND:

npm install body-parser --save

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 37
Configure Express Conti...

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 38


T USING MEAN STACK Unit 2
Configure Express Conti...

cookie-parser:
It is used to parse Cookie header and populate req.cookies with an object keyed by
the cookie names.
COMMAND:

npm install cookie-parser --save

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 39
Configure Express Conti...

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 40


T USING MEAN STACK Unit 2
Configure Express Conti...

multer: This is a node.js middleware for handling multipart/form-data.

COMMAND:
npm install multer --save

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 41


T USING MEAN STACK Unit 2
Configure Express Conti...

multer: This is a node.js middleware for handling multipart/form-data.

COMMAND:
npm install multer --save

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 42


T USING MEAN STACK Unit 2
Postman

Postman:
 Postman is a standalone software testing API (Application Programming Interface)
platform to build, test, design, modify, and document APIs.
 It is a simple Graphic User Interface for sending and viewing HTTP requests and
responses.
 While using Postman, for testing purposes, one doesn't need to write any HTTP
client network code. Instead, we build test suites called collections and let
Postman interact with the API.
 In this tool, nearly any functionality that any developer may need is embedded.
 This tool has the ability to make various types of HTTP requests like GET, POST,
PUT, PATCH, and convert the API to code for languages like JavaScript and Python.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 43
Features of Postman
Features of Postman:
 Accessibility
 Use Collections
 Test development
 Automation Testing
 Debugging

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 44
Postman Configuration

Steps to download and install the native Postman:


Step-1: Go to the link https://www.postman.com/downloads/ and click
download for Mac or Windows based on your operating system.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 45
Postman Configuration Conti....

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 46
Postman Configuration Conti....

Step-2: For downloading the app for Windows, click on the download
button and select the particular version. I opted for the 64-bit version.
If you are using a 32-bit OS, you can choose the 32 bit, as shown in the
above image.

Step-3: You can check the download progress on the bottom left if you
are using the Chrome browser. Once the .exe file is downloaded, you
need to install the application, as shown in the below image.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 47
Postman Configuration Conti....

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 48
Postman Configration Conti.....

Step-4: Once the installation completes, you will be redirected to a


window as shown in the image where you can click on Stop signing in
and take me straight to the app (as this app can also be used without
logging in) or otherwise you will get a new window to sign up.

Step-5: Create your account with all the required details, or you can
also signup with Google, as shown in the image.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 49
Postman Configuration Conti....

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 50
Postman Configuration Conti....

Step-6: After signing in, select the workspace tools as per your
requirement, and then click on, continue to get the startup screen.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 51
Postman Configuration Conti....

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 52
Postman Configuration

Step-7: You will see the following


page, and then you are ready to use
Postman.

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 53


T USING MEAN STACK Unit 2
Environment Variable
Environment Variable in Postman:
 A collection of key-value pairs is called an environment.
 Each name of the variable represents its keys. And referencing the name of the
variable allows you to access its value.
 It is a set of variables that differentiate among the requests. Such as, we can have
an environment for testing, one for development and another for production.
 We can change the value of the variables to pass the data between requests and
tests.
 Postman variables work in the same way as that of the programming variables.
These are the symbols capable of taking various values.
 You can store the values in variables and can use it throughout in requests,
environments, collections, and scripts.
 Variables in Postman increase the user's efficiency to work and decrease the errors.
SWETA PANDEY WEB DEVELOPMENT USING
03/27/2024 MEAN STACK Unit 2 54
Environment Variable
Types of EnvironmenVariables:
Local Variables
These are temporary variables that will only function inside the environment they were created in.
When you change the environment, the variable will stop its access, and an error will occur.
Collection Variables
These are independent of environments and are available for all the requests in a collection.
Environment Variables
These are the most used variable scope in Postman. At a time, a single environment can be active.
They are bound to a specified environment used to execute the request.
Global Variables
These are independent of environments and function outside the environment. Users are not
required to create an environment for global variables. Through global variables, we can access data
between collections, test scripts, requests, and environments.
Data Variables
Data variables come from external CSV and JSON files to define data sets
SWETA PANDEY WEB DEVELOPMENT USING
03/27/2024 MEAN STACK Unit 2 55
Environment Variable
Creating an Environment
To create an environment, follow the following steps:
Go to New -> Environment.

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 56


T USING MEAN STACK Unit 2
Environment Variable

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 57


T USING MEAN STACK Unit 2
Environment Variable

 Or you can create an environment from Environment quick look.


 For that, click on Environment quick look button visible as an eye icon
available in the top right corner of the builder section, as shown in the
image below.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 58
Environment Variable

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 59


T USING MEAN STACK Unit 2
Environment Variable

 Now select Add.

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 60


T USING MEAN STACK Unit 2
Environment Variable

 Enter the name of the Environment and click on Add..

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 61


T USING MEAN STACK Unit 2
Environment Variable

Creating an Environment Variable:


To create an environment variable follow the following steps:

 Go to Environment quick look button visible as an eye icon available in


the top right corner of the builder section.

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 62


T USING MEAN STACK Unit 2
Environment Variable

 Select the Edit option.

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 63


T USING MEAN STACK Unit 2
Environment Variable

 Enter the below mentioned key-value pairs in which Key =url and Initial Value =
http://restapi.demoqa.com.
 Then select the Update button and close the Manage Environment window. Now
you have an environment variable with the name 'url', and the value of the variable
is the http://restapi.demoqa.com.

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 64


T USING MEAN STACK Unit 2
Environment Variable
Dynamic Variables :
Numbers, Texts and Colors
Variable Name
$randomAlphaNumeric: A random alphanumeric character
$randomInt: A random integer between 1 and 1000
$randomColor: A random color
$randomHexColor:A random hex value
$randomAbbreviation: A random abbreviation
$randomBoolean: A random boolean value like true or false
Address, Location, Phone
$randomCountry: A random country
$randomCountryCode: Random country code of two letters (ISO 3166-1 alpha-2)
$randomCity: A random city name
$randomStreetName: A random street name
SWETA PANDEY WEB DEVELOPMENT USING
03/27/2024 MEAN STACK Unit 2 65
Pug Template
Pug Template:
 A template engine facilitates you to use static template files in your applications. At runtime, it
replaces variables in a template file with actual values, and transforms the template into an
HTML file sent to the client. So this approach is preferred to design HTML pages easily.

 Express.js template engine


 Pug template must be written inside .pug file and all .pug files must be put inside views folder
in the root folder of Node.js application.

 Note: By default Express.js searches all the views in the views folder under the root folder. you
can also set to another folder using views property in express. For example:
app.set('views','MyViews').

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 66


T USING MEAN STACK Unit 2
Pug Template
Install pug:
 Execute the following command to install pug template engine:
 npm install pug --save

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 67


T USING MEAN STACK Unit 2
Pug Template
Simple input:
doctype html
html
head
title A simple pug example
body
h1 This page is produced by pug template engine
p some paragraph here..

Output produced by pug template:

<!DOCTYPE html>
<html>
<head>
<title>A simple pug example</title>
</head>
<body>
<h1>This page is produced by pug template engine</h1>
<p>some paragraph here..</p>
</body>
</html>
Express.js
can be used with any template engine. Let's take an example to deploy how pug template creates HTML page
dynamically.
03/27/2024 SWETA PANDEY WEB DEVELOPMEN 68
T USING MEAN STACK Unit 2
Pug Template
Create a file named index.pug file inside views folder and write the following pug template in it:
doctype html
html
head
title A simple pug example
body
h1 This page is produced by pug template engine
p some paragraph here..
File: server.js
var express = require('express');
var app = express();
//set view engine
app.set("view engine","pug")
app.get('/', function (req, res) {
res.render('view.pug', index);
res.render('index');
});
var server = app.listen(5000, function () {
console.log('Node server is running..');
});
03/27/2024 SWETA PANDEY WEB DEVELOPMEN 69
T USING MEAN STACK Unit 2
Routing
Express.js Routing

 Routing is made from the word route. It is used to determine the specific behavior of an application.

 It specifies how an application responds to a client request to a particular route, URI or path and a
specific HTTP request method (GET, POST, etc.). It can handle different types of HTTP requests.

 Routing in ExpressJS is used to subdivide and organize the web application into multiple mini-
applications each having its own functionality.

 It provides more functionality by subdividing the web application rather than including all of the
functionality on a single page.

 These mini-applications combine together to form a web application. Each route in Express responds
to a client request to a particular route/endpoint and an HTTP request method (GET, POST, PUT,
DELETE, UPDATE and so on).

 Each route basically refers to the different URLs in the website. So when a URL.
03/27/2024 SWETA PANDEY WEB DEVELOPMEN 70
T USING MEAN STACK Unit 2
ExpressJS - Routing

To use the dynamic routes, we SHOULD provide different types of routes. Using dynamic routes allows us
to pass parameters and process based on them.

Here is an example of a dynamic route −

var express = require('express');


var app = express();

app.get('/:id', function(req, res){


res.send('The id you specified is ' + req.params.id);
});
app.listen(3000);

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 71


T USING MEAN STACK Unit 2
ExpressJS - Routing

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 72


T USING MEAN STACK Unit 2
Topic Objective

Topic : HTTP method of Express, URL binding, middleware function,


Serving static files, Express sessions.

• In this topic, the students will learn about the methods of express.
What are URL binding and middleware funtion. Student will learn
regarding sttic files and express session .

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 73
HTTP method of Express

 GET and POST both are two common HTTP requests used for
building REST API's.
 GET requests are used to send only limited amount of data
because data is sent into header while POST requests are used to
send large amount of data because data is sent in the body.
 Express.js facilitates you to handle GET and POST requests using
the instance of express.
 Get method facilitates you to send only limited amount of data
because data is sent in the header. It is not secure because data is
visible in URL bar.

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 74


T USING MEAN STACK Unit 2
GET METHOD EXAMPLE

Fetch data in paragraph format


File: index.html

1.<html>
2.<body>
3.<form action="http://127.0.0.1:8000/get_example2" method="GET">
4.First Name: <input type="text" name="first_name"/> <br/>
5.Last Name: <input type="text" name="last_name"/><br/>
6.<input type="submit" value="Submit"/>
7.</form>
8.</body>
9.</html>
03/27/2024 SWETA PANDEY WEB DEVELOPMEN 75
T USING MEAN STACK Unit 2
GET Method Cont……
File: get_example.js

1.var express = require('express');


2.var app=express();
3.app.get('/get_example2', function (req, res) {
4.res.send('<p>Username: ' + req.query['first_name']+'</
p><p>Lastname: '+req.query['last_name']+'</p>');
5.})
6.var server = app.listen(8000, function () {
7. var host = server.address().address
8. var port = server.address().port
9. console.log("Example app listening at http://%s:%s", host, port)
10.})
03/27/2024 SWETA PANDEY WEB DEVELOPMEN 76
T USING MEAN STACK Unit 2
GET Method Cont……

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 77


T USING MEAN STACK Unit 2
GET Method Cont…….

Output:

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 78


T USING MEAN STACK Unit 2
Post Method

 Post method facilitates you to send large amount of data


because data is send in the body.
 Post method is secure because data is not visible in URL bar
but it is not used as popularly as GET method.
 On the other hand GET method is more efficient and used
more than POST.

SWETA PANDEY WEB DEVELOPMENT USING MEAN STACK


03/27/2024 79
Unit 2
POST Method Cont…….

File: Index.html

1.<html>
2.<body>
3.<form action="http://127.0.0.1:8000/process_post" method="POST">
4.First Name: <input type="text" name="first_name"> <br>
5.Last Name: <input type="text" name="last_name">
6.<input type="submit" value="Submit">
7.</form>
8.</body>
9.</html>
03/27/2024 SWETA PANDEY WEB DEVELOPMEN 80
T USING MEAN STACK Unit 2
POST Method Cont…….
File: post_example1.js

1.var express = require('express');


2.var app = express();
3.var bodyParser = require('body-parser');
4.// Create application/x-www-form-urlencoded parser
5.var urlencodedParser = bodyParser.urlencoded({ extended: false })
6.app.use(express.static('public'));
7.app.get('/index.html', function (req, res) {
8. res.sendFile( __dirname + "/" + "index.html" );
9.})
10.app.post('/process_post', urlencodedParser, function (req, res) {
11. // Prepare output in JSON format
12. response = {
13. first_name:req.body.first_name,
14. last_name:req.body.last_name
15. };
16. console.log(response);
17. res.end(JSON.stringify(response));
18.})
19.var server = app.listen(8000, function () {
20. var host = server.address().address
21. var port = server.address().port
22. console.log("Example app listening at http://%s:%s", host, port)
23.})

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 81


T USING MEAN STACK Unit 2
POST Method Cont…….

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 82


T USING MEAN STACK Unit 2
POST Method Cont…….

OUTPUT:

Note: In the above picture, you can see that entries are not visible in the URL bar unlike GET method.

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 83


T USING MEAN STACK Unit 2
Express.js Middleware
Express.js Middleware
 Express.js Middleware are different types of functions that are invoked by the
Express.js routing layer before the final request handler.
 As the name specified, Middleware appears in the middle between an initial request
and final intended route. I
 n stack, middleware functions are always invoked in the order in which they are
added.
 Middleware is commonly used to perform tasks like body parsing for URL-encoded or
JSON requests, cookie parsing for basic cookie handling, or even building JavaScript
modules on the fly.
 Middleware functions are functions that have access to the request object (req),
the response object (res), and the next middleware function in the application’s
request-response cycle. These functions are used to modify req and res objects for
tasks like parsing request bodies, adding response headers, etc.
03/27/2024 SWETA PANDEY WEB DEVELOPMEN 84
T USING MEAN STACK Unit 2
Express.js Middleware Function
Middleware function
 Middleware functions are the functions that access to the request and response object (req, res) in request-
response cycle.

A middleware function can perform the following tasks :


 It can execute any code.
 It can make changes to the request and the response objects.
 It can end the request-response cycle.
 It can call the next middleware function in the stack.
Used middleware in Express.js app:

 Application-level middleware
 Router-level middleware
 Error-handling middleware
 Built-in middleware
 Third-party middleware
03/27/2024 SWETA PANDEY WEB DEVELOPMEN 85
T USING MEAN STACK Unit 2
Express.js Middleware Function Conti....
simple example of a middleware function in action −

var express = require('express');


var app = express();

//Simple request time logger


app.use(function(req, res, next){
console.log("A new request received at " + Date.now());

//This function call is very important. It tells that more processing is


//required for the current request and is in the next middleware
function route handler.
next();
});
app.listen(3000);

The above middleware is called for every request on the server. So after every request, we will get the following message in the
console −
A new request received at 1467267512545

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 86


T USING MEAN STACK Unit 2
ExpressJS - Serving static files
Static files
 Files that clients download as they are from the server. Create a new directory, public. Express, by
default does not allow you to serve static files.
 You need to enable it using the following built-in middleware.
app.use(express.static('public'));
 All static files you load will be considering public as root.
 To test that this is working fine, add any image file in your new public dir and change its name to
"testimage.jpg". In your views, create a new view and include this file like −

• html
• head
• body
• h3 Testing static file serving:
• img(src = "/testimage.jpg", alt = "Testing Image

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 87


T USING MEAN STACK Unit 2
ExpressJS - Serving static files

OUTPUT:

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 88


T USING MEAN STACK Unit 2
ExpressJS - Session
 HTTP is stateless; in order to associate a request to any other request, you need a
way to store user data between HTTP requests.
 Cookies and URL parameters are both suitable ways to transport data between the
client and the server. But they are both readable and on the client side.
 Sessions solve exactly this problem. You assign the client an ID and it makes all
further requests using that ID. Information associated with the client is stored on the
server linked to this ID.

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 89


T USING MEAN STACK Unit 2
ExpressJS - Session

We will need the Express-session, so install it using the following code.

npm install --save express-session


 We will put the session and cookie-parser middleware in place. In this example, we will use the default store for
storing sessions, i.e., MemoryStore. Never use this in production environments.
 The session middleware handles all things for us, i.e., creating the session, setting the session cookie and
creating the session object in req object.

 Whenever we make a request from the same client again, we will have their session information stored with us
(given that the server was not restarted).
 when a user visits the site, it creates a new session for the user and assigns them a cookie.
 Next time the user comes, the cookie is checked and the page_view session variable is updated accordingly.

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 90


T USING MEAN STACK Unit 2
Topic Objective

Topic : REST full API’s, FORM data in Express, document modeling with
Mongoose.
• In this topic, the students will gain , The idea of REST full API. FORM
data usedin Express and document modeling with Mongoose will
be cover.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 91
FORM Data

 Forms are an integral part of the web.


 Almost every website we visit offers us forms that submit or fetch some
information for us.
 To get started with forms, we will first install the body-parser(for parsing
JSON and url-encoded data) and multer(for parsing multipart/form data)
middleware.

 To install the body-parser and multer, go to your terminal and use −

 npm install --save body-parser multer

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 92
FORM Data Cont……

 After importing the body parser and multer, we will use the body-parser for
parsing json and x-www-form-urlencoded header requests, while we will
use multer for parsing multipart/form-data.

 Create a new view called form.pug

 Run your server using the following.

 At console; it will show you the body of your request as a JavaScript object

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 93
REST API
Introduction:
 REST API is the standard way to send and receive data for web services.
 A client sends a req which first goes to the rest API and then to the database
to get or put the data after that, it will again go to the rest API and then to
the client.
 Using an API is just like using a website in a browser, but instead of clicking
on buttons, we write code to req data from the server.
 It's incredibly adaptable and can handle multiple types of requests.

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 94


T USING MEAN STACK Unit 2
REST API Cont……

What Is REST API?


 REST (Representational state transfer) is a popular architecture that is used
to create web services.

 API (Application Programming Interface is a code that allows two software


programs to communicate with each other.

 REST API is a software that allows two apps to communicate with one
another over the internet and through numerous devices.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 95
REST API Cont……
 HTTP Request Types
 HTTP Requests are simply messages that are sent by the client to do some
tasks on the server

 GET - Get command is used to request data from the server, but mainly this
method is used to read data
 PATCH - This command is used to update, change or replace the data
 POST - The post method is used to create new or to edit already existing
data
 Delete - This delete command is used to delete the data completely from
the server

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 96
REST API Cont……
API Using Express and Its Architecture :

A request is sent by the client in the form of a JSON file, and with the help of an
HTTP request which gets a patch post and delete, it will go to the server first
then, the server sends back the response to the client in the form of a message
to tell what happened to your request.

SWETA PANDEY WEB DEVELOPMENT USING


03/27/2024 MEAN STACK Unit 2 97
REST API Cont……

Step 1: First, open your editor. Now open your terminal and write a command npm init -y

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 98


T USING MEAN STACK Unit 2
REST API Cont……

Step 1: command npm init -y


This command will create a JSON file

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 99


T USING MEAN STACK Unit 2
REST API Cont……
Step 2: Now we will install express for that write command
npm install express
Express_REST_API_3

This will install dependencies in the package.json file


Step 3: Now we will create a new file to write all our code index.js

Write a few lines of code in the first line. We will import the express packages

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 100


T USING MEAN STACK Unit 2
REST API Cont……
This app.listen will respond to the server to listen on a specific port which we have defined already as a
variable 4000

Step 5: Then we will write a second argument as a callback to tell the API is working, now lets run this code to
check our API is working or node
To run this code, we will write a command node.

Step 6: As our code is running fine, let's open our search engine and write localhost:4000, this will not run,

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 101


T USING MEAN STACK Unit 2
REST API Cont……
Step 7: Now we need an add the second argument here

localhost:4000/simplilearn

Our Simple API is running Successfully

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 102


T USING MEAN STACK Unit 2
Mongoose Document Model

The Model.create() method of the Mongoose API is used to create single or


many documents in the collection. Mongoose by default triggers save()
internally when we use the create() method on any model.

Syntax:

Model.create()
Parameters: The Model.create() method accepts three parameters:

docs: It is an object of key-value pair which will be inserted into a collection.


options: It is an object with various properties.
callback: It is a callback function that will run once execution is completed.
Return
03/27/2024 Value: The Model.create()
SWETA PANDEY
function returns a promise.
WEB DEVELOPMENT USING MEAN STACK
Unit 2
103
Mongoose Document Model
 Setting up Node.js application:

 Step 1: Create a Node.js application using the following command:

 npm init
 Step 2: After creating the NodeJS application, Install the required module
using the following command:

 npm install mongoose

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 104


T USING MEAN STACK Unit 2
Mongoose Document Model
 Project Structure: The project structure will look like this:

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 105


T USING MEAN STACK Unit 2
Mongoose Document Model
// Require mongoose module
const mongoose = require('mongoose');

// Set Up the Database connection


mongoose.connect(
'mongodb://localhost:27017/geeksforgeeks', {
useNewUrlParser: true,
useUnifiedTopology: true
})

// Defining customerSchema schema


const customerSchema = new mongoose.Schema(
{ name: String, orderCount: Number }
)

// Defining customerSchema model


const Customer = mongoose.model(
'Customer', customerSchema);

// creating document using create method


Customer.create({ name: 'Rahul', orderCount: 5 })
.then(result => {
console.log(result)
})

SWETA PANDEY WEB DEVELOPMENT USING MEAN STACK


03/27/2024 106
Unit 2
Mongoose Document Model
Steps to run the program:
To run the application execute the below command from the root directory of
the project:
node app.js
Output:

{
name: 'Rahul',
orderCount: 5,
_id: new ObjectId("6304e68407a431f560473ac2"),
__v: 0
}

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 107


T USING MEAN STACK Unit 2
Mongoose Document Model

DATABASE:

03/27/2024 SWETA PANDEY WEB DEVELOPMEN 108


T USING MEAN STACK Unit 2
Daily Quiz

1) Which of the following command is used to check the current version of NPM?

a. nmp --ver
b. npm --version
c. npm help
d. None of the above
2) Which of the following method requests that the server accept the data enclosed in the request to
modify an existing object identified by the URI?

e. GET
f. DELETE
g. PUT
h. POST

SWETA PANDEY WEB DEVELOPMENT USING MEAN STACK


03/27/2024 109
Unit 2
Daily Quiz

3. Which of the following was the earlier name of the Pug?

a. Terse
b. DRY
c. Express
d. Jade
4. Which of the following function is used to specify what to do when a get request at the given route is
called?

e. app.get(route, callback)
f. get(route, callback)
g. js.get(route, callback)
h. fun.get(route, callback

SWETA PANDEY WEB DEVELOPMENT USING MEAN STACK


03/27/2024 110
Unit 2
Weekly Assignment

1.Differentiate between GET and POST method.


2. What do you think are the advantages of middleware function ?
3.Explain documentation modelling in moongose ?
4.What is FORM data ?
5.Describe routing in express js .

SWETA PANDEY WEB DEVELOPMENT USING MEAN STACK


03/27/2024 111
Unit 2
Topic Link ( YouTube & NPTEL Video Links)

YouTube /other Video Links

• https://youtu.be/rI4kdGLaUiQ?list=PL6n9fhu94yhUbctIoxoVTrklN3LMwTCmd

• https://youtu.be/v9ejT8FO-7I?list=PLrhzvIcii6GNjpARdnO4ueTUAVR9eMBpc

• https://youtu.be/VGLjQuEQgkI?list=PLt4nG7RVVk1h9lxOYSOGI9pcP3I5oblbx

SWETA PANDEY WEB DEVELOPMENT USING MEAN


03/27/2024 112
STACK Unit 2
MCQ (End of Unit)
1) Who is credited as the developer of Express.js?

a. Larry wall
b. Rich Hickey
c. TJ Holowaychuk
d. Rob Pike
2) Which of the following are the core features of the Express framework?

e. It allows us to set up middleware to respond to HTTP Requests.


f. It defines a routing table that can work as per HTTP Method and URL.
g. It is used to render the HTML pages dynamically.
h. All of the above.
3) In which of the following year was Express.js initially released?

i. November 2010
j. November 2011
k. December 2010
l. December 2011
SWETA PANDEY WEB DEVELOPMENT USING MEAN STACK
03/27/2024 113
Unit 2
MCQ (End of Unit)

4) Where are the captured values populated regarding the route parameters?

a. req.data
b. app.locals
c. req.params
d. All of the above
5) How is it possible to create chainable route handlers for a route path in Express.js?

e. Using app.route()
f. Using app.routes()
g. Using app.router()
h. Using app.routing()

SWETA PANDEY WEB DEVELOPMENT USING MEAN STACK


03/27/2024 114
Unit 2
Glossary Questions
Top 10 interview questions

1. What is Express.js?
2. What are some distinctive features of Express?
3. Is Express.js front-end or backend framework?
4. Why do we use Express.js?
5. What is the difference between Express.js and Node.js?
6. Write a code to get post a query in Express.js
7. What is the difference between Express and Django
8. How can you deal with error handling in Express.js? Explain with an example
9. Write the code to start serving static files in Express.js.
10.What is Middleware in Express.js? What are the different types of
Middleware?
03/27/2024 SWETA PANDEY WEB DEVELOPMEN 115
T USING MEAN STACK Unit 2
Expected Questions for University Exam

1. What is exppress framework?


2. How will you install express js?
3. Explain REST API .
4. Describe environment variables.
5. Differentiate between GET and POST method.
6. What do you think are the advantages of middleware function ?
7. Explain documentation modelling in moongose ?
8. What is FORM data ?
9. Describe routing in express js .
10.What is URL binding ?

SWETA PANDEY WEB DEVELOPMENT USING MEAN STACK


03/27/2024 116
Unit 2
Summary
Till Now we understand, How to Install Node.js and NPM on Windows and Mac.
js can be used to design single-page, multi-page, and hybrid web applications and
APIs. It allows to set up middleware to respond to HTTP/RESTful Requests.
It defines a routing table to perform different HTTP operations (method and URL).
It allows to dynamically rendering HTML Pages based on passing arguments to
templates. It provides high performance because of its ultra-fast I/O. It prepares a
thin layer; therefore, the performance is adequate.
Its MVC-like structure makes it organize the web application into MVC
architecture. It provides good database support. It supports RDBMS as well as
NoSQL databases. Its robust API makes routing easy.

SWETA PANDEY WEB DEVELOPMENT USING MEAN STACK


03/27/2024 117
Unit 2
References
1. Simon Holmes, Clive Herber, “Getting MEAN with Mongo, Express,
Angular, and Node”, 2nd Edition 2016, Addison Wesley Publication.
2. Dhruti Shah, “Comprehensive guide to learn Node.js”, 1st Edition, 2018
BPB Publications.
3. Christoffer,Noring,Pablo,Deeleman,“Learning Angular”,3rd Edition,2017
Packt publications. .
4. Peter Membrey, David Hows, Eelco Plugge, “MongoDB Basics”, 2nd
edition, 2018, International Publication.
5. Christoffer Noring,SWETA
03/27/2024
Pablo
PANDEY
Deeleman,WEB“Learning
DEVELOPMEN
Angular”,3rd Edition,118
T USING MEAN STACK Unit 2
THANK YOU

SWETA PANDEY WEB DEVELOPMENT USING MEAN STACK


03/27/2024 119
Unit 2

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy