SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Downloaden Sie, um offline zu lesen
Kickstart NodeJS
Yashprit Singh
@yashprit
Agenda
1. Middleware Concept
2. Connect Middleware with Example
3. Express Middleware.
4. Express Philosophy.
5. Express Cool Features.
What is Middleware in NodeJS ?
The middleware is called as a chain of functions, with order based on middleware
definition order(time) with matching routes (if applicable).
e.g. req and res objects are travelling through chain so you can
reuse/improve/modify data in them along the chain.
/* This is only for demonstration purpose*/
function(req, res, next) {
req.name = “samething”;
next(/* err and/or output */)
}
Middleware cont.
This is sometime also called as Pipelines. Pipelines are everywhere, under
various forms, uses and purposes. Generically, a Pipeline is a series of processing
units connected together, where the output of one unit is the input for the next one.
(In Node.js, this often means a series of functions in the form.)
If your middleware should return a response, just do so. If it shouldn't, it's implied
that some later middleware should return a response. If you need to pass along
data to that later part of the process, you should attach it to an appropriate part of
the request object req.
P.S. Don’t confuse here about pipe(), thats belongs to another hero streams, streams are better
suited to process flowing data
Middleware cont.
For example,
1. The bundled bodyParser middleware is responsible for populating req.
rawBody and req.body based on the contents of the request body.
2. The bundled basicAuth middleware populates req.remoteUser based on the
HTTP authentication.
Middleware Cont.
Two general use cases for middleware :-
● Generic :- it will apply to every single request. Each middleware have to call
next() inside, if it wants to proceed to next middleware.
● Specific :- When you use app.get('/path', function(...) this actual function is
middleware as well, just inline defined
The chain order is based on definition order. So it is important to define
middleware in sync manner or order-reliable async manner. Otherwise different
order of middleware can break logic.
Middleware : Connect
● Node.js itself offers an HTTP module, whose createServer method returns an
object that you can use to respond to HTTP requests.
● That object inherits the http.Server prototype.
Connect Middleware
From the README:
Connect is an extensible HTTP server framework for node, providing high
performance "plugins" known as middleware.
More specifically, connect wraps the Server, ServerRequest, and
ServerResponse objects of node.js' standard httpmodule, giving them a few nice
extra features, one of which is allowing the Server object to use a stack of
middleware.
Connect Middleware Framework
● Connect has 18 bundled middleware and a rich selection of 3rd-party
middleware..
● That's why Connect describes itself as a "middleware framework," and is
often analogized to Ruby's Rack.
Example : Creating Simple Middleware
function uselessMiddleware(req, res, next) {
next()
}
A middleware can also signal an error by passing it as the first argument to next:
// A middleware that simply interrupts every request
function worseThanUselessMiddleware(req, res, next) {
next("Hey are you busy?")
}
When a middleware returns an error like this, all subsequent middleware will be
skipped until connect can find an error handler.
Adding middleware stack for server
To add a middleware to the stack of middleware for a server, we use it like so:
connect = require('connect')
stephen = connect.createServer()
stephen.use(worseThanUselessMiddleware)
Finally, you can also specify a path prefix when adding a middleware, and the
middleware will only be asked to handle requests that match the prefix:
connect = require('connect')
bob = connect.createServer()
bob.use('/attention', worseThanUselessMiddleware)
URL based authentication policy
function authenticateUrls(urls /* basicAuth args*/) {
basicAuthArgs = Array.slice.call(arguments, 1)
basicAuth = require('connect').basicAuth.apply(basicAuthArgs)
function authenticate(req, res, next) {
// Warning! assumes that urls is amenable to iteration
for (var pattern in urls) {
if (req.path.match(pattern)) {
basicAuth(req, res, next)
return
}
}
next()
}
return authenticate
}
Role base authorization
function authorizeUrls(urls, roles) {
function authorize(req, res, next) {
for (var pattern in urls) {
if (req.path.match(pattern)) {
for (var role in urls[pattern]) {
if (users[req.remoteUser].indexOf(role) < 0) {
next(new Error("unauthorized"))
return
}
}
}
}
next()
}
return authorize
}
Error handling
email = require('node_mailer')
function emailErrorNotifier(generic_opts, escalate) {
function notifyViaEmail(err, req, res, next) {
if (err) {
var opts = {
subject: "ERROR: " + err.constructor.name,
body: err.stack,
}
opts.__proto__ = generic_opts
email.send(opts, escalate)
}
next()
}
}
Putting it all together
private_urls = {
'^/attention': ['coworker', 'girlfriend'],
'^/bank_balance': ['me'],
}
roles = {
stephen: ['me'],
erin: ['girlfriend'],
judd: ['coworker'],
bob: ['coworker'],
}
passwords = {
me: 'doofus',
erin: 'greatest',
judd: 'daboss',
bob: 'anachronistic discomBOBulation',
}
function authCallback(name, password) {
return passwords[name] === password
}
stephen = require('connect').createServer()
stephen.use(authenticateUrls(private_urls,
authCallback))
stephen.use(authorizeUrls(private_urls, roles))
stephen.use('/attention',
worseThanUselessMiddleware)
stephen.use(emailErrorNotifier({to:
'stephen@betsmartmedia.com'}))
stephen.use('/bank_balance', function (req, res,
next) {
res.end("Don't be Seb-ish")
})
stephen.use('/', function (req, res, next) {
res.end("I'm out of coffee")
})
List of common uses connect middlewares
● logger request logger with custom format
support
● csrf Cross-site request forgery protection
● compress Gzip compression middleware
● basicAuth basic http authentication
● bodyParser extensible request body parser
● json application/json parser
● multipart multipart/form-data parser
● timeout request timeouts
● cookieParser cookie parser
● session session management support with
bundled MemoryStore
● cookieSession cookie-based session support
● methodOverride faux HTTP method support
● favicon efficient favicon server (with default
icon)
● query automatic querystring parser, populating
req.query
● errorHandler flexible error handler
Middleware: Express
Express does to Connect what Connect does to the http module: It offers a
createServer method that extends Connect's Server prototype. So all of the
functionality of Connect is there,plus view rendering and a handy DSL for
describing routes. Ruby's Sinatra is a good analogy.
Philosophy behind ExpressJS
This is probably one of the most popular frameworks in the Node.js community of
coders right now. The core philosophy behind ExpressJS is to offer an application
framework for single or multi-page web apps, using views and template engine.
The Express.js framework also includes a multitude of utilities to work with HTTP
and building APIs. The pluggable middleware in the framework provides a great
way to add elements, such as passportjs, as you need them.
Cool feature 1: routing
Routing is a way to map different
requests to specific handlers.
var express = require("express");
var http = require("http");
var app = express();
app.all("*", function(request, response, next) {
response.writeHead(200, { "Content-Type":
"text/plain" });
next();
});
app.get("/", function(request, response) {
response.end("Welcome to the homepage!");
});
app.get("/about", function(request, response) {
response.end("Welcome to the about page!");
});
app.get("*", function(request, response) {
response.end("404!");
});
http.createServer(app).listen(1337);
Cool feature 2: request handling
Express augments the request and response objects that you're passed in every
request handler.
response.redirect("/hello/anime");
response.redirect("http://www.myanimelist.net");
response.redirect(301, "http://www.anime.org"); // HTTP status code 301
This isn't in vanilla Node and it's also absent from Connect, but Express adds this
stuff. It adds things like sendFile which lets you just send a whole file:
response.sendFile("/path/to/anime.mp4");
The request gets a number of cool properties, like request.ip to get the IP address
and request.files to get uploaded files.
Cool feature 3: views
More features? Oh, Express, I'm blushing.
Express can handle views. It's not too bad. Here's what the setup looks like:
// Start Express
var express = require("express");
var app = express();
// Set the view directory to /views
app.set("views", __dirname + "/views");
// Let's use the Jade templating language
app.set("view engine", "jade");
The first block is the same as always. Then we say "our views are in a folder
called 'views'".
Bonus cool feature: everything from
Connect and Node
I want to remind you that Express is built on top of Connect which is built on top of
Node. This means that all Connect middleware works with Express. This is useful!
For example:
var express = require("express");
var app = express();
app.use(express.logger()); // Inherited from Connect
app.get("/", function(req, res) {
res.send("anime");
});
app.listen(1337);
Folder Structure : My Preference
/public
/images (there are several images exported from Photoshop)
/javascripts
/stylesheets
/style.css
/style.less (imports home.less and inner.less)
/routes
/index.js
/app
/views
/index.ejs (home page)
/inner.ejs (template for every other page of the site)
/controller
/model
/app.js
/package.json
Q-A
Thank You
@yashprit
MVC in Express
var express = require('express');
,app = express()
,fs = require('fs')
// database connection
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb');
// some environment variables
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(app.router);
app.use(express.static(path.join(__dirname,
'public')));
// dynamically include routes (Controller)
fs.readdirSync('./controllers').forEach(function
(file) {
if(file.substr(-3) == '.js') {
route = require('./controllers/' + file);
route.controller(app);
}
});
http.createServer(app).listen(app.get('port'),
function(){
console.log('Express server listening on port ' +
app.get('port'));
});
NodeJS HTTP Abstraction
Express wonderfull middleware
Philosophy behind ExpressJS
MVC in NodeJS
http://evanhahn.com/understanding-express/
NodeJS HTTP Abstraction
http://stackoverflow.com/questions/5284340/what-is-node-js-connect-express-and-
middleware
http://expressjs.com/guide.html
https://github.com/senchalabs/connect
http://stackoverflow.com/questions/17750308/middleware-design-pattern-in-node-
js-connect
http://expressjs.com/2x/guide.html#middleware
http://stackoverflow.com/questions/6893876/nodejs-and-connect-next-functionality
http://www.mariocasciaro.me/the-strange-world-of-node-js-design-patterns
http://philsversion.com/2011/08/24/lessons-learnt-from-my-first-node-js-project/
http://stella.laurenzo.org/2011/03/bulletproof-node-js-coding/
http://code.tutsplus.com/tutorials/meet-the-connect-framework--net-31220
http://stephensugden.com/middleware_guide/
http://howtonode.org/connect-it

Weitere Àhnliche Inhalte

Was ist angesagt?

What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?Simplilearn
 
Node.js File system & Streams
Node.js File system & StreamsNode.js File system & Streams
Node.js File system & StreamsEyal Vardi
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass SlidesNir Kaufman
 
React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXLRob Gietema
 
Node JS Crash Course
Node JS Crash CourseNode JS Crash Course
Node JS Crash CourseHaim Michael
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRob O'Doherty
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootJosué Neis
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Visual Engineering
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafThymeleaf
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 
Node js overview
Node js overviewNode js overview
Node js overviewEyal Vardi
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewShahed Chowdhuri
 
Express JS Middleware Tutorial
Express JS Middleware TutorialExpress JS Middleware Tutorial
Express JS Middleware TutorialSimplilearn
 

Was ist angesagt? (20)

What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
Node.js File system & Streams
Node.js File system & StreamsNode.js File system & Streams
Node.js File system & Streams
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
Express JS
Express JSExpress JS
Express JS
 
React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXL
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Node JS Crash Course
Node JS Crash CourseNode JS Crash Course
Node JS Crash Course
 
Node.js Basics
Node.js Basics Node.js Basics
Node.js Basics
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Node js overview
Node js overviewNode js overview
Node js overview
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 
Express JS Middleware Tutorial
Express JS Middleware TutorialExpress JS Middleware Tutorial
Express JS Middleware Tutorial
 

Ähnlich wie Express node js

Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Mindfire Solutions
 
Divide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsSebastian Springer
 
sveltekit-en.pdf
sveltekit-en.pdfsveltekit-en.pdf
sveltekit-en.pdfssuser65180a
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNicole Gomez
 
ExpressJS and REST API.pptx
ExpressJS and REST API.pptxExpressJS and REST API.pptx
ExpressJS and REST API.pptxGovardhan Bhavani
 
JavaEE6 my way
JavaEE6 my wayJavaEE6 my way
JavaEE6 my wayNicola Pedot
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.jsdavidchubbs
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing Techglyphs
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083Divyam Pateriya
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal Maniar
 
Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN StackRob Davarnia
 
.NET Core, ASP.NET Core Course, Session 18
 .NET Core, ASP.NET Core Course, Session 18 .NET Core, ASP.NET Core Course, Session 18
.NET Core, ASP.NET Core Course, Session 18aminmesbahi
 
ExpressJS-Introduction.pdf
ExpressJS-Introduction.pdfExpressJS-Introduction.pdf
ExpressJS-Introduction.pdfBareen Shaikh
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.jsAyush Mishra
 
OpenDMS - the first 2 weeks
OpenDMS - the first 2 weeksOpenDMS - the first 2 weeks
OpenDMS - the first 2 weeksJPC Hanson
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0megrhi haikel
 
Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Maarten Balliauw
 

Ähnlich wie Express node js (20)

Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)
 
