SlideShare a Scribd company logo
EXPRESS JS-MIDDLEWARE
Prepared By:
Mrs. Bareen Shaikh
Assistant Professor
Computer Science
MIT ACSC Alandi(D)
Pune
Middleware
▪ Express is a routing and middleware web
framework that has minimal functionality of its
own
▪ An Express application is essentially a series of
middleware function calls.
▪ 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.
▪ The next middleware function is commonly
denoted by a variable named next.
Middleware
▪ Middleware functions can perform the following
tasks:
 Execute any code.
 Make changes to the request and the response
objects.
 End the request-response cycle.
 Call the next middleware function in the stack.
 If the current middleware function does not end the
request-response cycle, it must call next to pass
control to the next middleware function.
 Otherwise, the request will be left hanging.
Writing Middleware
▪ The following figure shows the elements of a
middleware function call:
Middleware function Example
▪ Following is a simple example of a middleware
function called “myLogger”.
▪ This function just prints “LOGGED” when a
request to the app passes through it.
▪ The middleware function is assigned to a
variable named myLogger.
var myLogger = function (req, res, next)
{
console.log('LOGGED');
next();
}
Middleware function Example
▪ To load the middleware function, call app.use(), specifying the
middleware function.
▪ For example, the following code loads the myLogger middleware
function before the route to the root path (/).
var express = require('express');
var app = express();
var myLogger = function (req, res, next) {
console.log('LOGGED');
next()
}
app.use(myLogger);
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000);
Middleware
▪ An Express application can use the following
types of middleware:
 Application-level middleware
 Router-level middleware
 Error-handling middleware
 Built-in middleware
 Third-party middleware
