SlideShare uma empresa 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/

Mais conteúdo relacionado

Mais procurados

Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JSCakra Danu Sedayu
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to NodejsGabriele 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 & ExpressChristian 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 classFin 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 jsfakedarren
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event EmittersTheCreativedev 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 .NETGianluca Carucci
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.jsdavidchubbs
 
Overview of Node JS
Overview of Node JSOverview of Node JS
Overview of Node JSJacob Nelson
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJSSylvain Zimmer
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele 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 DevelopersCaldera Labs
 

Mais procurados (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
 

Destaque

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 FrameworkEdureka!
 
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 MongoAxilis
 
Node, express & sails
Node, express & sailsNode, express & sails
Node, express & sailsBrian 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.jsCaesar 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 COMPANYZulker Naeen
 
Branding Scotland, Blanding Scotland
Branding Scotland, Blanding ScotlandBranding Scotland, Blanding Scotland
Branding Scotland, Blanding ScotlandDeborahJ
 
Aplicación del Examen Complexiuo
Aplicación  del Examen  ComplexiuoAplicación  del Examen  Complexiuo
Aplicación del Examen ComplexiuoAlfredo Carrion
 
Node.js - Server Side Javascript
Node.js - Server Side JavascriptNode.js - Server Side Javascript
Node.js - Server Side JavascriptMatteo Napolitano
 
Hawesko_BiTS-2013
Hawesko_BiTS-2013Hawesko_BiTS-2013
Hawesko_BiTS-2013bigden81
 
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. 2006Gogely The Great
 
Web Applications Development with MEAN Stack
Web Applications Development with MEAN StackWeb Applications Development with MEAN Stack
Web Applications Development with MEAN StackShailendra 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 AppEdureka!
 
How to Customize Multiple Shirt Sizes
How to Customize Multiple Shirt SizesHow to Customize Multiple Shirt Sizes
How to Customize Multiple Shirt SizesTransfer Express
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 

Destaque (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
 

Semelhante a Building Web Apps with Express

nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
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 UGProject 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 azureColin 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 ApplicationsOhad Kravchick
 
Universal JavaScript
Universal JavaScriptUniversal JavaScript
Universal JavaScript名辰 洪
 
Kraken Front-Trends
Kraken Front-TrendsKraken Front-Trends
Kraken Front-TrendsPayPal
 
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.jssoft-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 EXPRESSannalakshmi35
 
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
 
Intro To webOS
Intro To webOSIntro To webOS
Intro To webOSfpatton
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteorSapna Upreti
 

Semelhante 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
 

Mais de Aaron Stannard

The Coming OSS Sustainability Crisis
The Coming OSS Sustainability CrisisThe Coming OSS Sustainability Crisis
The Coming OSS Sustainability CrisisAaron Stannard
 
Startup Product Development
Startup Product DevelopmentStartup Product Development
Startup Product DevelopmentAaron Stannard
 
NoSQL Shootout: RavenDB vs MongoDB
NoSQL Shootout: RavenDB vs MongoDBNoSQL Shootout: RavenDB vs MongoDB
NoSQL Shootout: RavenDB vs MongoDBAaron 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 7Aaron 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
 

Mais de Aaron Stannard (7)

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

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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 WorkerThousandEyes
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 

Último (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 

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 do 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