SlideShare una empresa de Scribd logo
1 de 23
Building Web Apps with Express

             By Aaron Stannard
      Startup Developer Evangelist, Microsoft Corporation
What is Express?
• Sinatra-inspired MVC
  framework for
  Node.JS
• Built on Connect
  Middleware
• Minimalist
What Express Does
• Parses arguments and headers
• Routing
• Views
  – Partials
  – Layouts
• Configuration
• Sessions
Simple Express App
var express = require('express');                   Loads Express module
var app = module.exports = express.createServer(); Instantiates Express
                                                    server
app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');                   Global Configuration
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

                                                    Loads and binds routes
// Routes
                                                    (defined in separate
require('./routes/site')(app);
                                                    module)
app.listen(process.env.PORT);
console.log("Express server listening on port %d in %s mode",
app.address().port, app.settings.env);
Getting Started with Express
• Installing Express
   [local install] C:> npm install express
   [global install] C:> npm install express -g

• Creating Express Applications
   C:> express [new project name]
   C:> cd [new project name]
   C:[new project name]> npm install -d
   C:[new project name]> node app.js
   Express server listening on port 3000 in development mode
Express Project Structure
/projectroot/
        package.json            Tells Node and NPM what packages are required
        readme.txt
        web/                    Root of your actual application
                app.js
                views/          The main entry point for the Express application
                           layout.jade
                           index.jade
                 models/
                           post.js     Data model
                 public/
                           /images
                           /stylesheets      Static content
                           /scripts
        test/                   Directory for unit tests
                route-test.js
                post-test.js
        node_modules/         Output directory for all NPM installations

C:[projectroot]> node web/app.js
Node server listenening on port 3000 in development mode
Express Configuration (app.js)
app.configure(function(){                    Global configuration setter
 app.set('views', __dirname + '/views');     View Engine and Views directory
 app.set('view engine', 'jade');
 app.use(express.bodyParser());
 app.use(express.methodOverride());
 app.use(express.cookieParser());
 app.use(sessions({secret: 'adfasdf34efsdfs34sefsdf'})); Session Key
 app.use(app.router);
 app.use(express.static(__dirname + '/public'));         Router and Static Content
});

app.configure('development', function(){  Development-environment configurations
 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){   Production-environment configurations
 app.use(express.errorHandler());
});
Routing
//Catch-all
app.all('/app(/*)?', requiresLogin);             Catch-all – works for all HTTP verbs

// Routes
app.get('/', routes.index);            HTTP GET request
app.get('/about', routes.about);
app.get('/contact', routes.contact);
app.get('/app/list', routes.listapps);
app.get('/app/new', routes.newapp);
app.post('/app/new', routes.saveapp); HTTP POST request
app.get('/app/:app', routes.getapp);
                                       Accepts :app route argument
app.get('/app/:app/edit', routes.editapp);



  Syntax follows the pattern:
            App.[verb](path, function(req,res), [function(req,res)]);
Creating Route Modules (Style 1)
server.js
var express = require('express')
  , routes = require('./routes');

…

app.get('/', routes.index);