Application-level middleware
▪ Connect application-level middleware to an instance of
the app object by using
the app.use() and app.METHOD() functions.
▪ Following example shows a middleware function with no
mount path.The function is executed every time the app
receives a request.
var express = require('express');
var app = express();
app.use(function (req, res, next) {
varT=new Date(Date.now());
var t=T.toString()
console.log('Time:',t)
next()
})
app.listen(3000);
Routing using use() on
specified path
▪ Following example shows a middleware
function mounted on the /user/:id path.
app.use('/user/:id', function (req, res, next) {
console.log('RequestType:', req.method)
next()
})
▪ Route and its handler function using HTTP GET
requests
app.get('/user/:id', function (req, res, next) {
res.send(‘User Information')
})
Series of middleware for any
type of HTTP request
app.use('/user/:id', function (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}, function (req, res, next) {
console.log('RequestType:', req.method)
res.send(req.params)
next()
})
Multiple routes for a path
▪ Route handlers enable you to define multiple routes for a path.
▪ The example below defines two routes for GET requests to
the /user/:id path.
▪ The second route will not cause any problems, but it will never get
called because the first route ends the request-response cycle.
▪ This example shows a middleware sub-stack that handles GET
requests to the /user/:id path.
app.get('/user/:id', function (req, res, next) {
console.log('ID:', req.params.id)
next()
}, function (req, res, next) {
res.send('User Informtion')
})
// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', function (req, res, next) {
res.end(req.params.id)
})
call next('route')
▪ To skip the rest of the middleware functions from a
router middleware stack, call next('route') to pass
control to the next route.
▪ Following example shows a middleware sub-stack.
app.get('/user/:id', function (req, res, next) {
if (req.params.id === '0') next('route')
else next() }, function (req, res, next) {
res.send(‘series middleware
executed')
})
app.get('/user/:id', function (req, res, next) {
res.send('skipped and next middleware
executed')
})
Middleware Using Array
▪ Middleware can also be declared in an array for
reusability. Example as follows
function OriginalUrl (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}
function Method (req, res, next) {
console.log('RequestType:', req.method)
next()
}
var arr= [OriginalUrl, Method]
app.get('/user/:id', arr, function (req, res, next) {
res.send('User Information')
})
Router Level Middleware
▪ Router-level middleware works in the same way
as application-level middleware.
▪ Except it is bound to an instance of
 express.Router().
▪ var router = express.Router() Load router-level
middleware by using
 router.use() and
 router.METHOD()
▪ Example on next slide of router level middleware.
▪ To skip the rest of the router’s middleware
functions, call next('router') to pass control back
out of the router instance.
Router Level Middleware
const express = require('express');
const app = express();
const router = express.Router()
router.use((req,res,next)=>{
console.log("Time:",new Date())
next()
})
router.get("/user/:id",(req,res,next)=>{
console.log('Request URL:', req.originalUrl)
next()
},(req,res,next)=>{
console.log('RequestType:', req.method)
next()
},(req,res)=>{
res.json({
status:true,
id:req.params.id
})
})
app.use('/',router)
app.listen(3000,(req,res)=>{
console.log('server running on 3000')
})
Error-handling middleware
▪ Error-handling middleware always takes four arguments.
▪ Provide four arguments to identify it as an error-handling
middleware function.
▪ Even if don’t need to use the next object, you must specify it
to maintain the signature.
▪ Otherwise, the next object will be interpreted as regular
middleware and will fail to handle errors.
▪ Define error-handling middleware functions in the same
way as other middleware functions, except with four
arguments instead of three, specifically with the
signature (err, req, res, next)):
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
Built in Midddleware
▪ Express 4.0x no longer depends on Connect.
▪ The middleware functions that were previously
included with Express are now in separate modules;
see the
https://github.com/senchalabs/connect#middleware
▪ Express has the following built-in middleware
functions:
 express.static serves static assets such as HTML files,
images, and so on.
 express.json parses incoming requests with JSON
payloads. Available with Express 4.16.0+
 express.urlencoded parses incoming requests with URL-
encoded payloads. Available with Express 4.16.0+
▪ Also check
▪ https://expressjs.com/en/resources/middleware.html

More Related Content

Similar to Middleware.pdf

NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
ArthyR3
 
Express: A Jump-Start
Express: A Jump-StartExpress: A Jump-Start
Express: A Jump-Start
Naveen Pete
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
Juliana Lucena
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
Eldar Djafarov
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
Spike Brehm
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Alex Su
 
Express JS
Express JSExpress JS
Express JS
Alok Guha
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
Visual Engineering
 
Emberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applicationsEmberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applications
ColdFusionConference
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
Gianluca Carucci
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013
Laurent_VB
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
Francois Zaninotto
 
Node js crash course session 3
Node js crash course   session 3Node js crash course   session 3
Node js crash course session 3
Abdul Rahman Masri Attal
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
Ahmed Assaf
 
apidays LIVE Australia 2020 - Building distributed systems on the shoulders o...
apidays LIVE Australia 2020 - Building distributed systems on the shoulders o...apidays LIVE Australia 2020 - Building distributed systems on the shoulders o...
apidays LIVE Australia 2020 - Building distributed systems on the shoulders o...
apidays
 
ExpressJS-Introduction.pdf
ExpressJS-Introduction.pdfExpressJS-Introduction.pdf
ExpressJS-Introduction.pdf
Bareen Shaikh
 
Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdf
EngmohammedAlzared
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "
FDConf
 
Intro to Node
Intro to NodeIntro to Node
Intro to Node
Aaron Stannard
 
Writing RESTful web services using Node.js
Writing RESTful web services using Node.jsWriting RESTful web services using Node.js
Writing RESTful web services using Node.js
FDConf
 

Similar to Middleware.pdf (20)

NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
 
Express: A Jump-Start
Express: A Jump-StartExpress: A Jump-Start
Express: A Jump-Start
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Express JS
Express JSExpress JS
Express JS
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte II
 
Emberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applicationsEmberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applications
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Node js crash course session 3
Node js crash course   session 3Node js crash course   session 3
Node js crash course session 3
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 
apidays LIVE Australia 2020 - Building distributed systems on the shoulders o...
apidays LIVE Australia 2020 - Building distributed systems on the shoulders o...apidays LIVE Australia 2020 - Building distributed systems on the shoulders o...
apidays LIVE Australia 2020 - Building distributed systems on the shoulders o...
 
ExpressJS-Introduction.pdf
ExpressJS-Introduction.pdfExpressJS-Introduction.pdf
ExpressJS-Introduction.pdf
 
Session 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdfSession 9 Android Web Services - Part 2.pdf
Session 9 Android Web Services - Part 2.pdf
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "
 
Intro to Node
Intro to NodeIntro to Node
Intro to Node
 
Writing RESTful web services using Node.js
Writing RESTful web services using Node.jsWriting RESTful web services using Node.js
Writing RESTful web services using Node.js
 

More from Bareen Shaikh

Express Generator.pdf
Express Generator.pdfExpress Generator.pdf
Express Generator.pdf
Bareen Shaikh
 
Express JS-Routingmethod.pdf
Express JS-Routingmethod.pdfExpress JS-Routingmethod.pdf
Express JS-Routingmethod.pdf
Bareen Shaikh
 
FS_module_functions.pptx
FS_module_functions.pptxFS_module_functions.pptx
FS_module_functions.pptx
Bareen Shaikh
 
File System.pptx
File System.pptxFile System.pptx
File System.pptx
Bareen Shaikh
 
Web Server.pdf
Web Server.pdfWeb Server.pdf
Web Server.pdf
Bareen Shaikh
 
NPM.pdf
NPM.pdfNPM.pdf
NPM.pdf
Bareen Shaikh
 
NodeJs Modules1.pdf
NodeJs Modules1.pdfNodeJs Modules1.pdf
NodeJs Modules1.pdf
Bareen Shaikh
 
NodeJs Modules.pdf
NodeJs Modules.pdfNodeJs Modules.pdf
NodeJs Modules.pdf
Bareen Shaikh
 
Introduction to Node JS1.pdf
Introduction to Node JS1.pdfIntroduction to Node JS1.pdf
Introduction to Node JS1.pdf
Bareen Shaikh
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdf
Bareen Shaikh
 

More from Bareen Shaikh (10)

Express Generator.pdf
Express Generator.pdfExpress Generator.pdf
Express Generator.pdf
 
Express JS-Routingmethod.pdf
Express JS-Routingmethod.pdfExpress JS-Routingmethod.pdf
Express JS-Routingmethod.pdf
 
FS_module_functions.pptx
FS_module_functions.pptxFS_module_functions.pptx
FS_module_functions.pptx
 
File System.pptx
File System.pptxFile System.pptx
File System.pptx
 
Web Server.pdf
Web Server.pdfWeb Server.pdf
Web Server.pdf
 
NPM.pdf
NPM.pdfNPM.pdf
NPM.pdf
 
NodeJs Modules1.pdf
NodeJs Modules1.pdfNodeJs Modules1.pdf
NodeJs Modules1.pdf
 
NodeJs Modules.pdf
NodeJs Modules.pdfNodeJs Modules.pdf
NodeJs Modules.pdf
 
Introduction to Node JS1.pdf
Introduction to Node JS1.pdfIntroduction to Node JS1.pdf
Introduction to Node JS1.pdf
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdf
 

Recently uploaded

BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptxBIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
RidwanHassanYusuf
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
PsychoTech Services
 
Educational Technology in the Health Sciences
Educational Technology in the Health SciencesEducational Technology in the Health Sciences
Educational Technology in the Health Sciences
Iris Thiele Isip-Tan
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
danielkiash986
 
Nutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour TrainingNutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour Training
melliereed
 
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDFLifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Vivekanand Anglo Vedic Academy
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
zuzanka
 
Stack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 MicroprocessorStack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 Microprocessor
JomonJoseph58
 
skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)
Mohammad Al-Dhahabi
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
How to Predict Vendor Bill Product in Odoo 17
How to Predict Vendor Bill Product in Odoo 17How to Predict Vendor Bill Product in Odoo 17
How to Predict Vendor Bill Product in Odoo 17
Celine George
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
TechSoup
 