Divide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.js
 
sveltekit-en.pdf
sveltekit-en.pdfsveltekit-en.pdf
sveltekit-en.pdf
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language Analysis
 
ExpressJS and REST API.pptx
ExpressJS and REST API.pptxExpressJS and REST API.pptx
ExpressJS and REST API.pptx
 
JavaEE6 my way
JavaEE6 my wayJavaEE6 my way
JavaEE6 my way
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
 
NodeJS @ ACS
NodeJS @ ACSNodeJS @ ACS
NodeJS @ ACS
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN Stack
 
.NET Core, ASP.NET Core Course, Session 18
 .NET Core, ASP.NET Core Course, Session 18 .NET Core, ASP.NET Core Course, Session 18
.NET Core, ASP.NET Core Course, Session 18
 
ExpressJS-Introduction.pdf
ExpressJS-Introduction.pdfExpressJS-Introduction.pdf
ExpressJS-Introduction.pdf
 
Introduction to Node.JS
Introduction to Node.JSIntroduction to Node.JS
Introduction to Node.JS
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.js
 
OpenDMS - the first 2 weeks
OpenDMS - the first 2 weeksOpenDMS - the first 2 weeks
OpenDMS - the first 2 weeks
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0
 
Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...
 

KĂŒrzlich hochgeladen

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 