route.js
// GET the homepage
exports.index = function(req, res){
        res.render('index', { title: Home' });
};
Creating Route Modules (Style 2)
server.js
 // Routes
 require('./routes/site')(app);


routes/site.js
/*
 * Module dependencies
 */

 module.exports = function(app){

     // GET home page
      app.get('/', function(req, res){
          res.render('index', { title: ‘Home' })
      });
 }
Request Object
• Req.Param
    – Req.Query
    – Req.Body
•   Req.Session
•   Req.Flash
•   Req.Headers
•   Can bind usable JSON payloads
Response Object
•   Res.Redirect
•   Res.Write
•   Res.End
•   Res.Download
•   Local variables and object binding
Route Pre-Conditions

app.param(‘app’, function(req, res, next, id){
        appProvider.getAppById(req.session.userName, id,
        function(error, app){
                if(error) return next(error);
                if(!app) return next(new
                        Error('Failed to find app with
                        id '+ id));
                req.app = app;
                next();
        });
});
Route Filters

//Catch-all
app.all('/app(/*)?', function(req, res, next) {
  if(req.session && req.session.userName) {
    next();
  } else {
    res.redirect('/login?redir=' + req.url);
  }
});
Views
•   Support for multiple view engines
•   Layout support
•   Partials
•   Dynamic Helpers
Jade
• Basic Syntax
  ul
       li
            a(href='/') Home

• Variables
  title= title

• Conditionals
  if flash.info
          span.info= flash.info

• Iterations
       each user in users
              div.user_id= user.username
View Helpers
app.dynamicHelpers({
    session: function (req, res) {
        return req.session;
    },
    flash: function(req, res){
        if(typeof(req.session) == 'undefined'){
                return undefined;
        }
        else{
                return req.flash();
        }
    }
});
Session Management
• Session State Providers
  – Cookie + Back-end Session Store
• Session Cookies
  – cookie-sessions NPM package


 //Assign username of logged in user to session
 req.session.userName = username;
Model Structure (OOP)
Model Structure (Common)
Express on Windows Azure
• Rename app.js to server.js
• (You're done)
• Caveats
  – Only a limited number of session state providers
  – Many popular data stores not available
Further Reference
•   ExpressJS.com - Official Express Homepage
•   Github.com/visionmedia/jade - Jade
•   Github.com/senchalabs/connect - Connect
•   Github.com/WindowsAzure – Azure bits
About Me
• Aaron Stannard
  – Twitter: @Aaronontheweb
  – Github: @Aaronontheweb
  – Blog: http://www.aaronstannard.com/

Más contenido relacionado

La actualidad más candente

How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
Ben Lin
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by express
Shawn Meng
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
martincabrera
 

La actualidad más candente (20)

Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 
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
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
Nodejs first class
Nodejs first classNodejs first class
Nodejs first class
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by express
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
Overview of Node JS
Overview of Node JSOverview of Node JS
Overview of Node JS
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJS
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress Developers
 

Destacado

Full-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.jsFull-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.js
Michael Lehmann
 
Marrueco, al otro lado del estrecho
Marrueco, al otro lado del estrechoMarrueco, al otro lado del estrecho
Marrueco, al otro lado del estrecho
jlpcaceres
 

Destacado (18)

Create Restful Web Application With Node.js Express Framework
Create Restful Web Application With Node.js Express FrameworkCreate Restful Web Application With Node.js Express Framework
Create Restful Web Application With Node.js Express Framework
 
Diving into Node with Express and Mongo
Diving into Node with Express and MongoDiving into Node with Express and Mongo
Diving into Node with Express and Mongo
 
Node, express & sails
Node, express & sailsNode, express & sails
Node, express & sails
 
Expressjs basic to advance, power by Node.js
Expressjs basic to advance, power by Node.jsExpressjs basic to advance, power by Node.js
Expressjs basic to advance, power by Node.js
 
Full-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.jsFull-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.js
 
Marrueco, al otro lado del estrecho
Marrueco, al otro lado del estrechoMarrueco, al otro lado del estrecho
Marrueco, al otro lado del estrecho
 
STRATEGIC PLAN ON A BIKE COMPANY
STRATEGIC PLAN ON A BIKE COMPANYSTRATEGIC PLAN ON A BIKE COMPANY
STRATEGIC PLAN ON A BIKE COMPANY
 
Branding Scotland, Blanding Scotland
Branding Scotland, Blanding ScotlandBranding Scotland, Blanding Scotland
Branding Scotland, Blanding Scotland
 
Aplicación del Examen Complexiuo
Aplicación  del Examen  ComplexiuoAplicación  del Examen  Complexiuo
Aplicación del Examen Complexiuo
 
Node.js - Server Side Javascript
Node.js - Server Side JavascriptNode.js - Server Side Javascript
Node.js - Server Side Javascript
 
Hawesko_BiTS-2013
Hawesko_BiTS-2013Hawesko_BiTS-2013
Hawesko_BiTS-2013
 
Jornada técnica de energía solar térmica - Salvador Escoda S.A. 2006
Jornada técnica de energía solar térmica - Salvador Escoda S.A. 2006Jornada técnica de energía solar térmica - Salvador Escoda S.A. 2006
Jornada técnica de energía solar térmica - Salvador Escoda S.A. 2006
 
Express yourself
Express yourselfExpress yourself
Express yourself
 
Web Applications Development with MEAN Stack
Web Applications Development with MEAN StackWeb Applications Development with MEAN Stack
Web Applications Development with MEAN Stack
 
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
 
How to Customize Multiple Shirt Sizes
How to Customize Multiple Shirt SizesHow to Customize Multiple Shirt Sizes
How to Customize Multiple Shirt Sizes
 
Node.js security
Node.js securityNode.js security
Node.js security
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 

Similar a Building Web Apps with Express

nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
Eldar Djafarov
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Alex Su
 
Kraken
KrakenKraken
Kraken
PayPal
 
MERN SRTACK WEB DEVELOPMENT NODE JS EXPRESS
MERN SRTACK WEB DEVELOPMENT NODE JS EXPRESSMERN SRTACK WEB DEVELOPMENT NODE JS EXPRESS
MERN SRTACK WEB DEVELOPMENT NODE JS EXPRESS
annalakshmi35
 

Similar a Building Web Apps with Express (20)

nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
API Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015
API  Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015 API  Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015
API Driven Application - AngulatJS, NodeJS and MongoDB | JCertif Tunisia 2015
 
sMash at May NYPHP UG
sMash at May NYPHP UGsMash at May NYPHP UG
sMash at May NYPHP UG
 
Kraken
KrakenKraken
Kraken
 
Introduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azureIntroduction to node js - From "hello world" to deploying on azure
Introduction to node js - From "hello world" to deploying on azure
 
Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
Universal JavaScript
Universal JavaScriptUniversal JavaScript
Universal JavaScript
 
Kraken Front-Trends
Kraken Front-TrendsKraken Front-Trends
Kraken Front-Trends
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
MERN SRTACK WEB DEVELOPMENT NODE JS EXPRESS
MERN SRTACK WEB DEVELOPMENT NODE JS EXPRESSMERN SRTACK WEB DEVELOPMENT NODE JS EXPRESS
MERN SRTACK WEB DEVELOPMENT NODE JS EXPRESS
 
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
 
23003468463PPT.pptx
23003468463PPT.pptx23003468463PPT.pptx
23003468463PPT.pptx
 
Nodejs web,db,hosting
Nodejs web,db,hostingNodejs web,db,hosting
Nodejs web,db,hosting
 
Intro To webOS
Intro To webOSIntro To webOS
Intro To webOS
 
NodeJS
NodeJSNodeJS
NodeJS
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
 

Más de Aaron Stannard

Consuming REST in .NET
Consuming REST in .NETConsuming REST in .NET
Consuming REST in .NET
Aaron Stannard
 
How to Design Applications People Love
How to Design Applications People LoveHow to Design Applications People Love
How to Design Applications People Love
Aaron Stannard
 

Más de Aaron Stannard (8)

How Software Developers Destroy Business Value.pptx
How Software Developers Destroy Business Value.pptxHow Software Developers Destroy Business Value.pptx
How Software Developers Destroy Business Value.pptx
 
The Coming OSS Sustainability Crisis
The Coming OSS Sustainability CrisisThe Coming OSS Sustainability Crisis
The Coming OSS Sustainability Crisis
 
Startup Product Development
Startup Product DevelopmentStartup Product Development
Startup Product Development
 
NoSQL Shootout: RavenDB vs MongoDB
NoSQL Shootout: RavenDB vs MongoDBNoSQL Shootout: RavenDB vs MongoDB
NoSQL Shootout: RavenDB vs MongoDB
 
Location Services and Bing Maps in Windows Phone 7
Location Services and Bing Maps in Windows Phone 7Location Services and Bing Maps in Windows Phone 7
Location Services and Bing Maps in Windows Phone 7
 
Consuming REST in .NET
Consuming REST in .NETConsuming REST in .NET
Consuming REST in .NET
 
MVVM for n00bs
MVVM for n00bsMVVM for n00bs
MVVM for n00bs
 
How to Design Applications People Love
How to Design Applications People LoveHow to Design Applications People Love
How to Design Applications People Love
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
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
Safe Software
 

Último (20)

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...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Building Web Apps with Express

  • 1. Building Web Apps with Express By Aaron Stannard Startup Developer Evangelist, Microsoft Corporation
  • 2. What is Express? • Sinatra-inspired MVC framework for Node.JS • Built on Connect Middleware • Minimalist
  • 3. What Express Does • Parses arguments and headers • Routing • Views – Partials – Layouts • Configuration • Sessions
  • 4. Simple Express App var express = require('express'); Loads Express module var app = module.exports = express.createServer(); Instantiates Express server app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); Global Configuration app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); Loads and binds routes // Routes (defined in separate require('./routes/site')(app); module) app.listen(process.env.PORT); console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
  • 5. Getting Started with Express • Installing Express [local install] C:> npm install express [global install] C:> npm install express -g • Creating Express Applications C:> express [new project name] C:> cd [new project name] C:[new project name]> npm install -d C:[new project name]> node app.js Express server listening on port 3000 in development mode
  • 6. Express Project Structure /projectroot/ package.json Tells Node and NPM what packages are required readme.txt web/ Root of your actual application app.js views/ The main entry point for the Express application layout.jade index.jade models/ post.js Data model public/ /images /stylesheets Static content /scripts test/ Directory for unit tests route-test.js post-test.js node_modules/ Output directory for all NPM installations C:[projectroot]> node web/app.js Node server listenening on port 3000 in development mode
  • 7. Express Configuration (app.js) app.configure(function(){ Global configuration setter app.set('views', __dirname + '/views'); View Engine and Views directory app.set('view engine', 'jade'); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(sessions({secret: 'adfasdf34efsdfs34sefsdf'})); Session Key app.use(app.router); app.use(express.static(__dirname + '/public')); Router and Static Content }); app.configure('development', function(){ Development-environment configurations app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ Production-environment configurations app.use(express.errorHandler()); });
  • 8. Routing //Catch-all app.all('/app(/*)?', requiresLogin); Catch-all – works for all HTTP verbs // Routes app.get('/', routes.index); HTTP GET request app.get('/about', routes.about); app.get('/contact', routes.contact); app.get('/app/list', routes.listapps); app.get('/app/new', routes.newapp); app.post('/app/new', routes.saveapp); HTTP POST request app.get('/app/:app', routes.getapp); Accepts :app route argument app.get('/app/:app/edit', routes.editapp); Syntax follows the pattern: App.[verb](path, function(req,res), [function(req,res)]);
  • 9. Creating Route Modules (Style 1) server.js var express = require('express') , routes = require('./routes'); … app.get('/', routes.index); route.js // GET the homepage exports.index = function(req, res){ res.render('index', { title: Home' }); };
  • 10. Creating Route Modules (Style 2) server.js // Routes require('./routes/site')(app); routes/site.js /* * Module dependencies */ module.exports = function(app){ // GET home page app.get('/', function(req, res){ res.render('index', { title: ‘Home' }) }); }
  • 11. Request Object • Req.Param – Req.Query – Req.Body • Req.Session • Req.Flash • Req.Headers • Can bind usable JSON payloads
  • 12. Response Object • Res.Redirect • Res.Write • Res.End • Res.Download • Local variables and object binding
  • 13. Route Pre-Conditions app.param(‘app’, function(req, res, next, id){ appProvider.getAppById(req.session.userName, id, function(error, app){ if(error) return next(error); if(!app) return next(new Error('Failed to find app with id '+ id)); req.app = app; next(); }); });
  • 14. Route Filters //Catch-all app.all('/app(/*)?', function(req, res, next) { if(req.session && req.session.userName) { next(); } else { res.redirect('/login?redir=' + req.url); } });
  • 15. Views • Support for multiple view engines • Layout support • Partials • Dynamic Helpers
  • 16. Jade • Basic Syntax ul li a(href='/') Home • Variables title= title • Conditionals if flash.info span.info= flash.info • Iterations each user in users div.user_id= user.username
  • 17. View Helpers app.dynamicHelpers({ session: function (req, res) { return req.session; }, flash: function(req, res){ if(typeof(req.session) == 'undefined'){ return undefined; } else{ return req.flash(); } } });
  • 18. Session Management • Session State Providers – Cookie + Back-end Session Store • Session Cookies – cookie-sessions NPM package //Assign username of logged in user to session req.session.userName = username;
  • 21. Express on Windows Azure • Rename app.js to server.js • (You're done) • Caveats – Only a limited number of session state providers – Many popular data stores not available
  • 22. Further Reference • ExpressJS.com - Official Express Homepage • Github.com/visionmedia/jade - Jade • Github.com/senchalabs/connect - Connect • Github.com/WindowsAzure – Azure bits
  • 23. About Me • Aaron Stannard – Twitter: @Aaronontheweb – Github: @Aaronontheweb – Blog: http://www.aaronstannard.com/

Notas del editor

  1. Req.Param is an abstraction layer for picking up information about a request – it automatically searches:Query stringsPosted form valuesRoute valuesAnd will let you pick from what’s available