SlideShare a Scribd company logo
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/

More Related Content

What's hot

Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
TheCreativedev Blog
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
Cakra Danu Sedayu
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
Gabriele Lana
 
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
Christian Joudrey
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering
 
Nodejs first class
Nodejs first classNodejs first class
Nodejs first class
Fin Chen
 
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
fakedarren
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
Felix Geisendörfer
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
Felix Geisendörfer
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
TheCreativedev Blog
 
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 frameworkBen Lin
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by expressShawn Meng
 
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
Gianluca Carucci
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
davidchubbs
 
Overview of Node JS
Overview of Node JSOverview of Node JS
Overview of Node JS
Jacob Nelson
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJS
Sylvain Zimmer
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
orkaplan
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
Gabriele Lana
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress Developers
Caldera Labs
 

What's hot (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
 

Viewers also liked

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
Edureka!
 
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
Axilis
 
Node, express & sails
Node, express & sailsNode, express & sails
Node, express & sails
Brian Shannon
 
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
Caesar Chi
 
Full-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.jsFull-Stack JavaScript with Node.js
Full-Stack JavaScript with Node.jsMichael Lehmann
 
Marrueco, al otro lado del estrecho
Marrueco, al otro lado del estrechoMarrueco, al otro lado del estrecho
Marrueco, al otro lado del estrechojlpcaceres
 
STRATEGIC PLAN ON A BIKE COMPANY
STRATEGIC PLAN ON A BIKE COMPANYSTRATEGIC PLAN ON A BIKE COMPANY
STRATEGIC PLAN ON A BIKE COMPANY
Zulker Naeen
 
Branding Scotland, Blanding Scotland
Branding Scotland, Blanding ScotlandBranding Scotland, Blanding Scotland
Branding Scotland, Blanding Scotland
DeborahJ
 
Aplicación del Examen Complexiuo
Aplicación  del Examen  ComplexiuoAplicación  del Examen  Complexiuo
Aplicación del Examen Complexiuo
Alfredo Carrion
 
Node.js - Server Side Javascript
Node.js - Server Side JavascriptNode.js - Server Side Javascript
Node.js - Server Side Javascript
Matteo Napolitano
 
Hawesko_BiTS-2013
Hawesko_BiTS-2013Hawesko_BiTS-2013
Hawesko_BiTS-2013
bigden81
 
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
Gogely The Great
 
Web Applications Development with MEAN Stack
Web Applications Development with MEAN StackWeb Applications Development with MEAN Stack
Web Applications Development with MEAN Stack
Shailendra Chauhan
 
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
Edureka!
 
How to Customize Multiple Shirt Sizes
How to Customize Multiple Shirt SizesHow to Customize Multiple Shirt Sizes
How to Customize Multiple Shirt Sizes
Transfer Express
 
Node.js security
Node.js securityNode.js security
Node.js security
Maciej Lasyk
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 

Viewers also liked (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 to 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 applicationsTom 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 javascriptEldar Djafarov
 
Node js introduction
Node js introductionNode js introduction
Node js introductionAlex Su
 
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
Hamdi Hmidi
 
sMash at May NYPHP UG
sMash at May NYPHP UGsMash at May NYPHP UG
sMash at May NYPHP UG
Project Zero
 
Kraken
KrakenKraken
KrakenPayPal
 
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
Colin Mackay
 
Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics Angular server side rendering - Strategies & Technics
Angular server side rendering - Strategies & Technics
Eliran Eliassy
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
Ohad Kravchick
 
Universal JavaScript
Universal JavaScriptUniversal JavaScript
Universal JavaScript
名辰 洪
 
Kraken Front-Trends
Kraken Front-TrendsKraken Front-Trends
Kraken Front-Trends
PayPal
 
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
soft-shake.ch
 
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
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
Jeetendra singh
 
23003468463PPT.pptx
23003468463PPT.pptx23003468463PPT.pptx
23003468463PPT.pptx
annalakshmi35
 
Intro To webOS
Intro To webOSIntro To webOS
Intro To webOS
fpatton
 
NodeJS
NodeJSNodeJS
NodeJS
Alok Guha
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
Sapna Upreti
 

Similar to 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
 

More from Aaron Stannard

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
Aaron Stannard
 
The Coming OSS Sustainability Crisis
The Coming OSS Sustainability CrisisThe Coming OSS Sustainability Crisis
The Coming OSS Sustainability Crisis
Aaron Stannard
 
Startup Product Development
Startup Product DevelopmentStartup Product Development
Startup Product Development
Aaron Stannard
 
NoSQL Shootout: RavenDB vs MongoDB
NoSQL Shootout: RavenDB vs MongoDBNoSQL Shootout: RavenDB vs MongoDB
NoSQL Shootout: RavenDB vs MongoDB
Aaron Stannard
 
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
Aaron Stannard
 
Consuming REST in .NET
Consuming REST in .NETConsuming REST in .NET
Consuming REST in .NETAaron Stannard
 
How to Design Applications People Love
How to Design Applications People LoveHow to Design Applications People Love
How to Design Applications People LoveAaron Stannard
 

More from 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
 

Recently uploaded

FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 

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/

Editor's Notes

  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