SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use casesFabio Biondi
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAnkit Agarwal
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesWebStackAcademy
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modulesmonikadeshmane
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBhargav Anadkat
 
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
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentationritika1
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3 ArezooKmn
 
Introduction To Single Page Application
Introduction To Single Page ApplicationIntroduction To Single Page Application
Introduction To Single Page ApplicationKMS Technology
 

Tendances (20)

Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
NestJS
NestJSNestJS
NestJS
 
Express JS
Express JSExpress JS
Express JS
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Node.js File system & Streams
Node.js File system & StreamsNode.js File system & Streams
Node.js File system & Streams
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
NEXT.JS
NEXT.JSNEXT.JS
NEXT.JS
 
Nodejs
NodejsNodejs
Nodejs
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Node js Introduction
Node js IntroductionNode js Introduction
Node js Introduction
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
introduction to Vue.js 3
introduction to Vue.js 3 introduction to Vue.js 3
introduction to Vue.js 3
 
Introduction To Single Page Application
Introduction To Single Page ApplicationIntroduction To Single Page Application
Introduction To Single Page Application
 

En vedette

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
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Plus de 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
 

Plus de 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
 

Dernier

Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 

Dernier (20)

Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 

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