How Barcodes Can Be Leveraged Within Odoo 17
How Barcodes Can Be Leveraged Within Odoo 17How Barcodes Can Be Leveraged Within Odoo 17
How Barcodes Can Be Leveraged Within Odoo 17
Celine George
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
Krassimira Luka
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
deepaannamalai16
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
nitinpv4ai
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
EduSkills OECD
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
Steve Thomason
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 

Recently uploaded (20)

BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptxBIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
BIOLOGY NATIONAL EXAMINATION COUNCIL (NECO) 2024 PRACTICAL MANUAL.pptx
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
 
Educational Technology in the Health Sciences
Educational Technology in the Health SciencesEducational Technology in the Health Sciences
Educational Technology in the Health Sciences
 
Pharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brubPharmaceutics Pharmaceuticals best of brub
Pharmaceutics Pharmaceuticals best of brub
 
Nutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour TrainingNutrition Inc FY 2024, 4 - Hour Training
Nutrition Inc FY 2024, 4 - Hour Training
 
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDFLifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
 
Stack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 MicroprocessorStack Memory Organization of 8086 Microprocessor
Stack Memory Organization of 8086 Microprocessor
 
skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)skeleton System.pdf (skeleton system wow)
skeleton System.pdf (skeleton system wow)
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
How to Predict Vendor Bill Product in Odoo 17
How to Predict Vendor Bill Product in Odoo 17How to Predict Vendor Bill Product in Odoo 17
How to Predict Vendor Bill Product in Odoo 17
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
 