KĂŒrzlich hochgeladen (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

Express node js

  • 2. Agenda 1. Middleware Concept 2. Connect Middleware with Example 3. Express Middleware. 4. Express Philosophy. 5. Express Cool Features.
  • 3. What is Middleware in NodeJS ? The middleware is called as a chain of functions, with order based on middleware definition order(time) with matching routes (if applicable). e.g. req and res objects are travelling through chain so you can reuse/improve/modify data in them along the chain. /* This is only for demonstration purpose*/ function(req, res, next) { req.name = “samething”; next(/* err and/or output */) }
  • 4. Middleware cont. This is sometime also called as Pipelines. Pipelines are everywhere, under various forms, uses and purposes. Generically, a Pipeline is a series of processing units connected together, where the output of one unit is the input for the next one. (In Node.js, this often means a series of functions in the form.) If your middleware should return a response, just do so. If it shouldn't, it's implied that some later middleware should return a response. If you need to pass along data to that later part of the process, you should attach it to an appropriate part of the request object req. P.S. Don’t confuse here about pipe(), thats belongs to another hero streams, streams are better suited to process flowing data
  • 5. Middleware cont. For example, 1. The bundled bodyParser middleware is responsible for populating req. rawBody and req.body based on the contents of the request body. 2. The bundled basicAuth middleware populates req.remoteUser based on the HTTP authentication.
  • 6. Middleware Cont. Two general use cases for middleware :- ● Generic :- it will apply to every single request. Each middleware have to call next() inside, if it wants to proceed to next middleware. ● Specific :- When you use app.get('/path', function(...) this actual function is middleware as well, just inline defined The chain order is based on definition order. So it is important to define middleware in sync manner or order-reliable async manner. Otherwise different order of middleware can break logic.
  • 7. Middleware : Connect ● Node.js itself offers an HTTP module, whose createServer method returns an object that you can use to respond to HTTP requests. ● That object inherits the http.Server prototype.
  • 8. Connect Middleware From the README: Connect is an extensible HTTP server framework for node, providing high performance "plugins" known as middleware. More specifically, connect wraps the Server, ServerRequest, and ServerResponse objects of node.js' standard httpmodule, giving them a few nice extra features, one of which is allowing the Server object to use a stack of middleware.
  • 9. Connect Middleware Framework ● Connect has 18 bundled middleware and a rich selection of 3rd-party middleware.. ● That's why Connect describes itself as a "middleware framework," and is often analogized to Ruby's Rack.
  • 10. Example : Creating Simple Middleware function uselessMiddleware(req, res, next) { next() } A middleware can also signal an error by passing it as the first argument to next: // A middleware that simply interrupts every request function worseThanUselessMiddleware(req, res, next) { next("Hey are you busy?") } When a middleware returns an error like this, all subsequent middleware will be skipped until connect can find an error handler.
  • 11. Adding middleware stack for server To add a middleware to the stack of middleware for a server, we use it like so: connect = require('connect') stephen = connect.createServer() stephen.use(worseThanUselessMiddleware) Finally, you can also specify a path prefix when adding a middleware, and the middleware will only be asked to handle requests that match the prefix: connect = require('connect') bob = connect.createServer() bob.use('/attention', worseThanUselessMiddleware)
  • 12. URL based authentication policy function authenticateUrls(urls /* basicAuth args*/) { basicAuthArgs = Array.slice.call(arguments, 1) basicAuth = require('connect').basicAuth.apply(basicAuthArgs) function authenticate(req, res, next) { // Warning! assumes that urls is amenable to iteration for (var pattern in urls) { if (req.path.match(pattern)) { basicAuth(req, res, next) return } } next() } return authenticate }
  • 13. Role base authorization function authorizeUrls(urls, roles) { function authorize(req, res, next) { for (var pattern in urls) { if (req.path.match(pattern)) { for (var role in urls[pattern]) { if (users[req.remoteUser].indexOf(role) < 0) { next(new Error("unauthorized")) return } } } } next() } return authorize }
  • 14. Error handling email = require('node_mailer') function emailErrorNotifier(generic_opts, escalate) { function notifyViaEmail(err, req, res, next) { if (err) { var opts = { subject: "ERROR: " + err.constructor.name, body: err.stack, } opts.__proto__ = generic_opts email.send(opts, escalate) } next() } }
  • 15. Putting it all together private_urls = { '^/attention': ['coworker', 'girlfriend'], '^/bank_balance': ['me'], } roles = { stephen: ['me'], erin: ['girlfriend'], judd: ['coworker'], bob: ['coworker'], } passwords = { me: 'doofus', erin: 'greatest', judd: 'daboss', bob: 'anachronistic discomBOBulation', } function authCallback(name, password) { return passwords[name] === password } stephen = require('connect').createServer() stephen.use(authenticateUrls(private_urls, authCallback)) stephen.use(authorizeUrls(private_urls, roles)) stephen.use('/attention', worseThanUselessMiddleware) stephen.use(emailErrorNotifier({to: 'stephen@betsmartmedia.com'})) stephen.use('/bank_balance', function (req, res, next) { res.end("Don't be Seb-ish") }) stephen.use('/', function (req, res, next) { res.end("I'm out of coffee") })
  • 16. List of common uses connect middlewares ● logger request logger with custom format support ● csrf Cross-site request forgery protection ● compress Gzip compression middleware ● basicAuth basic http authentication ● bodyParser extensible request body parser ● json application/json parser ● multipart multipart/form-data parser ● timeout request timeouts ● cookieParser cookie parser ● session session management support with bundled MemoryStore ● cookieSession cookie-based session support ● methodOverride faux HTTP method support ● favicon efficient favicon server (with default icon) ● query automatic querystring parser, populating req.query ● errorHandler flexible error handler
  • 17. Middleware: Express Express does to Connect what Connect does to the http module: It offers a createServer method that extends Connect's Server prototype. So all of the functionality of Connect is there,plus view rendering and a handy DSL for describing routes. Ruby's Sinatra is a good analogy.
  • 18. Philosophy behind ExpressJS This is probably one of the most popular frameworks in the Node.js community of coders right now. The core philosophy behind ExpressJS is to offer an application framework for single or multi-page web apps, using views and template engine. The Express.js framework also includes a multitude of utilities to work with HTTP and building APIs. The pluggable middleware in the framework provides a great way to add elements, such as passportjs, as you need them.
  • 19. Cool feature 1: routing Routing is a way to map different requests to specific handlers. var express = require("express"); var http = require("http"); var app = express(); app.all("*", function(request, response, next) { response.writeHead(200, { "Content-Type": "text/plain" }); next(); }); app.get("/", function(request, response) { response.end("Welcome to the homepage!"); }); app.get("/about", function(request, response) { response.end("Welcome to the about page!"); }); app.get("*", function(request, response) { response.end("404!"); }); http.createServer(app).listen(1337);
  • 20. Cool feature 2: request handling Express augments the request and response objects that you're passed in every request handler. response.redirect("/hello/anime"); response.redirect("http://www.myanimelist.net"); response.redirect(301, "http://www.anime.org"); // HTTP status code 301 This isn't in vanilla Node and it's also absent from Connect, but Express adds this stuff. It adds things like sendFile which lets you just send a whole file: response.sendFile("/path/to/anime.mp4"); The request gets a number of cool properties, like request.ip to get the IP address and request.files to get uploaded files.
  • 21. Cool feature 3: views More features? Oh, Express, I'm blushing. Express can handle views. It's not too bad. Here's what the setup looks like: // Start Express var express = require("express"); var app = express(); // Set the view directory to /views app.set("views", __dirname + "/views"); // Let's use the Jade templating language app.set("view engine", "jade"); The first block is the same as always. Then we say "our views are in a folder called 'views'".
  • 22. Bonus cool feature: everything from Connect and Node I want to remind you that Express is built on top of Connect which is built on top of Node. This means that all Connect middleware works with Express. This is useful! For example: var express = require("express"); var app = express(); app.use(express.logger()); // Inherited from Connect app.get("/", function(req, res) { res.send("anime"); }); app.listen(1337);
  • 23. Folder Structure : My Preference /public /images (there are several images exported from Photoshop) /javascripts /stylesheets /style.css /style.less (imports home.less and inner.less) /routes /index.js /app /views /index.ejs (home page) /inner.ejs (template for every other page of the site) /controller /model /app.js /package.json
  • 25. MVC in Express var express = require('express'); ,app = express() ,fs = require('fs') // database connection var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/mydb'); // some environment variables app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // dynamically include routes (Controller) fs.readdirSync('./controllers').forEach(function (file) { if(file.substr(-3) == '.js') { route = require('./controllers/' + file); route.controller(app); } }); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
  • 26. NodeJS HTTP Abstraction Express wonderfull middleware Philosophy behind ExpressJS MVC in NodeJS http://evanhahn.com/understanding-express/