Express Yourself With Node and Express


Published on

My presentation on Node.js and Express from SDP 2013

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • - cluster (
  • __dirname returns the directory that the currently executed script resides in (
  • MIME Types (
  • - Each piece of middleware is a request handler. You start by looking at the first request handler, then you look at the next one, then the next, and so on.
  • - Complete list of connect middlewares (
  • View EnginesEJS ( ( ( (
  • View EnginesEJS ( ( ( (
  • ThemethodOverride middleware (using put, and delete)
  • The cookieParser middleware is needed in both cases ( middleware ( – Entire session data is stored in the cookiesession middleware ( – Stores only session id in the cookie. The data is stored on the server (multiple storage possibilities)connect-mongo ( (
  • basicAuth middleware ( use on all routes use the app.use() methodTo use on selected routes, save it in a variable and pass it as a middleware to the selected routesAdditional information - (
  • Express Yourself With Node and Express

    1. 1. SELA DEVELOPER PRACTICE December 15-19, 2013 Moshe Levi Senior Consultant, SELA Blog: Twitter: @levimos Express Yourself © Copyright SELA software & Education Labs Ltd. | 14-18 Baruch Hirsch St Bnei Brak, 51202 Israel |
    2. 2. Agenda Introduction to node The connect middleware Express Configuration Routing Rendering views with Jade Handling POST data Session support Authentication
    3. 3. Node 101 A platform for building fast and scalable network applications Built on top of Google’s V8 JS engine Uses an event-driven, non-blocking IO
    4. 4. Why Node? Using a thread per request is not optimal Request Request Thread Pool Request Request Request FS T T T Blocking T T DB
    5. 5. Why Node? Request FS Request Request Request Request Event Loop libeio Non Blocking DB
    6. 6. Why Node? High performance I/O operations Using a single language for both client and server A big and vibrant community 46,754 packages in npm as of now
    7. 7. Who is using node?
    8. 8. Installation Download the installer from
    9. 9. A Static File Server var http = require('http'); var path = require('path'); var fs = require('fs'); var server = http.createServer(function(req, res){ var fullPath = path.join(__dirname, req.url); fs.readFile(fullPath, function(error, content){ if (error) { res.writeHead(404); res.end(JSON.stringify(error)); return; } res.writeHead(200); res.end(content); }); }); server.listen(3000); console.log("Server is listening");
    10. 10. Are We Done? What about: Client Side Caching? MIME Types? Security (GET /../../../)? Why write our own when we can use an existing, well tested library?
    11. 11. npm install connect “An abstraction layer, providing node developers with an effective, high performance solution for rapid development using interchangeable components called "middleware".” – TJ Holowaychuk Request logger bodyParser basicAuth Response static
    12. 12. Connect Middleware logger favicon cookieParser csrf bodyParser session compress basicAuth methodOverride
    13. 13. Connect Middleware A middleware is just a function that handle requests It can choose to respond to the request or to process it and pass it to the next middleware var connect = require('connect'); var app = connect() .use(function(req, res, next){ console.log(req); next(); }) .use(connect.static('public')) .listen(3000);
    14. 14. npm install express Express is a web application framework for Node It gives you everything in connect plus: Various view rendering engines (jade, ejs, …) Various style sheet engines (less, stylus) Routing Supports multiple configurations Additional convenience methods on the Request and Response objects
    15. 15. Hello Express npm install –g express express [project name] var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('Hello Express'); }); app.listen(3000);
    16. 16. Hello Express Demo
    17. 17. Configuration Use the app.set and app.get methods to set and get configuration values Use the app.use method to add middleware Order is important An optional path can be configured (Default is ‘/’) Use the app.configure method to add multiple configurations Controlled by the env setting which defaults to the value of the NODE_ENV environment variable
    18. 18. Configuration var express = require('express'); var app = express(); app.configure('development', function() { app.set('port', 3000); app.use('/log', express.logger()); }); app.configure('production', function() { app.set('port', 4000); app.use(express.logger()); }); app.listen(app.get('port'));
    19. 19. Routing Use any of the app.VERB methods with a path and a callback VERB can be any HTTP verb Path is threated as a regular expression Multiple callbacks may be given Use the app.all method to match all verbs
    20. 20. Simple Routing var authenticate = function(req, res, next){ // ... }; app.get('/', function(req, res) { // ... }); app.get('/users', function(req, res){ // ... });'/users/', authenticate, function(req, res) { // ... });
    21. 21. Route and Query Parameters Route parameters are set as part of the route and are prefixed with a colon Can be accessed through req.params.[parameter name] Use app.param to map logic for route parameters Query parameters can be accessed through req.query.[parameter name] They are not considered as part of the route
    22. 22. Route and Query Parameters app.param('userId', function(req, res, next, param) { // Load the user and set it as part of the request object. // You can also alter the req.params object directly. next(); }); // GET /users?name=moshe app.get('/users', function(req, res){ // name is available via }); app.get('/users/:userId', function(req, res){ // Route parameter is available via req.params.userId });
    23. 23. Routing Demo
    24. 24. Views To combine dynamic content with static templates, Express has a built in support for: Jade EJS jshtml hjs Support for partials Use the app.locals method to provide global variables to all templates
    25. 25. Jade Life is too short to close HTML tags! And for all those angle brackets! In Jade, its all about the indentation doctype 5 html head title= title body h1= title p Welcome to #{title} <!DOCTYPE html> <html> <head> <title>Express</title> </head> <body> <h1>Express</h1> <p>Welcome to Express</p> </body> </html>
    26. 26. Jade 101 Declare an element by its name Use an hash (#) to set the element’s id Use a period (.) to set the element’s class Attributes goes between brackets and are separated by a comma Use block and extends for partials Working with data Use for … in to enumerate collections Use = or #{} to reference a variable Use if and else for conditional content
    27. 27. View Rendering With Express // Locals can be set dynamically as part of a middleware. // This technique can be used to set the current session. app.locals({'title' : 'Express'}); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); var data = { 'sessions' : ['Express Yourself', 'AngularJS'], 'happyFlag' : true }; app.get('/', function(req, res){ res.render('index', data); });
    28. 28. Views Demo
    29. 29. Parsing The Request Body Use the bodyParser middleware to parse the request body x-www-form-urlencoded JSON Parsed data is available via the req.body object
    30. 30. Using The bodyParser Middleware app.use(express.bodyParser()); app.get('/', function(req, res){ res.render('index'); });'/', function(req, res){ console.log(req.body); res.redirect('/'); });
    31. 31. Using The bodyParser Middleware Demo
    32. 32. Sessions Implemented using cookies Therefore, the cookieParser middleware is needed Secret must be provided to prevent cookie tempering The cookieSession middleware stores the entire session data in the cookie The session middleware stores only a session id in the cookie. The data itself is stored on the server Default is MemoryStore connect-mongo connect-redis
    33. 33. Adding Session Support app.use(express.cookieParser()); app.use(express.session({secret : 'Some Secret'})); // alternatively, the cookieSession middleware can be used app.get('/', function (req, res){ if(!req.session.viewCount) { req.session.viewCount = 0; } ++req.session.viewCount; res.render('index', {viewCount : req.session.viewCount}); });
    34. 34. Sessions Demo
    35. 35. Authentication A built in basicAuth middleware Uses the request’s Authorization header Sets the req.user object on success Returns 401 Unauthorized status on failure Supports hard coded values, synchronous, and asynchronous callbacks Can be used on selected routes or on all routes Or use Passport ( More than 140 authentication strategies Single Sign On with Twitter, Facebook, Google and more
    36. 36. Using basicAuth var auth = express.basicAuth(function(user, pass, callback){ console.log(user); console.log(pass); // Authenticate the user and return true or false setTimeout(callback.bind(null, null, true), 0); }); // Can be passed to individual routes as well app.use(auth); app.get('/', function(req, res){ res.send("You're in!"); });
    37. 37. Authentication Demo
    38. 38. Resources Demo My Blog - Node - Connect Middleware Express - Jade -
    39. 39. Questions