How Barcodes Can Be Leveraged Within Odoo 17
How Barcodes Can Be Leveraged Within Odoo 17How Barcodes Can Be Leveraged Within Odoo 17
How Barcodes Can Be Leveraged Within Odoo 17
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
 
Standardized tool for Intelligence test.
Standardized tool for Intelligence test.Standardized tool for Intelligence test.
Standardized tool for Intelligence test.
 
Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10Haunted Houses by H W Longfellow for class 10
Haunted Houses by H W Longfellow for class 10
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 

Middleware.pdf

  • 1. EXPRESS JS-MIDDLEWARE Prepared By: Mrs. Bareen Shaikh Assistant Professor Computer Science MIT ACSC Alandi(D) Pune
  • 2. Middleware ▪ Express is a routing and middleware web framework that has minimal functionality of its own ▪ An Express application is essentially a series of middleware function calls. ▪ 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. ▪ The next middleware function is commonly denoted by a variable named next.
  • 3. Middleware ▪ Middleware functions can perform the following tasks:  Execute any code.  Make changes to the request and the response objects.  End the request-response cycle.  Call the next middleware function in the stack.  If the current middleware function does not end the request-response cycle, it must call next to pass control to the next middleware function.  Otherwise, the request will be left hanging.
  • 4. Writing Middleware ▪ The following figure shows the elements of a middleware function call:
  • 5. Middleware function Example ▪ Following is a simple example of a middleware function called “myLogger”. ▪ This function just prints “LOGGED” when a request to the app passes through it. ▪ The middleware function is assigned to a variable named myLogger. var myLogger = function (req, res, next) { console.log('LOGGED'); next(); }
  • 6. Middleware function Example ▪ To load the middleware function, call app.use(), specifying the middleware function. ▪ For example, the following code loads the myLogger middleware function before the route to the root path (/). var express = require('express'); var app = express(); var myLogger = function (req, res, next) { console.log('LOGGED'); next() } app.use(myLogger); app.get('/', function (req, res) { res.send('Hello World!'); }); app.listen(3000);
  • 7. Middleware ▪ An Express application can use the following types of middleware:  Application-level middleware  Router-level middleware  Error-handling middleware  Built-in middleware  Third-party middleware
  • 8. Application-level middleware ▪ Connect application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions. ▪ Following example shows a middleware function with no mount path.The function is executed every time the app receives a request. var express = require('express'); var app = express(); app.use(function (req, res, next) { varT=new Date(Date.now()); var t=T.toString() console.log('Time:',t) next() }) app.listen(3000);
  • 9. Routing using use() on specified path ▪ Following example shows a middleware function mounted on the /user/:id path. app.use('/user/:id', function (req, res, next) { console.log('RequestType:', req.method) next() }) ▪ Route and its handler function using HTTP GET requests app.get('/user/:id', function (req, res, next) { res.send(‘User Information') })
  • 10. Series of middleware for any type of HTTP request app.use('/user/:id', function (req, res, next) { console.log('Request URL:', req.originalUrl) next() }, function (req, res, next) { console.log('RequestType:', req.method) res.send(req.params) next() })
  • 11. Multiple routes for a path ▪ Route handlers enable you to define multiple routes for a path. ▪ The example below defines two routes for GET requests to the /user/:id path. ▪ The second route will not cause any problems, but it will never get called because the first route ends the request-response cycle. ▪ This example shows a middleware sub-stack that handles GET requests to the /user/:id path. app.get('/user/:id', function (req, res, next) { console.log('ID:', req.params.id) next() }, function (req, res, next) { res.send('User Informtion') }) // handler for the /user/:id path, which prints the user ID app.get('/user/:id', function (req, res, next) { res.end(req.params.id) })
  • 12. call next('route') ▪ To skip the rest of the middleware functions from a router middleware stack, call next('route') to pass control to the next route. ▪ Following example shows a middleware sub-stack. app.get('/user/:id', function (req, res, next) { if (req.params.id === '0') next('route') else next() }, function (req, res, next) { res.send(‘series middleware executed') }) app.get('/user/:id', function (req, res, next) { res.send('skipped and next middleware executed') })
  • 13. Middleware Using Array ▪ Middleware can also be declared in an array for reusability. Example as follows function OriginalUrl (req, res, next) { console.log('Request URL:', req.originalUrl) next() } function Method (req, res, next) { console.log('RequestType:', req.method) next() } var arr= [OriginalUrl, Method] app.get('/user/:id', arr, function (req, res, next) { res.send('User Information') })
  • 14. Router Level Middleware ▪ Router-level middleware works in the same way as application-level middleware. ▪ Except it is bound to an instance of  express.Router(). ▪ var router = express.Router() Load router-level middleware by using  router.use() and  router.METHOD() ▪ Example on next slide of router level middleware. ▪ To skip the rest of the router’s middleware functions, call next('router') to pass control back out of the router instance.
  • 15. Router Level Middleware const express = require('express'); const app = express(); const router = express.Router() router.use((req,res,next)=>{ console.log("Time:",new Date()) next() }) router.get("/user/:id",(req,res,next)=>{ console.log('Request URL:', req.originalUrl) next() },(req,res,next)=>{ console.log('RequestType:', req.method) next() },(req,res)=>{ res.json({ status:true, id:req.params.id }) }) app.use('/',router) app.listen(3000,(req,res)=>{ console.log('server running on 3000') })
  • 16. Error-handling middleware ▪ Error-handling middleware always takes four arguments. ▪ Provide four arguments to identify it as an error-handling middleware function. ▪ Even if don’t need to use the next object, you must specify it to maintain the signature. ▪ Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors. ▪ Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next)): app.use(function (err, req, res, next) { console.error(err.stack) res.status(500).send('Something broke!') })
  • 17. Built in Midddleware ▪ Express 4.0x no longer depends on Connect. ▪ The middleware functions that were previously included with Express are now in separate modules; see the https://github.com/senchalabs/connect#middleware ▪ Express has the following built-in middleware functions:  express.static serves static assets such as HTML files, images, and so on.  express.json parses incoming requests with JSON payloads. Available with Express 4.16.0+  express.urlencoded parses incoming requests with URL- encoded payloads. Available with Express 4.16.0+ ▪ Also check ▪ https://expressjs.com/en/resources/middleware.html