Merge tag '4.16.2'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Douglas Christopher Wilson · committed by Douglas Christopher Wilson · parents 8fabed8, 351396f · Browse files · 31 files·+497 added−112 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
31 files+497 added−112 removed
- tests:+262 added−42 removed
- other:+235 added−70 removed
Provenance
- Commit
62e12fe- Tree
20241ea- Author
Douglas Christopher Wilson <doug@somethingdoug.com>- Committer
Douglas Christopher Wilson <doug@somethingdoug.com>- Parent 1
8fabed8- Parent 2
351396f
31 files changed+497 added−112 removed
modified:benchmarks/middleware.js+1 added-3 removed
11 unmodified lines12131415161716191718192011 unmodified lines next(); });}
var body = new Buffer('Hello World');
app.use(function(req, res, next){ res.send(body); res.send('Hello World')});
app.listen(3333);modified:examples/auth/index.js+1 added-2 removed
12345667895 unmodified lines15161718201920212223107 unmodified linesExpand all/** * Module dependencies. */
var express = require('../..');var bodyParser = require('body-parser');var hash = require('pbkdf2-password')()var path = require('path');var session = require('express-session');
5 unmodified linesapp.set('views', path.join(__dirname, 'views'));
// middleware
app.use(bodyParser.urlencoded({ extended: false }));app.use(express.urlencoded({ extended: false }))app.use(session({ resave: false, // don't save session if unmodified saveUninitialized: false, // don't create session until something stored secret: 'shhhh, very secret'107 unmodified linesExpand allmodified:examples/cookies/index.js+1 added-2 removed
4 unmodified lines5 var express = require('../../');6 var app = module.exports = express();7 var logger = require('morgan');8 var cookieParser = require('cookie-parser');9-var bodyParser = require('body-parser');9 10 // custom log format11 if ('test' != process.env.NODE_ENV) app.use(logger(':method :url'));12 3 unmodified lines16 // for signing the cookies.17 app.use(cookieParser('my secret here'));18 19 // parses x-www-form-urlencoded21-app.use(bodyParser.urlencoded({ extended: false }));20+app.use(express.urlencoded({ extended: false }))21 22 app.get('/', function(req, res){23 if (req.cookies.remember) {24 res.send('Remembered :). Click to <a href="/forget">forget</a>!.');23 unmodified linesmodified:examples/mvc/index.js+1 added-2 removed
4 unmodified lines5 var express = require('../..');6 var logger = require('morgan');7 var path = require('path');8 var session = require('express-session');9-var bodyParser = require('body-parser');9 var methodOverride = require('method-override');10 11 var app = module.exports = express();12 28 unmodified lines41 secret: 'some secret here'42 }));43 44 // parse request bodies (req.body)46-app.use(bodyParser.urlencoded({ extended: true }));45+app.use(express.urlencoded({ extended: true }))46 47 // allow overriding methods in query (?_method=put)48 app.use(methodOverride('_method'));49 44 unmodified linesmodified:examples/route-separation/index.js+1 added-2 removed
5 unmodified lines6 var path = require('path');7 var app = express();8 var logger = require('morgan');9 var cookieParser = require('cookie-parser');10-var bodyParser = require('body-parser');10 var methodOverride = require('method-override');11 var site = require('./site');12 var post = require('./post');13 var user = require('./user');11 unmodified lines25 }26 27 app.use(methodOverride('_method'));28 app.use(cookieParser());30-app.use(bodyParser.urlencoded({ extended: true }));29+app.use(express.urlencoded({ extended: true }))30 app.use(express.static(path.join(__dirname, 'public')));31 32 // General33 20 unmodified linesmodified:lib/application.js+2 added-2 removed
203 unmodified lines204 205 var fns = flatten(slice.call(arguments, offset));206 207 if (fns.length === 0) {208- throw new TypeError('app.use() requires middleware functions');208+ throw new TypeError('app.use() requires a middleware function')209 }210 211 // get router212 var router = this.router;118 unmodified lines331 /**332 * Assign `setting` to `val`, or return `setting`'s value.333 *334 * app.set('foo', 'bar');335- * app.get('foo');335+ * app.set('foo');336 * // => "bar"337 *338 * Mounted servers inherit their parent server's settings.339 *291 unmodified linesmodified:lib/express.js+3 added
10 unmodified lines11 /**12 * Module dependencies.13 */14 15+var bodyParser = require('body-parser')16 var EventEmitter = require('events').EventEmitter;17 var mixin = require('merge-descriptors');18 var proto = require('./application');19 var Router = require('router');53 unmodified lines73 /**74 * Expose middleware75 */76 77+exports.json = bodyParser.json78 exports.static = require('serve-static');79+exports.urlencoded = bodyParser.urlencodedmodified:lib/request.js+6 added-2 removed
292 unmodified lines293 }294 295 // Note: X-Forwarded-Proto is normally only ever a296 // single value, but this is to be safe.297- proto = this.get('X-Forwarded-Proto') || proto;298- return proto.split(/\s*,\s*/)[0];297+ var header = this.get('X-Forwarded-Proto') || proto298+ var index = header.indexOf(',')299+300+ return index !== -1301+ ? header.substring(0, index).trim()302+ : header.trim()303 });304 305 /**306 * Short-hand for:205 unmodified linesmodified:lib/response.js+79 added-18 removed
10 unmodified lines11 * Module dependencies.12 * @private13 */14 15+var Buffer = require('safe-buffer').Buffer16 var contentDisposition = require('content-disposition');17 var encodeUrl = require('encodeurl');18 var escapeHtml = require('escape-html');19 var http = require('http');74 unmodified lines94 * Send a response.95 *96 * Examples:97 *97- * res.send(new Buffer('wahoo'));98+ * res.send(Buffer.from('wahoo'));99 * res.send({ some: 'json' });100 * res.send('<p>some html</p>');101 *102 * @param {string|number|boolean|object|Buffer} body2 unmodified lines105 106 res.send = function send(body) {107 var chunk = body;108 var encoding;108- var len;109 var req = this.req;110 var type;111 112 // settings31 unmodified lines144 this.set('Content-Type', setCharset(type, 'utf-8'));145 }146 }147 148+ // determine if ETag should be generated149+ var etagFn = app.get('etag fn')150+ var generateETag = !this.get('ETag') && typeof etagFn === 'function'151+152 // populate Content-Length153+ var len154 if (chunk !== undefined) {150- if (!Buffer.isBuffer(chunk)) {151- // convert chunk to Buffer; saves later double conversions152- chunk = new Buffer(chunk, encoding);155+ if (Buffer.isBuffer(chunk)) {156+ // get length of Buffer157+ len = chunk.length158+ } else if (!generateETag && chunk.length < 1000) {159+ // just calculate length when no ETag + small chunk160+ len = Buffer.byteLength(chunk, encoding)161+ } else {162+ // convert chunk to Buffer and calculate163+ chunk = Buffer.from(chunk, encoding)164 encoding = undefined;165+ len = chunk.length166 }167 156- len = chunk.length;168 this.set('Content-Length', len);169 }170 171 // populate ETag172 var etag;162- var generateETag = len !== undefined && app.get('etag fn');163- if (typeof generateETag === 'function' && !this.get('ETag')) {164- if ((etag = generateETag(chunk, encoding))) {173+ if (generateETag && len !== undefined) {174+ if ((etag = etagFn(chunk, encoding))) {175 this.set('ETag', etag);176 }177 }178 33 unmodified lines212 213 res.json = function json(obj) {214 // settings215 var app = this.app;216+ var escape = app.get('json escape')217 var replacer = app.get('json replacer');218 var spaces = app.get('json spaces');208- var body = stringify(obj, replacer, spaces);219+ var body = stringify(obj, replacer, spaces, escape)220 221 // content-type222 if (!this.get('Content-Type')) {223 this.set('Content-Type', 'application/json');16 unmodified lines240 241 res.jsonp = function jsonp(obj) {242 // settings243 var app = this.app;244+ var escape = app.get('json escape')245 var replacer = app.get('json replacer');246 var spaces = app.get('json spaces');235- var body = stringify(obj, replacer, spaces);247+ var body = stringify(obj, replacer, spaces, escape)248 var callback = this.req.query[app.get('jsonp callback name')];249 250 // content-type251 if (!this.get('Content-Type')) {7 unmodified lines259 }260 261 // jsonp262 if (typeof callback === 'string' && callback.length !== 0) {251- this.charset = 'utf-8';263 this.set('X-Content-Type-Options', 'nosniff');264 this.set('Content-Type', 'text/javascript');265 266 // restrict callback charset121 unmodified lines388 * and optional callback `callback(err)`. The callback is invoked389 * when the data transfer is complete, or when an error has390 * ocurred. Be sure to check `res.headersSent` if you plan to respond.391 *392+ * Optionally providing an `options` object to use with `res.sendFile()`.393+ * This function will set the `Content-Disposition` header, overriding394+ * any `Content-Disposition` header passed as header options in order395+ * to set the attachment and filename.396+ *397 * This method uses `res.sendFile()`.398 *399 * @public400 */401 386-res.download = function download(path, filename, callback) {402+res.download = function download (path, filename, options, callback) {403 var done = callback;404 var name = filename;405+ var opts = options || null406 390- // support function as second arg407+ // support function as second or third arg408 if (typeof filename === 'function') {409 done = filename;410 name = null;411+ opts = null412+ } else if (typeof options === 'function') {413+ done = options414+ opts = null415 }416 417 // set Content-Disposition when file is sent418 var headers = {419 'Content-Disposition': contentDisposition(name || path)420 };421 422+ // merge user-provided headers423+ if (opts && opts.headers) {424+ var keys = Object.keys(opts.headers)425+ for (var i = 0; i < keys.length; i++) {426+ var key = keys[i]427+ if (key.toLowerCase() !== 'content-disposition') {428+ headers[key] = opts.headers[key]429+ }430+ }431+ }432+433+ // merge user-provided options434+ opts = Object.create(opts)435+ opts.headers = headers436+437 // Resolve the full path for sendFile438 var fullPath = resolve(path);439 440+ // send file404- return this.sendFile(fullPath, { headers: headers }, done);441+ return this.sendFile(fullPath, opts, done)442 };443 444 /**445 * Set _Content-Type_ response header with `type` through `mime.lookup()`514 unmodified lines960 file.pipe(res);961 }962 963 /**927- * Stringify JSON, like JSON.stringify, but v8 optimized.964+ * Stringify JSON, like JSON.stringify, but v8 optimized, with the965+ * ability to escape characters that can trigger HTML sniffing.966+ *967+ * @param {*} value968+ * @param {function} replaces969+ * @param {number} spaces970+ * @param {boolean} escape971+ * @returns {string}972 * @private973 */974 931-function stringify(value, replacer, spaces) {975+function stringify (value, replacer, spaces, escape) {976 // v8 checks arguments.length for optimizing simple call977 // https://bugs.chromium.org/p/v8/issues/detail?id=4730934- return replacer || spaces978+ var json = replacer || spaces979 ? JSON.stringify(value, replacer, spaces)980 : JSON.stringify(value);981+982+ if (escape) {983+ json = json.replace(/[<>&]/g, function (c) {984+ switch (c.charCodeAt(0)) {985+ case 0x3c:986+ return '\\u003c'987+ case 0x3e:988+ return '\\u003e'989+ case 0x26:990+ return '\\u0026'991+ default:992+ return c993+ }994+ })995+ }996+997+ return json998 }modified:lib/utils.js+23 added-15 removed
10 unmodified lines11 * Module dependencies.12 * @api private13 */14 15-var mime = require('send').mime;15+var Buffer = require('safe-buffer').Buffer16 var contentType = require('content-type');17+var mime = require('send').mime;18 var etag = require('etag');19 var proxyaddr = require('proxy-addr');20 var qs = require('qs');21 var querystring = require('querystring');6 unmodified lines28 * @return {String}29 * @api private30 */31 31-exports.etag = function (body, encoding) {32- var buf = !Buffer.isBuffer(body)33- ? new Buffer(body, encoding)34- : body;32+exports.etag = createETagGenerator({ weak: false })33 36- return etag(buf, {weak: false});37-};38-34 /**35 * Return weak ETag for `body`.36 *37 * @param {String|Buffer} body1 unmodified line39 * @return {String}40 * @api private41 */42 48-exports.wetag = function wetag(body, encoding){49- var buf = !Buffer.isBuffer(body)50- ? new Buffer(body, encoding)51- : body;43+exports.wetag = createETagGenerator({ weak: true })44 53- return etag(buf, {weak: true});54-};55-45 /**46 * Normalize the given `type`, for example "html" becomes "text/html".47 *48 * @param {String} type172 unmodified lines221 return contentType.format(parsed);222 };223 224 /**225+ * Create an ETag generator function, generating ETags with226+ * the given options.227+ *228+ * @param {object} options229+ * @return {function}230+ * @private231+ */232+233+function createETagGenerator (options) {234+ return function generateETag (body, encoding) {235+ var buf = !Buffer.isBuffer(body)236+ ? Buffer.from(body, encoding)237+ : body238+239+ return etag(buf, options)240+ }241+}242+243+/**244 * Parse an extended query string with qs.245 *246 * @return {Object}247 * @private7 unmodified linesmodified:lib/view.js+9 added-1 removed
74 unmodified lines75 if (!opts.engines[this.ext]) {76 // load engine77 var mod = this.ext.substr(1)78 debug('require "%s"', mod)79+80+ // default engine export79- opts.engines[this.ext] = require(mod).__express81+ var fn = require(mod).__express82+83+ if (typeof fn !== 'function') {84+ throw new Error('Module "' + mod + '" does not provide a view engine.')85+ }86+87+ opts.engines[this.ext] = fn88 }89 90 // store loaded engine91 this.engine = opts.engines[this.ext];114 unmodified linesadded:test/fixtures/broken.send
modified:test/app.use.js+22 added-10 removed
1 2 var after = require('after');3-var assert = require('assert');3+var assert = require('assert')4 var express = require('..');5 var request = require('supertest');6 7 describe('app', function(){245 unmodified lines253 })254 })255 256 describe('.use(path, middleware)', function(){257- it('should reject missing functions', function () {258- var app = express();259- assert.throws(app.use.bind(app, '/'), /requires middleware function/);257+ it('should require middleware', function () {258+ var app = express()259+ assert.throws(function () { app.use('/') }, 'TypeError: app.use() requires a middleware function')260 })261 262- it('should reject non-functions as middleware', function () {263- var app = express();264- assert.throws(app.use.bind(app, '/', 'hi'), /argument handler must be a function/);265- assert.throws(app.use.bind(app, '/', 5), /argument handler must be a function/);266- assert.throws(app.use.bind(app, '/', null), /argument handler must be a function/);267- assert.throws(app.use.bind(app, '/', new Date()), /argument handler must be a function/);262+ it('should reject string as middleware', function () {263+ var app = express()264+ assert.throws(function () { app.use('/', 'foo') }, /argument handler must be a function/)265 })266 267+ it('should reject number as middleware', function () {268+ var app = express()269+ assert.throws(function () { app.use('/', 42) }, /argument handler must be a function/)270+ })271+272+ it('should reject null as middleware', function () {273+ var app = express()274+ assert.throws(function () { app.use('/', null) }, /argument handler must be a function/)275+ })276+277+ it('should reject Date as middleware', function () {278+ var app = express()279+ assert.throws(function () { app.use('/', new Date()) }, /argument handler must be a function/)280+ })281+282 it('should strip path from req.url', function (done) {283 var app = express();284 285 app.use('/foo', function (req, res) {255 unmodified linesmodified:test/middleware.basic.js+1 added-1 removed
26 unmodified lines27 res.end(buf);28 });29 });30 31- request(app.listen())31+ request(app)32 .get('/')33 .set('Content-Type', 'application/json')34 .send('{"foo":"bar"}')35 .expect('Content-Type', 'application/json')4 unmodified linesmodified:test/res.attachment.js+2 added-1 removed
1 2+var Buffer = require('safe-buffer').Buffer3 var express = require('../')4 , request = require('supertest');5 6 describe('res', function(){29 unmodified lines36 var app = express();37 38 app.use(function(req, res){39 res.attachment('/path/to/image.png');39- res.send(new Buffer(4));40+ res.send(Buffer.alloc(4, '.'))41 });42 43 request(app)44 .get('/')33 unmodified linesmodified:test/res.download.js+80 added
69 unmodified lines70 .expect(200, cb);71 })72 })73 74+ describe('.download(path, filename, options, fn)', function () {75+ it('should invoke the callback', function (done) {76+ var app = express()77+ var cb = after(2, done)78+ var options = {}79+80+ app.use(function (req, res) {81+ res.download('test/fixtures/user.html', 'document', options, done)82+ })83+84+ request(app)85+ .get('/')86+ .expect(200)87+ .expect('Content-Type', 'text/html; charset=UTF-8')88+ .expect('Content-Disposition', 'attachment; filename="document"')89+ .end(cb)90+ })91+92+ it('should allow options to res.sendFile()', function (done) {93+ var app = express()94+95+ app.use(function (req, res) {96+ res.download('test/fixtures/.name', 'document', {97+ dotfiles: 'allow',98+ maxAge: '4h'99+ })100+ })101+102+ request(app)103+ .get('/')104+ .expect(200)105+ .expect('Content-Disposition', 'attachment; filename="document"')106+ .expect('Cache-Control', 'public, max-age=14400')107+ .expect('tobi')108+ .end(done)109+ })110+111+ describe('when options.headers contains Content-Disposition', function () {112+ it('should should be ignored', function (done) {113+ var app = express()114+115+ app.use(function (req, res) {116+ res.download('test/fixtures/user.html', 'document', {117+ headers: {118+ 'Content-Type': 'text/x-custom',119+ 'Content-Disposition': 'inline'120+ }121+ })122+ })123+124+ request(app)125+ .get('/')126+ .expect(200)127+ .expect('Content-Type', 'text/x-custom')128+ .expect('Content-Disposition', 'attachment; filename="document"')129+ .end(done)130+ })131+132+ it('should should be ignored case-insensitively', function (done) {133+ var app = express()134+135+ app.use(function (req, res) {136+ res.download('test/fixtures/user.html', 'document', {137+ headers: {138+ 'content-type': 'text/x-custom',139+ 'content-disposition': 'inline'140+ }141+ })142+ })143+144+ request(app)145+ .get('/')146+ .expect(200)147+ .expect('Content-Type', 'text/x-custom')148+ .expect('Content-Disposition', 'attachment; filename="document"')149+ .end(done)150+ })151+ })152+ })153+154 describe('on failure', function(){155 it('should invoke the callback', function(done){156 var app = express();157 35 unmodified linesmodified:test/res.format.js+7 added-4 removed
1 2+var after = require('after')3 var express = require('../')4 , request = require('supertest')5 , assert = require('assert');6 166 unmodified lines173 .expect('Content-Type', 'text/plain; charset=utf-8')174 .expect('hey', done);175 })176 176- it('should set the correct charset for the Content-Type', function() {177+ it('should set the correct charset for the Content-Type', function (done) {178+ var cb = after(3, done)179+180 request(app)181 .get('/')182 .set('Accept', 'text/html')180- .expect('Content-Type', 'text/html; charset=utf-8');183+ .expect('Content-Type', 'text/html; charset=utf-8', cb)184 185 request(app)186 .get('/')187 .set('Accept', 'text/plain')185- .expect('Content-Type', 'text/plain; charset=utf-8');188+ .expect('Content-Type', 'text/plain; charset=utf-8', cb)189 190 request(app)191 .get('/')192 .set('Accept', 'application/json')190- .expect('Content-Type', 'application/json');193+ .expect('Content-Type', 'application/json; charset=utf-8', cb)194 })195 196 it('should Vary: Accept', function(done){197 request(app)23 unmodified linesmodified:test/res.json.js+22 added
100 unmodified lines101 .expect(200, '{"name":"tobi"}', done)102 })103 })104 105+ describe('"json escape" setting', function () {106+ it('should be undefined by default', function () {107+ var app = express()108+ assert.strictEqual(app.get('json escape'), undefined)109+ })110+111+ it('should unicode escape HTML-sniffing characters', function (done) {112+ var app = express()113+114+ app.enable('json escape')115+116+ app.use(function (req, res) {117+ res.json({ '&': '<script>' })118+ })119+120+ request(app)121+ .get('/')122+ .expect('Content-Type', 'application/json; charset=utf-8')123+ .expect(200, '{"\\u0026":"\\u003cscript\\u003e"}', done)124+ })125+ })126+127 describe('"json replacer" setting', function(){128 it('should be passed to JSON.stringify()', function(done){129 var app = express();130 40 unmodified linesmodified:test/res.jsonp.js+22 added
240 unmodified lines241 .expect(200, '"str"', done)242 })243 })244 245+ describe('"json escape" setting', function () {246+ it('should be undefined by default', function () {247+ var app = express()248+ assert.strictEqual(app.get('json escape'), undefined)249+ })250+251+ it('should unicode escape HTML-sniffing characters', function (done) {252+ var app = express()253+254+ app.enable('json escape')255+256+ app.use(function (req, res) {257+ res.jsonp({ '&': '\u2028<script>\u2029' })258+ })259+260+ request(app)261+ .get('/?callback=foo')262+ .expect('Content-Type', 'text/javascript; charset=utf-8')263+ .expect(200, /foo\({"\\u0026":"\\u2028\\u003cscript\\u003e\\u2029"}\)/, done)264+ })265+ })266+267 describe('"json replacer" setting', function(){268 it('should be passed to JSON.stringify()', function(done){269 var app = express();270 54 unmodified linesmodified:test/res.render.js+14 added
33 unmodified lines34 .get('/')35 .expect('<p>tobi</p>', done);36 })37 38+ it('should error without "view engine" set and file extension to a non-engine module', function (done) {39+ var app = createApp()40+41+ app.locals.user = { name: 'tobi' }42+43+ app.use(function (req, res) {44+ res.render(path.join(__dirname, 'fixtures', 'broken.send'))45+ })46+47+ request(app)48+ .get('/')49+ .expect(500, /does not provide a view engine/, done)50+ })51+52 it('should error without "view engine" set and no file extension', function (done) {53 var app = createApp();54 55 app.locals.user = { name: 'tobi' };311 unmodified linesmodified:test/res.send.js+19 added-6 removed
1 2+var Buffer = require('safe-buffer').Buffer3 var express = require('..');4 var methods = require('methods');5 var request = require('supertest');6 var utils = require('./support/utils');114 unmodified lines121 it('should keep charset in Content-Type for Buffers', function(done){122 var app = express();123 124 app.use(function(req, res){124- res.set('Content-Type', 'text/plain; charset=iso-8859-1').send(new Buffer('hi'));125+ res.set('Content-Type', 'text/plain; charset=iso-8859-1').send(Buffer.from('hi'))126 });127 128 request(app)129 .get('/')6 unmodified lines136 it('should send as octet-stream', function(done){137 var app = express();138 139 app.use(function(req, res){139- res.send(new Buffer('hello'));140+ res.send(Buffer.from('hello'))141 });142 143 request(app)144 .get('/')4 unmodified lines149 it('should set ETag', function (done) {150 var app = express();151 152 app.use(function (req, res) {152- var str = Array(1000).join('-');153- res.send(new Buffer(str));153+ res.send(Buffer.alloc(999, '-'))154 });155 156 request(app)157 .get('/')4 unmodified lines162 it('should not override Content-Type', function(done){163 var app = express();164 165 app.use(function(req, res){166- res.set('Content-Type', 'text/plain').send(new Buffer('hey'));166+ res.set('Content-Type', 'text/plain').send(Buffer.from('hey'))167 });168 169 request(app)170 .get('/')171 .expect('Content-Type', 'text/plain; charset=utf-8')172 .expect(200, 'hey', done);173 })174+175+ it('should not override ETag', function (done) {176+ var app = express()177+178+ app.use(function (req, res) {179+ res.type('text/plain').set('ETag', '"foo"').send(Buffer.from('hey'))180+ })181+182+ request(app)183+ .get('/')184+ .expect('ETag', '"foo"')185+ .expect(200, 'hey', done)186+ })187 })188 189 describe('.send(Object)', function(){190 it('should send as application/json', function(done){288 unmodified lines479 var app = express();480 481 app.set('etag', function (body, encoding) {482 var chunk = !Buffer.isBuffer(body)470- ? new Buffer(body, encoding)483+ ? Buffer.from(body, encoding)484 : body;485 chunk.toString().should.equal('hello, world!');486 return '"custom"';487 });30 unmodified linesmodified:test/res.sendFile.js+47 added-6 removed
99 unmodified lines100 101 app.use(function (req, res) {102 setImmediate(function () {103 res.sendFile(path.resolve(fixtures, 'name.txt'));104- cb();104+ server.close(cb)105 });106 test.abort();107 });108 1 unmodified line110 err.code.should.be.empty()111 cb();112 });113 114- var test = request(app).get('/');114+ var server = app.listen()115+ var test = request(server).get('/')116 test.expect(200, cb);117 })118 119 describe('with "cacheControl" option', function () {59 unmodified lines179 .expect(404, done);180 });181 });182 183+ describe('with "immutable" option', function () {184+ it('should add immutable cache-control directive', function (done) {185+ var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'), {186+ immutable: true,187+ maxAge: '4h'188+ })189+190+ request(app)191+ .get('/')192+ .expect('Cache-Control', 'public, max-age=14400, immutable')193+ .expect(200, done)194+ })195+ })196+197+ describe('with "maxAge" option', function () {198+ it('should set cache-control max-age from number', function (done) {199+ var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'), {200+ maxAge: 14400000201+ })202+203+ request(app)204+ .get('/')205+ .expect('Cache-Control', 'public, max-age=14400')206+ .expect(200, done)207+ })208+209+ it('should set cache-control max-age from string', function (done) {210+ var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'), {211+ maxAge: '4h'212+ })213+214+ request(app)215+ .get('/')216+ .expect('Cache-Control', 'public, max-age=14400')217+ .expect(200, done)218+ })219+ })220+221 describe('with "root" option', function () {222 it('should not transfer relative with without', function (done) {223 var app = createApp('test/fixtures/name.txt');224 38 unmodified lines263 setImmediate(function () {264 res.sendFile(path.resolve(fixtures, 'name.txt'), function (err) {265 should(err).be.ok()266 err.code.should.equal('ECONNABORTED');228- cb();267+ server.close(cb)268 });269 });270 test.abort();271 });272 234- var test = request(app).get('/');273+ var server = app.listen()274+ var test = request(server).get('/')275 test.expect(200, cb);276 })277 278 it('should invoke the callback when client already aborted', function (done) {4 unmodified lines283 onFinished(res, function () {284 res.sendFile(path.resolve(fixtures, 'name.txt'), function (err) {285 should(err).be.ok()286 err.code.should.equal('ECONNABORTED');247- cb();287+ server.close(cb)288 });289 });290 test.abort();291 });292 253- var test = request(app).get('/');293+ var server = app.listen()294+ var test = request(server).get('/')295 test.expect(200, cb);296 })297 298 it('should invoke the callback without error when HEAD', function (done) {68 unmodified linesmodified:test/res.type.js+2 added-1 removed
11 unmodified lines12 });13 14 request(app)15 .get('/')16- .expect('Content-Type', 'application/javascript', done);16+ .expect('Content-Type', 'application/javascript; charset=utf-8')17+ .end(done)18 })19 20 it('should default to application/octet-stream', function(done){21 var app = express();24 unmodified linesmodified:test/Router.js+21 added-9 removed
366 unmodified lines367 })368 })369 370 describe('.use', function() {371- it('should require arguments', function(){372- var router = new Router();373- assert.throws(router.use.bind(router), /argument handler is required/)371+ it('should require middleware', function () {372+ var router = new Router()373+ assert.throws(function () { router.use('/') }, /argument handler is required/)374 })375 376- it('should not accept non-functions', function(){377- var router = new Router();378- assert.throws(router.use.bind(router, '/', 'hello'), /argument handler must be a function/)379- assert.throws(router.use.bind(router, '/', 5), /argument handler must be a function/)380- assert.throws(router.use.bind(router, '/', null), /argument handler must be a function/)381- assert.throws(router.use.bind(router, '/', new Date()), /argument handler must be a function/)376+ it('should reject string as middleware', function () {377+ var router = new Router()378+ assert.throws(function () { router.use('/', 'foo') }, /argument handler must be a function/)379 })380 381+ it('should reject number as middleware', function () {382+ var router = new Router()383+ assert.throws(function () { router.use('/', 42) }, /argument handler must be a function/)384+ })385+386+ it('should reject null as middleware', function () {387+ var router = new Router()388+ assert.throws(function () { router.use('/', null) }, /argument handler must be a function/)389+ })390+391+ it('should reject Date as middleware', function () {392+ var router = new Router()393+ assert.throws(function () { router.use('/', new Date()) }, /argument handler must be a function/)394+ })395+396 it('should be called for any URL', function (done) {397 var cb = after(4, done)398 var router = new Router()399 174 unmodified linesmodified:test/utils.js+3 added-4 removed
1 2 var assert = require('assert');3+var Buffer = require('safe-buffer').Buffer4 var utils = require('../lib/utils');5 6 describe('utils.etag(body, encoding)', function(){7 it('should support strings', function(){6 unmodified lines14 .should.eql('"a-JBiXf7GyzxwcrxY4hVXUwa7tmks"')15 })16 17 it('should support buffer', function(){17- var buf = new Buffer('express!')18- utils.etag(buf)18+ utils.etag(Buffer.from('express!'))19 .should.eql('"8-O2uVAFaQ1rZvlKLT14RnuvjPIdg"')20 })21 22 it('should support empty string', function(){35 unmodified lines58 .should.eql('W/"a-JBiXf7GyzxwcrxY4hVXUwa7tmks"')59 })60 61 it('should support buffer', function(){62- var buf = new Buffer('express!')63- utils.wetag(buf)62+ utils.wetag(Buffer.from('express!'))63 .should.eql('W/"8-O2uVAFaQ1rZvlKLT14RnuvjPIdg"')64 })65 66 it('should support empty string', function(){4 unmodified linesmodified:.gitignore+1 added
13 unmodified lines14 15 16 # npm17 node_modules18+package-lock.json19 *.log20 *.gz21 22 5 unmodified linesmodified:.travis.yml+6 added
7 unmodified lines8 - "4.8"9 - "5.12"10 - "6.11"11 - "7.10"12+ - "8.4"13 matrix:14 include:15 - node_js: "8"16 env: "NVM_NODEJS_ORG_MIRROR=https://nodejs.org/download/nightly"17+ - node_js: "9"18+ env: "NVM_NODEJS_ORG_MIRROR=https://nodejs.org/download/nightly"19 allow_failures:20 # Allow the nightly installs to fail21 - env: "NVM_NODEJS_ORG_MIRROR=https://nodejs.org/download/nightly"22 sudo: false23 cache:24 directories:25 - node_modules26 before_install:27+ # Skip updating shrinkwrap / lock28+ - "npm config set shrinkwrap false"29+30 # Remove all non-test dependencies31 - "npm rm --save-dev connect-redis"32 33 # Update Node.js modules6 unmodified linesmodified:appveyor.yml+2 added
7 unmodified lines8 - nodejs_version: "4.8"9 - nodejs_version: "5.12"10 - nodejs_version: "6.11"11 - nodejs_version: "7.10"12+ - nodejs_version: "8.4"13 cache:14 - node_modules15 install:16 - ps: Install-Product node $env:nodejs_version17+ - npm config set shrinkwrap false18 - npm rm --save-dev connect-redis19 - if exist node_modules npm prune20 - if exist node_modules npm rebuild21 - npm install7 unmodified linesmodified:History.md+65 added
1 5.x2 ===3 4+This incorporates all changes after 4.15.5 up to 4.16.2.5+6 * remove:7 - `path-to-regexp` dependency8 9 5.0.0-alpha.6 / 2017-09-2485 unmodified lines95 - `req.query` is now a getter instead of a plain property96 * add:97 - `app.router` is a reference to the base router98 99+4.16.2 / 2017-10-09100+===================101+102+ * Fix `TypeError` in `res.send` when given `Buffer` and `ETag` header set103+ * perf: skip parsing of entire `X-Forwarded-Proto` header104+105+4.16.1 / 2017-09-29106+===================107+108+ * deps: send@0.16.1109+ * deps: serve-static@1.13.1110+ - Fix regression when `root` is incorrectly set to a file111+ - deps: send@0.16.1112+113+4.16.0 / 2017-09-28114+===================115+116+ * Add `"json escape"` setting for `res.json` and `res.jsonp`117+ * Add `express.json` and `express.urlencoded` to parse bodies118+ * Add `options` argument to `res.download`119+ * Improve error message when autoloading invalid view engine120+ * Improve error messages when non-function provided as middleware121+ * Skip `Buffer` encoding when not generating ETag for small response122+ * Use `safe-buffer` for improved Buffer API123+ * deps: accepts@~1.3.4124+ - deps: mime-types@~2.1.16125+ * deps: content-type@~1.0.4126+ - perf: remove argument reassignment127+ - perf: skip parameter parsing when no parameters128+ * deps: etag@~1.8.1129+ - perf: replace regular expression with substring130+ * deps: finalhandler@1.1.0131+ - Use `res.headersSent` when available132+ * deps: parseurl@~1.3.2133+ - perf: reduce overhead for full URLs134+ - perf: unroll the "fast-path" `RegExp`135+ * deps: proxy-addr@~2.0.2136+ - Fix trimming leading / trailing OWS in `X-Forwarded-For`137+ - deps: forwarded@~0.1.2138+ - deps: ipaddr.js@1.5.2139+ - perf: reduce overhead when no `X-Forwarded-For` header140+ * deps: qs@6.5.1141+ - Fix parsing & compacting very deep objects142+ * deps: send@0.16.0143+ - Add 70 new types for file extensions144+ - Add `immutable` option145+ - Fix missing `</html>` in default error & redirects146+ - Set charset as "UTF-8" for .js and .json147+ - Use instance methods on steam to check for listeners148+ - deps: mime@1.4.1149+ - perf: improve path validation speed150+ * deps: serve-static@1.13.0151+ - Add 70 new types for file extensions152+ - Add `immutable` option153+ - Set charset as "UTF-8" for .js and .json154+ - deps: send@0.16.0155+ * deps: setprototypeof@1.1.0156+ * deps: utils-merge@1.0.1157+ * deps: vary@~1.1.2158+ - perf: improve header token parsing speed159+ * perf: re-use options object when generating ETags160+ * perf: remove dead `.charset` set in `res.jsonp`161+162 4.15.5 / 2017-09-24163 ===================164 165 * deps: debug@2.6.93307 unmodified linesmodified:package.json+22 added-21 removed
25 unmodified lines26 "app",27 "api"28 ],29 "dependencies": {30- "accepts": "~1.3.3",30+ "accepts": "~1.3.4",31 "array-flatten": "2.1.1",32+ "body-parser": "1.18.2",33 "content-disposition": "0.5.2",33- "content-type": "~1.0.2",34+ "content-type": "~1.0.4",35 "cookie": "0.3.1",36 "cookie-signature": "1.0.6",37 "debug": "2.6.9",38 "depd": "~1.1.1",39 "encodeurl": "~1.0.1",40 "escape-html": "~1.0.3",40- "etag": "~1.8.0",41- "finalhandler": "~1.0.6",41+ "etag": "~1.8.1",42+ "finalhandler": "1.1.0",43 "fresh": "0.5.2",44 "merge-descriptors": "1.0.1",45 "methods": "~1.1.2",46 "on-finished": "~2.3.0",46- "parseurl": "~1.3.1",47+ "parseurl": "~1.3.2",48 "path-is-absolute": "1.0.1",48- "proxy-addr": "~1.1.5",49- "qs": "6.5.0",49+ "proxy-addr": "~2.0.2",50+ "qs": "6.5.1",51 "range-parser": "~1.2.0",52 "router": "~1.3.1",53+ "safe-buffer": "5.1.1",52- "send": "0.15.6",53- "serve-static": "1.12.6",54- "setprototypeof": "1.0.3",54+ "send": "0.16.1",55+ "serve-static": "1.13.1",56+ "setprototypeof": "1.1.0",57 "statuses": "~1.3.1",58 "type-is": "~1.6.15",57- "utils-merge": "1.0.0",58- "vary": "~1.1.1"59+ "utils-merge": "1.0.1",60+ "vary": "~1.1.2"61 },62 "devDependencies": {63 "after": "0.8.2",62- "body-parser": "1.18.1",64 "cookie-parser": "~1.4.3",64- "cookie-session": "1.3.1",65+ "cookie-session": "1.3.2",66 "ejs": "2.5.7",67 "eslint": "2.13.1",67- "express-session": "1.15.5",68+ "express-session": "1.15.6",69 "hbs": "4.0.1",70 "istanbul": "0.4.5",71 "marked": "0.3.6",71- "method-override": "2.3.9",72+ "method-override": "2.3.10",73 "mocha": "3.5.3",73- "morgan": "1.8.2",74+ "morgan": "1.9.0",75 "multiparty": "4.1.3",76 "pbkdf2-password": "1.2.1",77 "should": "13.1.0",78 "supertest": "1.2.0",11 unmodified lines90 "lib/"91 ],92 "scripts": {93 "lint": "eslint .",93- "test": "mocha --require test/support/env --reporter spec --bail --check-leaks test/ test/acceptance/",94- "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/ test/acceptance/",95- "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/ test/acceptance/",96- "test-tap": "mocha --require test/support/env --reporter tap --check-leaks test/ test/acceptance/"94+ "test": "mocha --require test/support/env --reporter spec --bail --check-leaks --no-exit test/ test/acceptance/",95+ "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks --no-exit test/ test/acceptance/",96+ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks --no-exit test/ test/acceptance/",97+ "test-tap": "mocha --require test/support/env --reporter tap --check-leaks --no-exit test/ test/acceptance/"98 }99 }modified:Readme.md+12 added
19 unmodified lines20 ```21 22 ## Installation23 24+This is a [Node.js](https://nodejs.org/en/) module available through the25+[npm registry](https://www.npmjs.com/).26+27+Before installing, [download and install Node.js](https://nodejs.org/en/download/).28+Node.js 0.10 or higher is required.29+30+Installation is done using the31+[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):32+33 ```bash34 $ npm install express35 ```36 37+Follow [our installing guide](http://expressjs.com/en/starter/installing.html)38+for more information.39+40 ## Features41 42 * Robust routing43 * Focus on high performance110 unmodified lines