• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Express Yourself With Node and Express
 

Express Yourself With Node and Express

on

  • 1,694 views

My presentation on Node.js and Express from SDP 2013

My presentation on Node.js and Express from SDP 2013

Statistics

Views

Total Views
1,694
Views on SlideShare
1,101
Embed Views
593

Actions

Likes
1
Downloads
3
Comments
0

5 Embeds 593

http://www.programmingtidbits.com 468
http://programmingtidbits.com 96
http://blogs.microsoft.co.il 22
http://feeds.feedburner.com 5
http://feedly.com 2

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • - cluster (http://nodejs.org/api/cluster.html)
  • __dirname returns the directory that the currently executed script resides in (http://nodejs.org/api/globals.html#globals_dirname)
  • MIME Types (http://en.wikipedia.org/wiki/Internet_media_type)
  • - 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 (http://www.senchalabs.org/connect/)
  • View EnginesEJS (http://embeddedjs.com/)Jade (http://jade-lang.com/)JSHTML (https://github.com/elmerbulthuis/jshtml)Hjs (http://twitter.github.io/hogan.js/)
  • View EnginesEJS (http://embeddedjs.com/)Jade (http://jade-lang.com/)JSHTML (https://github.com/elmerbulthuis/jshtml)Hjs (http://twitter.github.io/hogan.js/)
  • ThemethodOverride middleware (using put, and delete)
  • The cookieParser middleware is needed in both cases (http://www.senchalabs.org/connect/cookieParser.html)cookieSession middleware (http://www.senchalabs.org/connect/cookieSession.html) – Entire session data is stored in the cookiesession middleware (http://www.senchalabs.org/connect/session.html) – Stores only session id in the cookie. The data is stored on the server (multiple storage possibilities)connect-mongo (https://github.com/kcbanner/connect-mongo)connect-redis (https://github.com/visionmedia/connect-redis)
  • basicAuth middleware (http://www.senchalabs.org/connect/basicAuth.html)To 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 - http://blog.modulus.io/nodejs-and-express-basic-authenticationPassport (http://passportjs.org/)

Express Yourself With Node and Express Express Yourself With Node and Express Presentation Transcript

  • SELA DEVELOPER PRACTICE December 15-19, 2013 Moshe Levi Senior Consultant, SELA Blog: www.programmingtidbits.com Twitter: @levimos Express Yourself © Copyright SELA software & Education Labs Ltd. | 14-18 Baruch Hirsch St Bnei Brak, 51202 Israel | www.selagroup.com
  • Agenda Introduction to node The connect middleware Express Configuration Routing Rendering views with Jade Handling POST data Session support Authentication
  • 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
  • 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
  • Why Node? Request FS Request Request Request Request Event Loop libeio Non Blocking DB
  • 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
  • Who is using node?
  • Installation Download the installer from http://nodejs.org/
  • 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");
  • 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?
  • 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
  • Connect Middleware logger favicon cookieParser csrf bodyParser session compress basicAuth methodOverride
  • 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);
  • 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
  • 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);
  • Hello Express Demo
  • 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
  • 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'));
  • 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
  • Simple Routing var authenticate = function(req, res, next){ // ... }; app.get('/', function(req, res) { // ... }); app.get('/users', function(req, res){ // ... }); app.post('/users/', authenticate, function(req, res) { // ... });
  • 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
  • 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 req.query.name }); app.get('/users/:userId', function(req, res){ // Route parameter is available via req.params.userId });
  • Routing Demo
  • 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
  • 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>
  • 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
  • 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); });
  • Views Demo
  • 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
  • Using The bodyParser Middleware app.use(express.bodyParser()); app.get('/', function(req, res){ res.render('index'); }); app.post('/', function(req, res){ console.log(req.body); res.redirect('/'); });
  • Using The bodyParser Middleware Demo
  • 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
  • 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}); });
  • Sessions Demo
  • 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 (http://passportjs.org/) More than 140 authentication strategies Single Sign On with Twitter, Facebook, Google and more
  • 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!"); });
  • Authentication Demo
  • Resources Demo https://github.com/BravoAlpha/HeapOverflow My Blog - http://www.programmingtidbits.com/ Node - http://nodejs.org/ Connect Middleware http://www.senchalabs.org/connect/ Express - http://expressjs.com/ Jade - http://jade-lang.com/
  • Questions