An introduction to the Express web framework for Node.js
Building web appswith ExpressAndy Appleton@appltnhttp://appleton.me
View Slide
Expressis a simple web application frameworkhttp://expressjs.com/
...built onConnect,the middleware frameworkhttp://www.senchalabs.org/connect/
Connectprovides a bunch of handy utilities fordealing with HTTP requests
var app = connect().use(connect.logger('dev')).use(connect.static('public')).use(function(req, res){res.end('hello world\n');}).listen(3000);
But anyway, Express
$ npm install -g expressInstall express globally
$ npm install -g expressInit a new express app in ./awesome-demo$ express awesome-demo
$ npm install -g expressInstall the app’s dependencies with npm$ express awesome-demo$ cd awesome-demo && npm install
$ npm install -g expressRun it!$ express awesome-demo$ cd awesome-demo && npm install$ node app.js>> Express server listening onport 3000
var express = require('express');...var app = express();
// Get & set an app propertyapp.set('name', 'value');// Use a middleware functionapp.use(myMiddlewareFunction());// Respond to an HTTP requestapp.get('/path', callbackFn);app.post('/path', callbackFn);app.put('/path', callbackFn); // ...etc
Routing
app.get('/', routes.index);app.get('/users', routes.users.index);app.get('/users/:id', routes.users.show);app.post('/users/:id', routes.users.create);app.put('/users/:id', routes.users.update);
Handling a route// /usersroutes.index = function(req, res) {res.send('Hello Bath');};// /users/:idroutes.users.show = function(req, res) {var userId = req.params.id;res.send('Your userId is ' + userId);};
Rendering HTML templates
Rendering HTML templatesroutes.index = function(req, res) {res.render('index');};routes.users.show = function(req, res) {var userId = req.params.id;res.render('users/show', {id: userId});};
doctype 5htmlhead...bodyblock contentextends layoutblock contenth1= titlep Welcome to #{title}./views/layout.jade./views/index.jade
"dependencies": {..."hbs": "*"}./package.json$ npm install./app.jsapp.configure(function(){...app.set('view engine', 'hbs');...});app.configure(function(){...app.set('view engine', 'jade');...});
...{{{body}}}./views/layout.hbs./views/index.hbs{{title}}Welcome to {{title}}
routes.index = function(req, res) {res.render('index');};routes.users.show = function(req, res) {var userId = req.params.id;res.render('users/show', {id: userId});};
Sessions
// must come before routerapp.use(express.cookieParser('secret'));app.use(express.session());app.use(app.router);Session support ismiddleware
routes.users.show = function(req, res) {req.session.id || (req.session.id = 1);res.render('users/show', {id: req.session.id});};
Andy Appleton@appltnhttp://appleton.me