SlideShare a Scribd company logo
1 of 17
express
high class web development for nodeJS




             Alok Guha
What‘s express?

• nodeJS based web framework
• inspired by Sinatra
• asynchronous

    var app = express.createServer();
    app.get('/', function(req, res){
    res.send('Hello World');
    });

    app.listen(3000);
Installation

• Install nodeJS
   $ brew install node


• Install npm (node package manager)
  $ brew install npm


• Install express
  $ npm install express
Routing
app.get('/users/:id?', function(req, res) {
var id = req.params.id;
res.send(id ? 'user ' + id : 'users');
});

app.post('/users/:id.:format', function(req, res) {
var id = req.params.id;
var format = req.params.format;
res.send('user: ' + id + ' format: ' + format);
});

app.get('/file/*.*', function(req, res) {
res.send('path: ' + req.params);
});
Connect / Middlewares

• Connect is a middleware framework
• Similar to Rack
• A middleware is simply a function with
  three arguments: request, response, next

     var helloWorld = function(req, res, next) {
     res.writeHead(200, { 'Content-Type':
       'text/plain' });
     res.end('hello world');
     }
Middleware

var loadUser = function(req, res, next) {
var id = req.params.id;
var user = db.loadUser(id); // fetch user from db
if (user) {
req.user = user;
next();
} else {
next(new Error('Failed to load user ' + id));
}
}

app.get('/user/:id', loadUser, function(req, res) {
res.send('Viewing user ' + req.user.name);
});
HTTP POST

<form method="post" action="/">
<input type="text" name="user[name]" />
<input type="submit" value="Submit" />
</form>

bodyDecoder middleware for POST params:

app.use(express.bodyDecoder());

app.post('/', function(req, res){
console.log(req.body.user);
res.redirect('back');
});
HTTP PUT/DELETE

<form method="post" action="/">
<input type="hidden" name="_method" value="put" />
<input type="text" name="user[name]" />
<input type="submit" value="Submit" />
</form>

bodyDecoder and methodOverride:

app.use(express.bodyDecoder());
app.use(express.methodOverride());

app.post('/', function(req, res){
console.log(req.body.user);
res.redirect('back');
});
View Rendering
• Concept: Layout, view and partials
• Template Engines: Jade, Haml, EJS, …
• View variables are passed to render

   app.set('view engine', 'jade');

   app.get('/', function(req, res){
   res.render('index.haml', {
   layout: 'app', // -> app.jade
   locals: { title: 'This is my app' }
   });
   });
Jade - Template Engine
!!!
html(lang="en")
head
title= pageTitle
:javascript
| if (foo)
|
bar()
body
h1 Jade - node template engine
#container
- if (youAreUsingJade)
p You are amazing
- else
p Get on it!
.comments
= partial('comment', comments)
Helpers

app.dynamicHelpers({
flashes: function(req, res) {
var msg = req.flash('message');
return msg.length ? '<p id="msg">' + msg + '</p>': '';
}
});

app.helpers({
linkTo: function(text, url) {
return '<a href=' + url + '>' + text + '</a>';
},
name: function(user) {
return user.firstName + ' ' + user.lastName;
}
});
Sessions

• Currently depending on cookies
• Store implementations: Memory, Redis, …

    app.use(express.cookieDecoder());
    app.use(express.session());

    app.post('/cart/add', function(req, res) {
    req.session.items = req.body.items;
    res.redirect('back');
    });

    app.get('/cart', function(req, res) {
    var items = req.session.items;
    res.render('cart', { locals: { items: items } });
    });
Error Handling

The app.error() method receives exceptions
thrown within a route, or passed to next(err)

app.use(express.errorHandler({ dumpExceptions: true }));

app.error(function(err, req, res, next) {
if (err instanceof Unauthorized) {
res.render('401.jade', { locals: { error: err } });
} else if (err instanceof NotFound) {
res.render('404.jade');
} else {
next(err);
}
});
Why express?

•   Full-blown feature set
•   Built on Connect
•   Good documentation
•   Lots of examples
•   Many extensions
•   Nice community
Going further…

• http://expressjs.com/guide.html
• http://expressjs.com/api.html
• http://senchalabs.github.com/connect/
• http://github.com/senchalabs/connect/wiki
• http://github.com/visionmedia/express/tree/
  master/examples/
• https://github.com/dbloete/Codeshelver
Express JS
Express JS

More Related Content

What's hot

What's hot (20)

NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Web api
Web apiWeb api
Web api
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular Components
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Going realtime with Socket.IO
Going realtime with Socket.IOGoing realtime with Socket.IO
Going realtime with Socket.IO
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Rest api with node js and express
Rest api with node js and expressRest api with node js and express
Rest api with node js and express
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 

Viewers also liked

Express js clean-controller
Express js clean-controllerExpress js clean-controller
Express js clean-controllerAsia Tyshchenko
 
Node-IL Meetup 12/2
Node-IL Meetup 12/2Node-IL Meetup 12/2
Node-IL Meetup 12/2Ynon Perek
 
Nodejs mongoose
Nodejs mongooseNodejs mongoose
Nodejs mongooseFin Chen
 
Mongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsMongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsPallavi Srivastava
 
Getting Started With MongoDB and Mongoose
Getting Started With MongoDB and MongooseGetting Started With MongoDB and Mongoose
Getting Started With MongoDB and MongooseYnon Perek
 
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
 
Trends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science BereichTrends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science BereichAWS Germany
 
Mongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is BrightMongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is Brightaaronheckmann
 
Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppEdureka!
 
Architecting large Node.js applications
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applicationsSergi Mansilla
 
3 Facts & Insights to Master the Work Ahead in Insurance
3 Facts & Insights to Master the Work Ahead in Insurance3 Facts & Insights to Master the Work Ahead in Insurance
3 Facts & Insights to Master the Work Ahead in InsuranceCognizant
 
Cognizant's HCM Capabilities
Cognizant's HCM CapabilitiesCognizant's HCM Capabilities
Cognizant's HCM CapabilitiesArlene DeMita
 
50 Ways To Understand The Digital Customer Experience
50 Ways To Understand The Digital Customer Experience50 Ways To Understand The Digital Customer Experience
50 Ways To Understand The Digital Customer ExperienceCognizant
 
Cognizant organizational culture and structure
Cognizant organizational culture and structureCognizant organizational culture and structure
Cognizant organizational culture and structureSOuvagya Kumar Jena
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 

Viewers also liked (16)

Express js clean-controller
Express js clean-controllerExpress js clean-controller
Express js clean-controller
 
React js
React jsReact js
React js
 
Node-IL Meetup 12/2
Node-IL Meetup 12/2Node-IL Meetup 12/2
Node-IL Meetup 12/2
 
Nodejs mongoose
Nodejs mongooseNodejs mongoose
Nodejs mongoose
 
Mongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsMongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node js
 
Getting Started With MongoDB and Mongoose
Getting Started With MongoDB and MongooseGetting Started With MongoDB and Mongoose
Getting Started With MongoDB and Mongoose
 
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
 
Trends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science BereichTrends und Anwendungsbeispiele im Life Science Bereich
Trends und Anwendungsbeispiele im Life Science Bereich
 
Mongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is BrightMongoose v3 :: The Future is Bright
Mongoose v3 :: The Future is Bright
 
Node JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web AppNode JS Express : Steps to Create Restful Web App
Node JS Express : Steps to Create Restful Web App
 
Architecting large Node.js applications
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applications
 
3 Facts & Insights to Master the Work Ahead in Insurance
3 Facts & Insights to Master the Work Ahead in Insurance3 Facts & Insights to Master the Work Ahead in Insurance
3 Facts & Insights to Master the Work Ahead in Insurance
 
Cognizant's HCM Capabilities
Cognizant's HCM CapabilitiesCognizant's HCM Capabilities
Cognizant's HCM Capabilities
 
50 Ways To Understand The Digital Customer Experience
50 Ways To Understand The Digital Customer Experience50 Ways To Understand The Digital Customer Experience
50 Ways To Understand The Digital Customer Experience
 
Cognizant organizational culture and structure
Cognizant organizational culture and structureCognizant organizational culture and structure
Cognizant organizational culture and structure
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 

Similar to Express JS

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
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & ExpressChristian Joudrey
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by expressShawn Meng
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsBastian Hofmann
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfArthyR3
 
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
 
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
 
Emberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applicationsEmberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applicationsColdFusionConference
 
Real Time App with Node.js
Real Time App with Node.jsReal Time App with Node.js
Real Time App with Node.jsJxck Jxck
 
Node js introduction
Node js introductionNode js introduction
Node js introductionAlex Su
 
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
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in SwiftPeter Friese
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.jsdavidchubbs
 
node.js and the AR.Drone: building a real-time dashboard using socket.io
node.js and the AR.Drone: building a real-time dashboard using socket.ionode.js and the AR.Drone: building a real-time dashboard using socket.io
node.js and the AR.Drone: building a real-time dashboard using socket.ioSteven Beeckman
 
Nodejs do teste de unidade ao de integração
Nodejs  do teste de unidade ao de integraçãoNodejs  do teste de unidade ao de integração
Nodejs do teste de unidade ao de integraçãoVinícius Pretto da Silva
 

Similar to Express JS (20)

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
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & Express
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by express
 
Mashing up JavaScript
Mashing up JavaScriptMashing up JavaScript
Mashing up JavaScript
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web Apps
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
 
Pengenalan blaast platform sdk
Pengenalan blaast platform sdkPengenalan blaast platform sdk
Pengenalan blaast platform sdk
 
Reduxing like a pro
Reduxing like a proReduxing like a pro
Reduxing like a pro
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
Node.js server-side rendering
Node.js server-side renderingNode.js server-side rendering
Node.js server-side rendering
 
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
 
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
 
Emberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applicationsEmberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applications
 
Real Time App with Node.js
Real Time App with Node.jsReal Time App with Node.js
Real Time App with Node.js
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
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
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in Swift
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
node.js and the AR.Drone: building a real-time dashboard using socket.io
node.js and the AR.Drone: building a real-time dashboard using socket.ionode.js and the AR.Drone: building a real-time dashboard using socket.io
node.js and the AR.Drone: building a real-time dashboard using socket.io
 
