SlideShare a Scribd company logo
1 of 17
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.pdfArthyR3
 
Express: A Jump-Start
Express: A Jump-StartExpress: A Jump-Start
Express: A Jump-StartNaveen 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 javascriptEldar 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 serverSpike Brehm
 
Node js introduction
Node js introductionNode js introduction
Node js introductionAlex Su
 
Workshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIWorkshop 13: AngularJS Parte II
Workshop 13: AngularJS Parte IIVisual Engineering
 
Emberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applicationsEmberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applicationsColdFusionConference
 
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 .NETGianluca 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 2013Laurent_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 jsFrancois Zaninotto
 
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 jsAhmed Assaf
 
apidays LIVE Australia - Building distributed systems on the shoulders of gia...
apidays LIVE Australia - Building distributed systems on the shoulders of gia...apidays LIVE Australia - Building distributed systems on the shoulders of gia...
apidays LIVE Australia - Building distributed systems on the shoulders of gia...apidays
 
ExpressJS-Introduction.pdf
ExpressJS-Introduction.pdfExpressJS-Introduction.pdf
ExpressJS-Introduction.pdfBareen 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.pdfEngmohammedAlzared
 
"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
 
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.jsFDConf
 

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 - Building distributed systems on the shoulders of gia...
apidays LIVE Australia - Building distributed systems on the shoulders of gia...apidays LIVE Australia - Building distributed systems on the shoulders of gia...
apidays LIVE Australia - Building distributed systems on the shoulders of gia...
 
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.pdfBareen Shaikh
 
Express JS-Routingmethod.pdf
Express JS-Routingmethod.pdfExpress JS-Routingmethod.pdf
Express JS-Routingmethod.pdfBareen Shaikh
 
FS_module_functions.pptx
FS_module_functions.pptxFS_module_functions.pptx
FS_module_functions.pptxBareen Shaikh
 
Introduction to Node JS1.pdf
Introduction to Node JS1.pdfIntroduction to Node JS1.pdf
Introduction to Node JS1.pdfBareen Shaikh
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdfBareen 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

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 

Recently uploaded (20)

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 

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