Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Building Web Apps with Express


Published on

An introduction to Express, the Sinatra-inspired MVC framework for Node.JS. You'll learn how Express manages and processes routes, how to use the Jade template engine, and how to design data models aimed to play nice with Express.

Published in: Technology
  • Login to see the comments

Building Web Apps with Express

  1. 1. Building Web Apps with Express By Aaron Stannard Startup Developer Evangelist, Microsoft Corporation
  2. 2. What is Express?• Sinatra-inspired MVC framework for Node.JS• Built on Connect Middleware• Minimalist
  3. 3. What Express Does• Parses arguments and headers• Routing• Views – Partials – Layouts• Configuration• Sessions
  4. 4. Simple Express Appvar express = require(express); Loads Express modulevar app = module.exports = express.createServer(); Instantiates Express serverapp.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 separaterequire(./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. 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. 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 installationsC:[projectroot]> node web/app.jsNode server listenening on port 3000 in development mode
  7. 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. 8. Routing//Catch-allapp.all(/app(/*)?, requiresLogin); Catch-all – works for all HTTP verbs// Routesapp.get(/, routes.index); HTTP GET requestapp.get(/about, routes.about);app.get(/contact,;app.get(/app/list, routes.listapps);app.get(/app/new, routes.newapp);, routes.saveapp); HTTP POST requestapp.get(/app/:app, routes.getapp); Accepts :app route argumentapp.get(/app/:app/edit, routes.editapp); Syntax follows the pattern: App.[verb](path, function(req,res), [function(req,res)]);
  9. 9. Creating Route Modules (Style 1)server.jsvar express = require(express) , routes = require(./routes);…app.get(/, routes.index);route.js// GET the homepageexports.index = function(req, res){ res.render(index, { title: Home });};
  10. 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. 11. Request Object• Req.Param – Req.Query – Req.Body• Req.Session• Req.Flash• Req.Headers• Can bind usable JSON payloads
  12. 12. Response Object• Res.Redirect• Res.Write• Res.End• Res.Download• Local variables and object binding
  13. 13. Route Pre-Conditionsapp.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)); = app; next(); });});
  14. 14. Route Filters//Catch-allapp.all(/app(/*)?, function(req, res, next) { if(req.session && req.session.userName) { next(); } else { res.redirect(/login?redir= + req.url); }});
  15. 15. Views• Support for multiple view engines• Layout support• Partials• Dynamic Helpers
  16. 16. Jade• Basic Syntax ul li a(href=/) Home• Variables title= title• Conditionals if• Iterations each user in users div.user_id= user.username
  17. 17. View Helpersapp.dynamicHelpers({ session: function (req, res) { return req.session; }, flash: function(req, res){ if(typeof(req.session) == undefined){ return undefined; } else{ return req.flash(); } }});
  18. 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;
  19. 19. Model Structure (OOP)
  20. 20. Model Structure (Common)
  21. 21. Express on Windows Azure• Rename app.js to server.js• (Youre done)• Caveats – Only a limited number of session state providers – Many popular data stores not available
  22. 22. Further Reference• - Official Express Homepage• - Jade• - Connect• – Azure bits
  23. 23. About Me• Aaron Stannard – Twitter: @Aaronontheweb – Github: @Aaronontheweb – Blog: