Merge branch 'integration'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by TJ Holowaychuk · committed by TJ Holowaychuk · parents 6368ab4, 73caacb · Browse files · 44 files·+823 added−325 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
44 files+823 added−325 removed
- tests:+559 added−0 removed
- other:+264 added−325 removed
Provenance
- Commit
0ae024a- Tree
d5118a6- Author
TJ Holowaychuk <tj@vision-media.ca>- Committer
TJ Holowaychuk <tj@vision-media.ca>- Parent 1
6368ab4- Parent 2
73caacb
44 files changed+823 added−325 removed
modified:examples/auth/views/login.ejs+1 added-1 removed
1 <h1>Login</h1>2 <%- message %>3-Try accessing <a href="/restricted">/restricted</a>.3+Try accessing <a href="/restricted">/restricted</a>, then authenticate with "tj" and "foobar".4 <form method="post" action="/login">5 <p>6 <label>Username:</label>7 <input type="text" name="username">9 unmodified linesmodified:examples/auth/app.js+26 added-33 removed
4 unmodified lines567891011121391015111213141516171819181921222324252627282930202122232425262728293031323533343835363738394041454243444945464748495013 unmodified lines646566677273747576687869707181727374757677787989808182838420 unmodified lines1051061071081181091101111121131141231241151161174 unmodified lines
var express = require('../../lib/express') , crypto = require('crypto');
var app = express.createServer( express.bodyParser() , express.cookieParser() , express.session({ secret: 'keyboard cat' }));var app = module.exports = express();
app.set('views', __dirname + '/views');app.use(express.bodyParser());app.use(express.cookieParser('shhhh, very secret'));app.use(express.session());
app.set('view engine', 'ejs');app.set('views', __dirname + '/views');
// Message helper, ideally we would use req.flash()// however this is more light-weight for an example// Session-persisted message middleware
app.dynamicHelpers({ message: function(req){ var err = req.session.error , msg = req.session.success; delete req.session.error; delete req.session.success; if (err) return '<p class="msg error">' + err + '</p>'; if (msg) return '<p class="msg success">' + msg + '</p>'; }});app.locals.use(function(req,res){ var err = req.session.error , msg = req.session.success; delete req.session.error; delete req.session.success; res.locals.message = ''; if (err) res.locals.message = '<p class="msg error">' + err + '</p>'; if (msg) res.locals.message = '<p class="msg success">' + msg + '</p>';})
// Generate a salt for the user to prevent rainbow table attacks// for better security take a look at the bcrypt c++ addon:// https://github.com/ncb000gt/node.bcrypt.js
var users = { tj: { name: 'tj' name: 'tj' , salt: 'randomly-generated-salt' , pass: hash('foobar', 'randomly-generated-salt') }};
// Used to generate a hash of the plain-text password + salt
function hash(msg, key) { return crypto.createHmac('sha256', key).update(msg).digest('hex');}// Authenticate using our plain-object database of doom!
// Authenticate using our plain-object database of doom!function authenticate(name, pass, fn) { var user = users[name]; // query the db for the given username if (!user) return fn(new Error('cannot find user'));13 unmodified lines res.redirect('/login'); }}
function accessLogger(req, res, next) { console.log('/restricted accessed by %s', req.session.user.name); next();}
app.get('/', function(req, res){ res.redirect('/login'); res.redirect('login');});
app.get('/restricted', restrict, accessLogger, function(req, res){app.get('/restricted', restrict, function(req, res){ res.send('Wahoo! restricted area');});
app.get('/logout', function(req, res){ // destroy the user's session to log them out // will be re-created next request req.session.destroy(function(){ res.redirect('home'); res.redirect('/'); });});
app.get('/login', function(req, res){20 unmodified lines } else { req.session.error = 'Authentication failed, please check your ' + ' username and password.' + ' (use "tj" and "foobar")'; res.redirect('back'); res.redirect('login'); } });});
if (!module.parent) {app.listen(3000);console.log('Express started on port 3000'); app.listen(3000); console.log('Express started on port 3000');}No newline at end of filedeleted:examples/blog/middleware/locals.js-31 removed
12345678910111213141516171819202122232425262728293031
/** * Module dependencies. */
var messages = require('express-messages');
module.exports = function(req, res, next){ // access the app without passing it into // this file explicitly var app = req.app;
// express-messages returns a function which // when called will flush the session-based // notification messages as HTML. Because of // this "flushing" action it must be a function // otherwise any view render would remove the // notifications regardless of their delay. res.locals.messages = messages(req, res);
// expose the app's mount-point // so that urls can adjust. For example // if you run this example /post/add works // however if you run the mounting example // it adjusts to /blog/post/add res.locals.base = '/' == app.route ? '' : app.route;
// all we wanted to do was assign some view locals // so pass control to the next middleware next();};No newline at end of filemodified:examples/blog/models/post.js+3 added-3 removed
15 unmodified lines16 fn();17 };18 19 Post.prototype.validate = function(fn){20- if (!this.title) return fn(new Error('_title_ required'));21- if (!this.body) return fn(new Error('_body_ required'));20+ if (!this.title) return fn(new Error('title required'));21+ if (!this.body) return fn(new Error('body required'));22 if (this.body.length < 10) {23 return fn(new Error(24- '_body_ should be at least **10** characters long, was only _' + this.title.length + '_'));24+ 'body should be at least **10** characters long, was only ' + this.title.length));25 }26 fn();27 };28 39 unmodified linesmodified:examples/blog/public/style.css+6 added-8 removed
39 unmodified lines4041424344444546474848494950515251535455545556575639 unmodified lines}.date { font-size: 11px;}#messages ul {p.error,p.message { padding: 10px; border: 1px solid;}#messages ul li { list-style: none;p.error { background: #FDEAE7; color: #E4250C;}#messages ul.info {p.message { color: #2EBBE6; background: #F7FBFD;}#messages ul.error { color: #E4250C; background: #FDEAE7;}No newline at end of fileNo newline at end of filemodified:examples/blog/routes/post.js+7 added-6 removed
40 unmodified lines41 * Save a post.42 */43 44 app.post('/post', function(req, res){45- var data = req.body.post45+ var data = req.body.post || {}46 , post = new Post(data.title, data.body);47-47+ 48 post.validate(function(err){49 if (err) {50- req.flash('error', err.message);50+ req.session.error = err.message;51 return res.redirect('back');52 }53 54 post.save(function(err){55- req.flash('info', 'Successfully created post _%s_', post.title);55+ req.session.message = 'Successfully created the post.';56 res.redirect('/post/' + post.id);57 }); 58 });59 });21 unmodified lines81 app.put('/post/:post', function(req, res, next){82 var post = req.post;83 post.validate(function(err){84 if (err) {85- req.flash('error', err.message);85+ req.session.error = err.message;86 return res.redirect('back');87 }88+89 post.update(req.body.post, function(err){90 if (err) return next(err);90- req.flash('info', 'Successfully updated post');91+ req.session.message = 'Successfully updated post';92 res.redirect('back');93 });94 });95 });1 unmodified linemodified:examples/blog/views/post/form.jade+19 added-17 removed
1+extends ../layout2 3+block content2-- if (post.title)3- h1 Editing #{post.title}4-- else5- h1 New Post4+ if post.title5+ h1 Editing #{post.title}6+ else7+ h1 New Post8 7-!= messages()9+ include ../messages10 9-form#post(action=base + '/post' + (post.title ? '/' + post.id : ''), method='post')10- - if (post.title)11- input(type='hidden', name='_method', value='put')12- p13- label(for='post[title]') Title:14- input(type='text', name='post[title]', value=post.title)15- p16- label(for='post[body]') Body:17- textarea(name='post[body]')= post.body || ''18- p19- input(type='submit', value=post.title ? 'Update' : 'Create')20- 11+ form#post(action='/post' + (post.title ? '/' + post.id : ''), method='post')12+ if post.title13+ input(type='hidden', name='_method', value='put')14+ p15+ label(for='post[title]') Title:16+ input(type='text', name='post[title]', value=post.title)17+ p18+ label(for='post[body]') Body:19+ textarea(name='post[body]')= post.body || ''20+ p21+ input(type='submit', value=post.title ? 'Update' : 'Create')22+ modified:examples/blog/views/post/index.jade+18 added-16 removed
1-.post2- // title3- h24- = post.title5- a.edit(href=base + '/post/' + post.id + '/edit') Edit6- 7- // flash messages8- != messages()9- 10- // dates11- p.date.created Created at #{post.createdAt}12- - if (post.updatedAt)13- p.date.updated Updated at #{post.updatedAt}14- 15- // body16- pre.body= post.body1+extends ../layout2+3+block content4+ .post5+ // title6+ h27+ = post.title8+ a.edit(href='/post/' + post.id + '/edit') Edit9+ 10+ include ../messages11+ 12+ // dates13+ p.date.created Created at #{post.createdAt}14+ if post.updatedAt15+ p.date.updated Updated at #{post.updatedAt}16+ 17+ // body18+ pre.body= post.bodymodified:examples/blog/views/index.jade+20 added-17 removed
1-h1 Blog1+extends layout2 3-!= messages()3+block content4+ h1 Blog5 6+ if count7+ p Display all #{count} post(s)5-- if (count)6- p Display all #{count} post(s)7- #posts!= partial('post', posts)8-- else9- p 10- | It looks like you have no posts!11- p12- | Click13- a(href=base + '/post/add') here 14- | to create a post. Login15- | as16- em "admin" 17- | and18- em "express"19- | .8+ #posts9+ each post in posts10+ include post/index11+ else12+ p 13+ | It looks like you have no posts!14+ p15+ | Click16+ a(href='/post/add') here 17+ | to create a post. Login18+ | as19+ em "admin" 20+ | and21+ em "express"22+ | .modified:examples/blog/views/layout.jade+3 added-2 removed
1 !!! 52 html3 head4 title Blog5- link(rel='stylesheet', href=base + '/style.css')5+ link(rel='stylesheet', href='/style.css')6 body7- #container!= body7+ #container8+ block contentadded:examples/blog/views/messages.jade+6 added
1+2+if error3+ p.error= error4+5+if message6+ p.message= messagemodified:examples/blog/app.js+17 added-4 removed
2 unmodified lines3 * Module dependencies.4 */5 6 var express = require('../../')7- , app = express();7+ , app = module.exports = express();8 9 // config10 11 app.set('views', __dirname + '/views');12 app.set('view engine', 'jade');13 14 // middleware15 16-app.configure(function(){16+app.configure('development',function(){17 app.use(express.logger('dev'));18+})19+20+app.configure(function(){21 app.use(express.bodyParser());22 app.use(express.methodOverride());23 app.use(express.cookieParser('keyboard cat'));24 app.use(express.session());22- app.use(require('./middleware/locals'));23- app.use(messages());25 app.use(app.router);26 app.use(express.static(__dirname + '/public'));27 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));28 });29 30+// Locals31+32+app.locals.use(function(req, res){33+ // expose "error" and "message" to all34+ // views that are rendered.35+ res.locals.error = req.session.error || '';36+ res.locals.message = req.session.message || '';37+ // remove them so they're not displayed on subsequent renders38+ delete req.session.error;39+ delete req.session.message;40+});41+42 // Routes43 44 require('./routes/site')(app);45 require('./routes/post')(app);5 unmodified linesmodified:examples/cookies/app.js+7 added-4 removed
2 unmodified lines3 * Module dependencies.4 */5 6 var express = require('../../')7- , app = express();7+ , app = module.exports = express();8 9 10 // add favicon() before logger() so11 // GET /favicon.ico requests are not2 unmodified lines14 // call next()15 app.use(express.favicon());16 17 // custom log format18+if ('test' != process.env.NODE_ENV)18-app.use(express.logger(':method :url'));19+ app.use(express.logger(':method :url'));20 21 // parses request cookies, populating22 // req.cookies and req.signedCookies23 // when the secret is passed, used 23 unmodified lines47 if (req.body.remember) res.cookie('remember', 1, { maxAge: minute });48 res.redirect('back');49 });50 51+if (!module.parent){50-app.listen(3000);51-console.log('Express started on port 3000');52+ app.listen(3000);53+ console.log('Express started on port 3000');54+}modified:examples/downloads/app.js+9 added-7 removed
2 unmodified lines3 * Module dependencies.4 */5 6 var express = require('../../')7- , app = express();7+ , app = module.exports = express();8 9 app.get('/', function(req, res){10 res.send('<ul>'11 + '<li>Download <a href="/files/amazing.txt">amazing.txt</a>.</li>'14 unmodified lines26 // below our routes, you will be able to27 // "intercept" errors, otherwise Connect28 // will respond with 500 "Internal Server Error".29 app.use(function(err, req, res, next){30- // log all errors31- console.error(err.stack);32-33- // special-case 404s30+ // special-case 404s,31+ // remember you could32+ // render a 404 template here33 if (404 == err.status) {34+ res.statusCode = 404;35 res.send('Cant find that file, sorry!');36 } else {37 next(err);38 }39 });40 41+if (!module.parent) {41-app.listen(3000);42-console.log('Express started on port 3000');42+ app.listen(3000);43+ console.log('Express started on port 3000');44+}modified:examples/error/app.js+9 added-5 removed
2 unmodified lines3 * Module dependencies.4 */5 6 var express = require('../../')7- , app = express();7+ , app = module.exports = express();8 9+if ('test' != process.env.NODE_ENV)9-app.use(express.logger('dev'));10+ app.use(express.logger('dev'));11 app.use(app.router);12 13 // the error handler is strategically14 // placed *below* the app.router; if it8 unmodified lines23 // in different orders etc.24 25 function error(err, req, res, next) {26 // log it27+ if ('test' != process.env.NODE_ENV)26- console.error(err.stack);28+ console.error(err.stack);29 30 // respond with 500 "Internal Server Error".31 res.send(500);32 }9 unmodified lines42 next(new Error('oh no!'));43 });44 });45 46+if (!module.parent) {44-app.listen(3000);45-console.log('app listening on port 3000');47+ app.listen(3000);48+ console.log('Express started on port 3000');49+}modified:examples/error-pages/app.js+8 added-5 removed
2 unmodified lines3 * Module dependencies.4 */5 6 var express = require('../../')7- , app = express();7+ , app = module.exports = express()8+ , silent = 'test' == process.env.NODE_ENV;9 10 app.set('views', __dirname + '/views');11 app.set('view engine', 'jade');12 13 app.use(express.favicon());13-app.use(express.logger('dev'));14 15+silent || app.use(express.logger('dev'));16+17 // "app.router" positions our routes 18 // above the middleware defined below,19 // this means that Express will attempt20 // to match & call routes _before_ continuing12 unmodified lines33 34 app.use(function(req, res, next){35 // respond with html page36 if (req.accepts('html')) {35- console.log('test');37 res.status(404);38 res.render('404', { url: req.url });39 return;40 }47 unmodified lines88 app.get('/500', function(req, res, next){89 next(new Error('keyboard cat!'));90 });91 92+if (!module.parent) {91-app.listen(3000);92-console.log('Express app started on port 3000');93+ app.listen(3000);94+ silent || console.log('Express started on port 3000');95+}deleted:examples/flash/views/index.ejs-3 removed
1-<h1>Flash Message Example</h1>2-<p>on page <%- page %></p>3-<%- messages() %>deleted:examples/flash/views/layout.ejs-5 removed
1-<html>2- <body>3- <%- body %>4- </body>5-</html>deleted:examples/flash/app.js-46 removed
1-2-/**3- * Module dependencies.4- */5-6-var express = require('../../lib/express');7-8-// App with session support9-10-var app = express.createServer(11- express.cookieParser()12- , express.session({ secret: 'keyboard cat' })13-);14-15-// View settings16-17-app.set('views', __dirname + '/views');18-app.set('view engine', 'ejs');19-20-app.dynamicHelpers({21- // express-messages is a dynamicHelper that22- // renders the flash messages to HTML for you23- // $ npm install express-messages24- messages: require('express-messages')25-});26-27-app.dynamicHelpers({28- // Another dynamic helper example. Since dynamic29- // helpers resolve at view rendering time, we can30- // "inject" the "page" local variable per request31- // providing us with the request url.32- page: function(req, res){33- return req.url;34- } 35-});36-37-app.get('/', function(req, res){38- // Not very realistic notifications but illustrates usage39- req.flash('info', 'email queued');40- req.flash('info', 'email sent');41- req.flash('error', 'delivery failed');42- res.render('index');43-});44-45-app.listen(3000);46-console.log('Express app started on port 3000');modified:examples/form/app.js+6 added-8 removed
1-2-// Expose modules in ./support for demo purposes3-require.paths.unshift(__dirname + '/../../support');4-1 /**2 * Module dependencies.3 */4 9-var express = require('../../lib/express');5+var express = require('../../');6 11-var app = express.createServer();7+var app = module.exports = express();8 9 // Here we use the bodyDecoder middleware10 // to parse urlencoded request bodies11 // which populates req.body60 unmodified lines72 req.flash('info', 'Updated ' + req.body.name);73 res.redirect('/?name=' + req.body.name);74 });75 76+if (!module.parent) {80-app.listen(3000);81-console.log('Express app started on port 3000');77+ app.listen(3000);78+ console.log('Express started on port 3000');79+}modified:examples/format/app.js+8 added-7 removed
1 unmodified line2 /**3 * Module dependencies.4 */5 6-var express = require('../../lib/express');6+var express = require('../../');7 8-var app = express.createServer();8+var app = module.exports = express();9 10 // Fake items11 12 var items = [31 unmodified lines44 var xml = ''45 + '<items>'46 + '<item>' + item.name + '</item>'47 + '</items>';48- res.contentType('.xml');49- res.send(xml);48+ res.type('xml').send(xml);49 break;50 case 'html':51 default:52 // By default send some hmtl7 unmodified lines60 });61 62 // Middleware63 65-app.use(express.errorHandler({ showStack: true }));64+app.use(express.errorHandler());65 66+if (!module.parent) {67-app.listen(3000);68-console.log('Express app started on port 3000');67+ app.listen(3000);68+ silent || console.log('Express started on port 3000');69+}modified:examples/github/views/index.jade+14 added-8 removed
1+2+extends layout3+4+block content1-- each user in users2- .user3- h2= user.name4- p.summary5- | <a href="http://github.com/#{user.name}">#{user.name}</a> has6- | <strong>#{user.repos.length}</strong> repositories 7- | with a total of <strong>#{user.totalWatchers}</strong> watchers.8- table#repos!= partial('repo', user.repos)5+ each user in users6+ .user7+ h2= user.name8+ p.summary9+ | <a href="http://github.com/#{user.name}">#{user.name}</a> has10+ | <strong>#{user.repos.length}</strong> repositories 11+ | with a total of <strong>#{user.totalWatchers}</strong> watchers.12+ table#repos13+ for repo in user.repos14+ include repomodified:examples/github/views/layout.jade+2 added-1 removed
2 unmodified lines3 head4 title Github Example5 link(rel="stylesheet", href="/style.css")6 body7- #container!= body7+ #container8+ block contentmodified:examples/github/app.js+1 added-1 removed
4 unmodified lines5 6 var express = require('../../lib/express')7 , http = require('http');8 9-var app = express.createServer();9+var app = express();10 11 // Expose our views12 13 app.set('views', __dirname + '/views');100 unmodified linesmodified:examples/helloworld/app.js+3 added-2 removed
1 unmodified line2 /**3 * Module dependencies.4 */5 6-var express = require('../../lib/express');6+var express = require('../../');7 8-var app = express.createServer();8+var app = express();9 10 app.get('/', function(req, res){11 res.send('Hello World');12 });13 14 app.listen(3000);15+console.log('Express started on port 3000');modified:examples/markdown/app.js+29 added-22 removed
1 unmodified line2 /**3 * Module dependencies.4 */5 6-var express = require('../../lib/express')7- , md = require('node-markdown').Markdown;6+var express = require('../../')7+ , fs = require('fs')8+ , md = require('github-flavored-markdown').parse;9 9-var app = express.createServer();10+var app = module.exports = express();11 11-// register .md so that markdown may comply12-// with the express view system by implementing13-// a .compile() method12+// register .md as an engine in express view system13 15-app.register('.md', {16- compile: function(str, options){17- var html = md(str);18- return function(locals){19- return html.replace(/\{([^}]+)\}/g, function(_, name){20- return locals[name];21- });22- };23- }24-});14+app.engine('md', function(path, options, fn){15+ fs.readFile(path, 'utf8', function(err, str){16+ if (err) return fn(err);17+ try{18+ var html = md(str);19+ html = html.replace(/\{([^}]+)\}/g, function(_, name){20+ return options[name];21+ })22+ fn(null,html)23+ } catch(e){24+ fn(e)25+ }26+ })27+})28 26-// Optional since express defaults to CWD/views27-29 app.set('views', __dirname + '/views');30 app.set('view engine', 'md');31 32 app.get('/', function(req, res){32- res.render('index', { layout: false, title: 'Markdown Example' });33-});33+ res.render('index', { title: 'Markdown Example' });34+})35 36+app.get('/fail', function(req, res){37+ res.render('missing', { title: 'Markdown Example' });38+})39+40+if (!module.parent) {35-app.listen(3000);36-console.log('Express app started on port 3000');41+ app.listen(3000);42+ console.log('Express started on port 3000');43+}deleted:examples/mounting/app.js-23 removed
1-/**2- * Module dependencies.3- */4-5-var express = require('../../lib/express')6- , blog = require('../blog/app');7-8-var app = express.createServer();9-10-app.use(express.cookieParser());11-app.use(express.session({ secret: 'keyboard cat' }));12-13-// mount the blog. the blog app is written using the "base"14-// local variable, allowing its urls to adjust to wherever15-// we wish to mount it.16-app.use('/blog', blog);17-18-app.get('/', function(req, res){19- res.send('Visit <a href="/blog">/blog</a>');20-});21-22-app.listen(3000);23-console.log('Server listening on port 3000');modified:examples/multipart/app.js+19 added-29 removed
1 unmodified line2 /**3 * Module dependencies.4 */5 6-var express = require('../../lib/express')7- , form = require('connect-form');6+var express = require('../../')7+ , format = require('util').format;8 9-var app = express.createServer(10- // connect-form (http://github.com/visionmedia/connect-form)11- // middleware uses the formidable middleware to parse urlencoded12- // and multipart form data13- form({ keepExtensions: true })14-);9+var app = module.exports = express()10 11+// bodyParser in connect 2.x uses node-formidable to parse 12+// the multipart form data.13+app.use(express.bodyParser())14+15 app.get('/', function(req, res){16 res.send('<form method="post" enctype="multipart/form-data">'17+ + '<p>Title: <input type="text" name="title" /></p>'18 + '<p>Image: <input type="file" name="image" /></p>'19 + '<p><input type="submit" value="Upload" /></p>'20 + '</form>');21 });22 23 app.post('/', function(req, res, next){24 25- // connect-form adds the req.form object26- // we can (optionally) define onComplete, passing27- // the exception (if any) fields parsed, and files parsed28- req.form.complete(function(err, fields, files){29- if (err) {30- next(err);31- } else {32- console.log('\nuploaded %s to %s'33- , files.image.filename34- , files.image.path);35- res.redirect('back');36- }37- });25+ // the uploaded file can be found as `req.files.image` and the26+ // title field as `req.body.title`27 39- // We can add listeners for several form40- // events such as "progress"41- req.form.on('progress', function(bytesReceived, bytesExpected){42- var percent = (bytesReceived / bytesExpected * 100) | 0;43- process.stdout.write('Uploading: %' + percent + '\r');44- });28+ res.send(format('\nuploaded %s (%d Kb) to %s as %s'29+ , req.files.image.name30+ , (req.files.image.size / 1024) << 0 31+ , req.files.image.path32+ , req.body.title));33 });34 35+if (!module.parent) {47-app.listen(3000);48-console.log('Express app started on port 3000');36+ app.listen(3000);37+ console.log('Express started on port 3000');38+}modified:examples/params/app.js+14 added-5 removed
1 unmodified line2 /**3 * Module dependencies.4 */5 6-var express = require('../../lib/express')7- , app = express.createServer();6+var express = require('../../')7+ , app = module.exports = express();8 9 // Faux database10 11 var users = [5 unmodified lines17 ];18 19 // Convert :to and :from to integers20 21-app.param(['to', 'from'], function(n){ return parseInt(n, 10); });21+app.param(['to', 'from'], function(req, res, next, num, name){ 22+ req.params[name] = num = parseInt(num, 10);23+ if( isNaN(num) ){24+ next(new Error('failed to parseInt '+num));25+ } else {26+ next();27+ }28+});29 30 // Load user by id31 32 app.param('user', function(req, res, next, id){30 unmodified lines63 , names = users.map(function(user){ return user.name; });64 res.send('users ' + names.slice(from, to).join(', '));65 });66 67+if (!module.parent) {60-app.listen(3000);61-console.log('Express application listening on port 3000');68+ app.listen(3000);69+ console.log('Express started on port 3000');70+}modified:examples/resource/app.js+6 added-4 removed
1 unmodified line2 /**3 * Module dependencies.4 */5 6-var express = require('../../lib/express');6+var express = require('../../');7 8-var app = express.createServer();8+var app = module.exports = express();9 10 // Ad-hoc example resource method11 12 app.resource = function(path, obj) {71 unmodified lines84 , '</ul>'85 ].join('\n')); 86 });87 88+if (!module.parent) {88-app.listen(3000);89-console.log('Express app started on port 3000');89+ app.listen(3000);90+ console.log('Express started on port 3000');91+}added:test/acceptance/auth.js+93 added
1+var app = require('../../examples/auth/app')2+ , request = require('../support/http');3+4+function redirects(to,fn){5+ return function(res){6+ res.statusCode.should.equal(302)7+ res.headers.should.have.property('location').match(to);8+ fn()9+ }10+}11+12+function getCookie(res) {13+ return res.headers['set-cookie'][0].split(';')[0];14+}15+16+describe('auth', function(){17+ var cookie;18+19+ describe('GET /',function(){20+ it('should redirect to /login', function(done){21+ request(app)22+ .get('/')23+ .end(redirects(/\/login$/,done))24+ })25+ })26+27+ describe('GET /restricted (w/o cookie)',function(){28+ it('should redirect to /login', function(done){29+ request(app)30+ .get('/restricted')31+ .end(redirects(/\/login$/,done))32+ })33+ })34+35+ describe('POST /login', function(){36+ it('should fail without proper credentials', function(done){37+ request(app)38+ .post('/login')39+ .set('content-type','application/x-www-form-urlencoded')40+ .write('&username=not-tj&password=foobar')41+ .end(redirects(/\/login$/,done))42+ })43+44+ it('should authenticate', function(done){45+ request(app)46+ .post('/login')47+ .set('content-type', 'application/x-www-form-urlencoded')48+ .write('username=tj&password=foobar')49+ .end(function(res){50+ res.statusCode.should.equal(302);51+ cookie = getCookie(res);52+ request(app)53+ .get('/login')54+ .set('Cookie', cookie)55+ .end(function(res){56+ res.body.should.include('Authenticated as tj');57+ done();58+ })59+ })60+ })61+ })62+63+ describe('GET /restricted (w. cookie)',function(){64+ it('should respond with 200', function(done){65+ request(app)66+ .get('/restricted')67+ .set('Cookie', cookie)68+ .expect(200, done);69+ })70+ })71+72+ describe('GET /logout',function(){73+ it('should respond with 302 and clear cookie',function(done){74+ request(app)75+ .get('/logout')76+ .set('Cookie', cookie)77+ .end(function(res){78+ res.statusCode.should.equal(302);79+ res.headers.should.not.have.property('set-cookie')80+ done();81+ })82+ })83+ })84+85+ describe('GET /restricted (w. expired cookie)',function(){86+ it('should respond with 302',function(done){87+ request(app)88+ .get('/restricted')89+ .set('Cookie', cookie)90+ .expect(302, done)91+ })92+ })93+})added:test/acceptance/blog.js+78 added
1+var app = require('../../examples/blog/app')2+ , request = require('../support/http');3+4+var authorization = 'Basic ' + Buffer('admin:express').toString('base64');5+6+function redirects(to,fn){7+ return function(res){8+ res.statusCode.should.equal(302)9+ res.headers.should.have.property('location').match(to);10+ fn()11+ }12+}13+14+describe('blog', function(){15+ describe('GET /', function(){16+ it('should have no posts', function(done){17+ request(app)18+ .get('/')19+ .expect(/you have no posts/, done)20+ })21+ })22+23+ describe('GET /post/add', function(){24+ it('should require auth', function(done){25+ request(app)26+ .get('/post/add')27+ .expect(401, done)28+ })29+30+ it('should login', function(done){31+ request(app)32+ .get('/post/add')33+ .set('Authorization', authorization)34+ .expect(/<h1>New Post<\/h1>/, done)35+ })36+ })37+38+ describe('POST /post', function(){39+ it('should require auth', function(done){40+ request(app)41+ .post('/post')42+ .expect(401, done)43+ })44+45+ it('should redirect to / with no title or body', function(done){46+ request(app)47+ .post('/post')48+ .set('Authorization', authorization)49+ .end(redirects(/\/$/, done))50+ })51+52+ it('should redirect to / with no body', function(done){53+ request(app)54+ .post('/post')55+ .set('Authorization', authorization)56+ .set('Content-Type', 'application/x-www-form-urlencoded')57+ .write('post[title]=Kittens')58+ .end(redirects(/\/$/, done))59+ })60+61+ it('should redirect to /post/:post when successful', function(done){62+ request(app)63+ .post('/post')64+ .set('Authorization', authorization)65+ .set('Content-Type', 'application/x-www-form-urlencoded')66+ .write('post[title]=Kittens&post[body]=In+very+large+baskets')67+ .end(redirects(/\/post\/\d+$/, done))68+ })69+ })70+71+ describe('GET /', function(){72+ it('should now list 1 post',function(done){73+ request(app)74+ .get('/')75+ .expect(/Display all 1 post/, done)76+ })77+ })78+})added:test/acceptance/cookies.js+33 added
1+var app = require('../../examples/cookies/app')2+ , request = require('../support/http');3+4+describe('cookies', function(){5+ describe('GET /', function(){6+ it('should have a form', function(done){7+ request(app)8+ .get('/')9+ .expect(/<form/,done)10+ })11+ it('should respond with no cookies', function(done){12+ request(app)13+ .get('/')14+ .end(function(res){15+ res.headers.should.not.have.property('set-cookie')16+ done()17+ })18+ })19+ })20+21+ describe('POST /', function(){22+ it('should set a cookie', function(done){23+ request(app)24+ .post('/')25+ .set('Content-Type','application/x-www-form-urlencoded')26+ .write('remember=1')27+ .end(function(res){28+ res.headers.should.have.property('set-cookie')29+ done()30+ })31+ })32+ })33+})added:test/acceptance/downloads.js+32 added
1+var app = require('../../examples/downloads/app')2+ , request = require('../support/http');3+4+describe('downloads', function(){5+ describe('GET /', function(){6+ it('should have a link to amazing.txt', function(done){7+ request(app)8+ .get('/')9+ .expect(/href="\/files\/amazing.txt"/,done)10+ })11+ })12+13+ describe('GET /files/amazing.txt', function(){14+ it('should have a download header', function(done){15+ request(app)16+ .get('/files/amazing.txt')17+ .end(function(res){18+ res.should.have.property('statusCode',200)19+ res.headers.should.have.property('content-disposition', 'attachment; filename="amazing.txt"')20+ done()21+ })22+ })23+ })24+25+ describe('GET /files/missing.txt', function(){26+ it('should respond with 404', function(done){27+ request(app)28+ .get('/files/missing.txt')29+ .expect(404,done)30+ })31+ })32+})added:test/acceptance/error-pages.js+101 added
1+var app = require('../../examples/error-pages/app')2+ , request = require('../support/http');3+4+describe('error-pages', function(){5+ describe('GET /', function(){6+ it('should respond with page list', function(done){7+ request(app)8+ .get('/')9+ .expect(/Pages Example/,done)10+ })11+ })12+13+ describe('Accept: text/html',function(){14+ describe('GET /403', function(){15+ it('should respond with 403', function(done){16+ request(app)17+ .get('/403')18+ .expect(403,done)19+ })20+ })21+ describe('GET /404', function(){22+ it('should respond with 404', function(done){23+ request(app)24+ .get('/404')25+ .expect(404,done)26+ })27+ })28+ describe('GET /500', function(){29+ it('should respond with 500', function(done){30+ request(app)31+ .get('/500')32+ .expect(500,done)33+ })34+ })35+ })36+37+38+ describe('Accept: application/json',function(){39+ describe('GET /403', function(){40+ it('should respond with 403', function(done){41+ request(app)42+ .get('/403')43+ .set('Accept','application/json')44+ .expect(403,done)45+ })46+ })47+ describe('GET /404', function(){48+ it('should respond with 404', function(done){49+ request(app)50+ .get('/404')51+ .set('Accept','application/json')52+ .end(function(res){53+ res.should.have.property('statusCode',200)54+ res.should.have.property('body',JSON.stringify({error:'Not found'}))55+ done()56+ })57+ })58+ })59+ describe('GET /500', function(){60+ it('should respond with 500', function(done){61+ request(app)62+ .get('/500')63+ .set('Accept','application/json')64+ .expect(500,done)65+ })66+ })67+ })68+69+70+ describe('Accept: text/plain',function(){71+ describe('GET /403', function(){72+ it('should respond with 403', function(done){73+ request(app)74+ .get('/403')75+ .set('Accept','text/plain')76+ .expect(403,done)77+ })78+ })79+ describe('GET /404', function(){80+ it('should respond with 404', function(done){81+ request(app)82+ .get('/404')83+ .set('Accept','text/plain')84+ .end(function(res){85+ res.should.have.property('statusCode',200)86+ res.should.have.property('body','Not found')87+ done()88+ })89+ })90+ })91+ describe('GET /500', function(){92+ it('should respond with 500', function(done){93+ request(app)94+ .get('/500')95+ .set('Accept','text/plain')96+ .expect(500,done)97+ })98+ })99+ })100+101+})added:test/acceptance/error.js+28 added
1+var app = require('../../examples/error/app')2+ , request = require('../support/http');3+4+describe('error', function(){5+ describe('GET /', function(){6+ it('should respond with 500', function(done){7+ request(app)8+ .get('/')9+ .expect(500,done)10+ })11+ })12+13+ describe('GET /next', function(){14+ it('should respond with 500', function(done){15+ request(app)16+ .get('/next')17+ .expect(500,done)18+ })19+ })20+21+ describe('GET /missing', function(){22+ it('should respond with 404', function(done){23+ request(app)24+ .get('/missing')25+ .expect(404,done)26+ })27+ })28+})added:test/acceptance/format.js+52 added
1+var app = require('../../examples/format/app')2+ , request = require('../support/http');3+4+describe('format', function(){5+ describe('GET /', function(){6+ it('should respond with 200', function(done){7+ request(app)8+ .get('/')9+ .expect(200,done)10+ })11+ })12+13+ describe('GET /item/2', function(){14+ it('should respond with html', function(done){15+ request(app)16+ .get('/item/2')17+ .end(function(res){18+ res.should.have.property('statusCode',200)19+ res.should.have.property('body','<h1>baz</h1>')20+ res.headers.should.have.property('content-type','text/html; charset=utf-8')21+ done()22+ })23+ })24+ })25+26+ describe('GET /item/2.json', function(){27+ it('should respond with json', function(done){28+ request(app)29+ .get('/item/2.json')30+ .end(function(res){31+ res.should.have.property('statusCode',200)32+ res.should.have.property('body','{"name":"baz"}')33+ res.headers.should.have.property('content-type','application/json; charset=utf-8')34+ done()35+ })36+ })37+ })38+39+ describe('GET /item/2.xml', function(){40+ it('should respond with xml', function(done){41+ request(app)42+ .get('/item/2.xml')43+ .end(function(res){44+ res.should.have.property('statusCode',200)45+ res.should.have.property('body','<items><item>baz</item></items>')46+ res.headers.should.have.property('content-type','application/xml')47+ done()48+ })49+ })50+ })51+52+})added:test/acceptance/markdown.js+20 added
1+var app = require('../../examples/markdown/app')2+ , request = require('../support/http');3+4+describe('markdown', function(){5+ describe('GET /', function(){6+ it('should respond with html', function(done){7+ request(app)8+ .get('/')9+ .expect(/<h1>Markdown Example<\/h1>/,done)10+ })11+ })12+13+ describe('GET /fail',function(){14+ it('should respond with an error', function(done){15+ request(app)16+ .get('/fail')17+ .expect(500,done)18+ })19+ })20+})added:test/acceptance/multipart.js+40 added
1+var app = require('../../examples/multipart/app')2+ , fs = require('fs')3+ , request = require('../support/http');4+5+var logo = fs.readFileSync(__dirname+'/../../docs/images/logo.png')6+ , boundary = '------expressmultipart';7+8+describe('multipart', function(){9+ describe('GET /', function(){10+ it('should respond with a form', function(done){11+ request(app)12+ .get('/')13+ .expect(/<form/,done)14+ })15+ })16+17+ describe('POST /', function(){18+ it('should upload logo as multipart', function(done){19+ request(app)20+ .post('/')21+ .set('content-type','multipart/form-data; boundary='+boundary.slice(2))22+ .write(boundary+'\r\n')23+ .write('Content-Disposition: form-data; name="title"\r\n')24+ .write('\r\n')25+ .write('logo\r\n')26+ .write(boundary+'\r\n')27+ .write('Content-Disposition: form-data; name="image"; filename="logo.png"\r\n')28+ .write('Content-Type: image/png\r\n')29+ .write('\r\n')30+ .write(logo+'\r\n')31+ .write(boundary+'--\r\n')32+ .end(function(res){33+ res.body.should.match(/uploaded logo.png/)34+ res.body.should.match(/\(12 Kb\)/)35+ res.body.should.match(/as logo/)36+ done()37+ })38+ })39+ })40+})added:test/acceptance/params.js+28 added
1+var app = require('../../examples/params/app')2+ , request = require('../support/http');3+4+describe('params', function(){5+ describe('GET /', function(){6+ it('should respond with instructions', function(done){7+ request(app)8+ .get('/')9+ .expect(/Visit/,done)10+ })11+ })12+13+ describe('GET /user/0', function(){14+ it('should respond with a user', function(done){15+ request(app)16+ .get('/user/0')17+ .expect(/user tj/,done)18+ })19+ })20+21+ describe('GET /users/0-2', function(){22+ it('should respond with three users', function(done){23+ request(app)24+ .get('/users/0-2')25+ .expect(/users tj, tobi/,done)26+ })27+ })28+})added:test/acceptance/resource.js+52 added
1+var app = require('../../examples/resource/app')2+ , request = require('../support/http');3+4+describe('resource', function(){5+ describe('GET /', function(){6+ it('should respond with instructions', function(done){7+ request(app)8+ .get('/')9+ .expect(/^<h1>Examples:<\/h1>/,done)10+ })11+ })12+13+ describe('GET /users', function(){14+ it('should respond with all users', function(done){15+ request(app)16+ .get('/users')17+ .expect(/^\[{"name":"tj"},{"name":"ciaran"},{"name":"aaron"},{"name":"guillermo"},{"name":"simon"},{"name":"tobi"}\]/,done)18+ })19+ })20+21+ describe('GET /users/1', function(){22+ it('should respond with user 1', function(done){23+ request(app)24+ .get('/users/1')25+ .expect(/^{"name":"ciaran"}/,done)26+ })27+ })28+29+ describe('GET /users/1..3', function(){30+ it('should respond with users 1 through 3', function(done){31+ request(app)32+ .get('/users/1..3')33+ .expect(/^<ul><li>ciaran<\/li>\n<li>aaron<\/li>\n<li>guillermo<\/li><\/ul>/,done)34+ })35+ })36+37+ describe('DELETE /users/1', function(){38+ it('should respond with users 1 through 3', function(done){39+ request(app)40+ .delete('/users/1')41+ .expect(/^destroyed/,done)42+ })43+ })44+45+ describe('GET /users/1..3.json', function(){46+ it('should respond with users 2 and 3 as json', function(done){47+ request(app)48+ .get('/users/1..3.json')49+ .expect(/^\[null,{"name":"aaron"},{"name":"guillermo"}\]/,done)50+ })51+ })52+})modified:test/support/http.js+2 added
57 unmodified lines58 Request.prototype.expect = function(body, fn){59 this.end(function(res){60 if ('number' == typeof body) {61 res.statusCode.should.equal(body);62+ } else if (body instanceof RegExp) {63+ res.body.should.match(body);64 } else {65 res.body.should.equal(body);66 }67 fn();38 unmodified linesmodified:Makefile+1 added-1 removed
33 unmodified lines34 35 docclean:36 rm -f docs/*.{1,html}37 38-.PHONY: site test benchmark docs docclean test-acceptance38+.PHONY: site test benchmark docs docclean test-acceptancemodified:package.json+2 added-1 removed
20 unmodified lines21 "mocha": "*",22 "jade": "*",23 "stylus": "*",24 "should": "*",25- "connect-redis": "*"25+ "connect-redis": "*",26+ "github-flavored-markdown": "*"27 },28 "keywords": ["express", "framework", "sinatra", "web", "rest", "restful", "router"],29 "repository": "git://github.com/visionmedia/express",30 "main": "index",8 unmodified lines