Nodejs do teste de unidade ao de integração
Nodejs  do teste de unidade ao de integraçãoNodejs  do teste de unidade ao de integração
Nodejs do teste de unidade ao de integração
 

More from Alok Guha

Aglie estimation and planning
Aglie estimation and planningAglie estimation and planning
Aglie estimation and planningAlok Guha
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script PromiseAlok Guha
 
Design patterns
Design patternsDesign patterns
Design patternsAlok Guha
 

More from Alok Guha (6)

Aglie estimation and planning
Aglie estimation and planningAglie estimation and planning
Aglie estimation and planning
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
 
Q unit
Q unitQ unit
Q unit
 
Jasmine
JasmineJasmine
Jasmine
 
Design patterns
Design patternsDesign patterns
Design patterns
 
NodeJS
NodeJSNodeJS
NodeJS
 

Recently uploaded

Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 

Recently uploaded (20)

Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 

Express JS

  • 1. express high class web development for nodeJS Alok Guha
  • 2. What‘s express? • nodeJS based web framework • inspired by Sinatra • asynchronous var app = express.createServer(); app.get('/', function(req, res){ res.send('Hello World'); }); app.listen(3000);
  • 3. Installation • Install nodeJS $ brew install node • Install npm (node package manager) $ brew install npm • Install express $ npm install express
  • 4. Routing app.get('/users/:id?', function(req, res) { var id = req.params.id; res.send(id ? 'user ' + id : 'users'); }); app.post('/users/:id.:format', function(req, res) { var id = req.params.id; var format = req.params.format; res.send('user: ' + id + ' format: ' + format); }); app.get('/file/*.*', function(req, res) { res.send('path: ' + req.params); });
  • 5. Connect / Middlewares • Connect is a middleware framework • Similar to Rack • A middleware is simply a function with three arguments: request, response, next var helloWorld = function(req, res, next) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('hello world'); }
  • 6. Middleware var loadUser = function(req, res, next) { var id = req.params.id; var user = db.loadUser(id); // fetch user from db if (user) { req.user = user; next(); } else { next(new Error('Failed to load user ' + id)); } } app.get('/user/:id', loadUser, function(req, res) { res.send('Viewing user ' + req.user.name); });
  • 7. HTTP POST <form method="post" action="/"> <input type="text" name="user[name]" /> <input type="submit" value="Submit" /> </form> bodyDecoder middleware for POST params: app.use(express.bodyDecoder()); app.post('/', function(req, res){ console.log(req.body.user); res.redirect('back'); });
  • 8. HTTP PUT/DELETE <form method="post" action="/"> <input type="hidden" name="_method" value="put" /> <input type="text" name="user[name]" /> <input type="submit" value="Submit" /> </form> bodyDecoder and methodOverride: app.use(express.bodyDecoder()); app.use(express.methodOverride()); app.post('/', function(req, res){ console.log(req.body.user); res.redirect('back'); });
  • 9. View Rendering • Concept: Layout, view and partials • Template Engines: Jade, Haml, EJS, … • View variables are passed to render app.set('view engine', 'jade'); app.get('/', function(req, res){ res.render('index.haml', { layout: 'app', // -> app.jade locals: { title: 'This is my app' } }); });
  • 10. Jade - Template Engine !!! html(lang="en") head title= pageTitle :javascript | if (foo) | bar() body h1 Jade - node template engine #container - if (youAreUsingJade) p You are amazing - else p Get on it! .comments = partial('comment', comments)
  • 11. Helpers app.dynamicHelpers({ flashes: function(req, res) { var msg = req.flash('message'); return msg.length ? '<p id="msg">' + msg + '</p>': ''; } }); app.helpers({ linkTo: function(text, url) { return '<a href=' + url + '>' + text + '</a>'; }, name: function(user) { return user.firstName + ' ' + user.lastName; } });
  • 12. Sessions • Currently depending on cookies • Store implementations: Memory, Redis, … app.use(express.cookieDecoder()); app.use(express.session()); app.post('/cart/add', function(req, res) { req.session.items = req.body.items; res.redirect('back'); }); app.get('/cart', function(req, res) { var items = req.session.items; res.render('cart', { locals: { items: items } }); });
  • 13. Error Handling The app.error() method receives exceptions thrown within a route, or passed to next(err) app.use(express.errorHandler({ dumpExceptions: true })); app.error(function(err, req, res, next) { if (err instanceof Unauthorized) { res.render('401.jade', { locals: { error: err } }); } else if (err instanceof NotFound) { res.render('404.jade'); } else { next(err); } });
  • 14. Why express? • Full-blown feature set • Built on Connect • Good documentation • Lots of examples • Many extensions • Nice community
  • 15. Going further… • http://expressjs.com/guide.html • http://expressjs.com/api.html • http://senchalabs.github.com/connect/ • http://github.com/senchalabs/connect/wiki • http://github.com/visionmedia/express/tree/ master/examples/ • https://github.com/dbloete/Codeshelver