Merge tag '4.17.1'
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 5f0c829, e1b45eb · Browse files · 38 files·+3318 added−84 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
38 files+3318 added−84 removed
- tests:+3190 added−36 removed
- other:+128 added−48 removed
Provenance
- Commit
121fe99- Tree
5f37133- Author
Douglas Christopher Wilson <doug@somethingdoug.com>- Committer
Douglas Christopher Wilson <doug@somethingdoug.com>- Parent 1
5f0c829- Parent 2
e1b45eb
38 files changed+3318 added−84 removed
modified:examples/downloads/index.js+1 added-1 removed
19 unmodified lines202122232424252627287 unmodified lines19 unmodified lines var filePath = path.join(__dirname, 'files', req.params.file);
res.download(filePath, function (err) { if (!err) return; // file sent if (err && err.status !== 404) return next(err); // non-404 error if (err.status !== 404) return next(err); // non-404 error // file for download not found res.statusCode = 404; res.send('Cant find that file, sorry!'); });7 unmodified linesmodified:examples/mvc/public/style.css+1 added-1 removed
123345677 unmodified linesbody { padding: 50px; font: 16px "Helvetica Neue", Helvetica, Arial; font: 16px "Helvetica Neue", Helvetica, Arial, sans-serif;}a { color: #107aff; text-decoration: none;7 unmodified linesmodified:examples/static-files/public/js/app.js+1 added-1 removed
11foo// foomodified:lib/express.js+2 added
73 unmodified lines747576777879808173 unmodified lines * Expose middleware */
exports.json = bodyParser.jsonexports.raw = bodyParser.rawexports.static = require('serve-static');exports.text = bodyParser.textexports.urlencoded = bodyParser.urlencodedmodified:lib/request.js+4 added
407 unmodified lines408 var val = this.get('X-Forwarded-Host');409 410 if (!val || !trust(this.connection.remoteAddress, 0)) {411 val = this.get('Host');412+ } else if (val.indexOf(',') !== -1) {413+ // Note: X-Forwarded-Host is normally only ever a414+ // single value, but this is to be safe.415+ val = val.substring(0, val.indexOf(',')).trimRight()416 }417 418 return val || undefined;419 });96 unmodified linesmodified:lib/response.js+6 added-1 removed
353 unmodified lines354 if (!path) {355 throw new TypeError('path argument is required to res.sendFile');356 }357 358+ if (typeof path !== 'string') {359+ throw new TypeError('path must be a string to res.sendFile')360+ }361+362 // support function as second arg363 if (typeof options === 'function') {364 done = options;365 opts = {};323 unmodified lines689 *690 * // "Remember Me" for 15 minutes691 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });692 *689- * // save as above693+ * // same as above694 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })695 *696 * @param {String} name697 * @param {String|Object} value293 unmodified lines991 case 0x3e:992 return '\\u003e'993 case 0x26:994 return '\\u0026'995+ /* istanbul ignore next: unreachable default */996 default:997 return c998 }999 })4 unmodified linesadded:test/fixtures/pets/names.txt+1 added
1+tobi,lokiadded:test/fixtures/snow ☃/.gitkeep
added:test/fixtures/users/index.html+1 added
1+<p>tobi, loki, jane</p>added:test/fixtures/users/tobi.txt+1 added
1+ferretadded:test/fixtures/empty.txt
added:test/fixtures/nums.txt+1 added
1+123456789added:test/fixtures/todo.html+1 added
1+<li>groceries</li>added:test/fixtures/todo.txt+1 added
1+- groceriesmodified:test/support/env.js+1 added-1 removed
1 2 process.env.NODE_ENV = 'test';3-process.env.NO_DEPRECATION = 'express';3+process.env.NO_DEPRECATION = 'body-parser,express';modified:test/support/utils.js+34 added
1 unmodified line2 /**3 * Module dependencies.4 * @private5 */6+7 var assert = require('assert');8+var Buffer = require('safe-buffer').Buffer9 10 /**11 * Module exports.12 * @public13 */14+15+exports.shouldHaveBody = shouldHaveBody16+exports.shouldNotHaveBody = shouldNotHaveBody17 exports.shouldNotHaveHeader = shouldNotHaveHeader;18 19 /**20+ * Assert that a supertest response has a specific body.21+ *22+ * @param {Buffer} buf23+ * @returns {function}24+ */25+26+function shouldHaveBody (buf) {27+ return function (res) {28+ var body = !Buffer.isBuffer(res.body)29+ ? Buffer.from(res.text)30+ : res.body31+ assert.ok(body, 'response has body')32+ assert.strictEqual(body.toString('hex'), buf.toString('hex'))33+ }34+}35+36+/**37+ * Assert that a supertest response does not have a body.38+ *39+ * @returns {function}40+ */41+42+function shouldNotHaveBody () {43+ return function (res) {44+ assert.ok(res.text === '' || res.text === undefined)45+ }46+}47+48+/**49 * Assert that a supertest response does not have a header.50 *51 * @param {string} header Header name to check52 * @returns {function}6 unmodified linesmodified:test/app.router.js+10 added-16 removed
152 unmodified lines153 });154 155 app.use(function(req, res, next){156 calls.push('after');157- res.end();157+ res.json(calls)158 });159 160 request(app)161 .get('/')162- .end(function(res){163- calls.should.eql(['before', 'GET /', 'after'])164- done();165- })162+ .expect(200, ['before', 'GET /', 'after'], done)163 })164 165 describe('when given a regexp', function(){166 it('should match the pathname only', function(done){401 unmodified lines568 .get('/user/tobi.json')569 .expect('/user/tobi.json', done)570 })571 575- it('should decore the capture', function (done) {572+ it('should decode the capture', function (done) {573 var app = express()574 575 app.get('*', function (req, res) {576 res.end(req.params[0])312 unmodified lines889 });890 891 app.get('/foo', function(req, res, next){892 calls.push('/foo 2');896- res.end('done');893+ res.json(calls)894 });895 896 request(app)897 .get('/foo')901- .expect('done', function(){902- calls.should.eql(['/foo/:bar?', '/foo', '/foo 2']);903- done();904- })898+ .expect(200, ['/foo/:bar?', '/foo', '/foo 2'], done)899 })900 })901 902 describe('when next("route") is called', function(){74 unmodified lines977 assert(0);978 });979 980 app.use(function(err, req, res, next){987- res.end(err.message);981+ res.json({982+ calls: calls,983+ error: err.message984+ })985 })986 987 request(app)988 .get('/foo')992- .expect('fail', function(){993- calls.should.eql(['/foo/:bar?', '/foo']);994- done();995- })989+ .expect(200, { calls: ['/foo/:bar?', '/foo'], error: 'fail' }, done)990 })991 992 it('should call handler in same route, if exists', function(done){993 var app = express();219 unmodified linesmodified:test/exports.js+26 added
1 2+var assert = require('assert')3 var express = require('../');4 var request = require('supertest');5 6 describe('exports', function(){7 it('should expose Router', function(){8 express.Router.should.be.a.Function()9 })10 11+ it('should expose json middleware', function () {12+ assert.equal(typeof express.json, 'function')13+ assert.equal(express.json.length, 1)14+ })15+16+ it('should expose raw middleware', function () {17+ assert.equal(typeof express.raw, 'function')18+ assert.equal(express.raw.length, 1)19+ })20+21+ it('should expose static middleware', function () {22+ assert.equal(typeof express.static, 'function')23+ assert.equal(express.static.length, 2)24+ })25+26+ it('should expose text middleware', function () {27+ assert.equal(typeof express.text, 'function')28+ assert.equal(express.text.length, 1)29+ })30+31+ it('should expose urlencoded middleware', function () {32+ assert.equal(typeof express.urlencoded, 'function')33+ assert.equal(express.urlencoded.length, 1)34+ })35+36 it('should expose the application prototype', function(){37 express.application.set.should.be.a.Function()38 })39 39 unmodified linesadded:test/express.json.js+664 added
1+2+var assert = require('assert')3+var Buffer = require('safe-buffer').Buffer4+var express = require('..')5+var request = require('supertest')6+7+describe('express.json()', function () {8+ it('should parse JSON', function (done) {9+ request(createApp())10+ .post('/')11+ .set('Content-Type', 'application/json')12+ .send('{"user":"tobi"}')13+ .expect(200, '{"user":"tobi"}', done)14+ })15+16+ it('should handle Content-Length: 0', function (done) {17+ request(createApp())18+ .post('/')19+ .set('Content-Type', 'application/json')20+ .set('Content-Length', '0')21+ .expect(200, '{}', done)22+ })23+24+ it('should handle empty message-body', function (done) {25+ request(createApp())26+ .post('/')27+ .set('Content-Type', 'application/json')28+ .set('Transfer-Encoding', 'chunked')29+ .expect(200, '{}', done)30+ })31+32+ it('should handle no message-body', function (done) {33+ request(createApp())34+ .post('/')35+ .set('Content-Type', 'application/json')36+ .unset('Transfer-Encoding')37+ .expect(200, '{}', done)38+ })39+40+ it('should 400 when invalid content-length', function (done) {41+ var app = express()42+43+ app.use(function (req, res, next) {44+ req.headers['content-length'] = '20' // bad length45+ next()46+ })47+48+ app.use(express.json())49+50+ app.post('/', function (req, res) {51+ res.json(req.body)52+ })53+54+ request(app)55+ .post('/')56+ .set('Content-Type', 'application/json')57+ .send('{"str":')58+ .expect(400, /content length/, done)59+ })60+61+ it('should handle duplicated middleware', function (done) {62+ var app = express()63+64+ app.use(express.json())65+ app.use(express.json())66+67+ app.post('/', function (req, res) {68+ res.json(req.body)69+ })70+71+ request(app)72+ .post('/')73+ .set('Content-Type', 'application/json')74+ .send('{"user":"tobi"}')75+ .expect(200, '{"user":"tobi"}', done)76+ })77+78+ describe('when JSON is invalid', function () {79+ before(function () {80+ this.app = createApp()81+ })82+83+ it('should 400 for bad token', function (done) {84+ request(this.app)85+ .post('/')86+ .set('Content-Type', 'application/json')87+ .send('{:')88+ .expect(400, parseError('{:'), done)89+ })90+91+ it('should 400 for incomplete', function (done) {92+ request(this.app)93+ .post('/')94+ .set('Content-Type', 'application/json')95+ .send('{"user"')96+ .expect(400, parseError('{"user"'), done)97+ })98+99+ it('should error with type = "entity.parse.failed"', function (done) {100+ request(this.app)101+ .post('/')102+ .set('Content-Type', 'application/json')103+ .set('X-Error-Property', 'type')104+ .send(' {"user"')105+ .expect(400, 'entity.parse.failed', done)106+ })107+108+ it('should include original body on error object', function (done) {109+ request(this.app)110+ .post('/')111+ .set('Content-Type', 'application/json')112+ .set('X-Error-Property', 'body')113+ .send(' {"user"')114+ .expect(400, ' {"user"', done)115+ })116+ })117+118+ describe('with limit option', function () {119+ it('should 413 when over limit with Content-Length', function (done) {120+ var buf = Buffer.alloc(1024, '.')121+ request(createApp({ limit: '1kb' }))122+ .post('/')123+ .set('Content-Type', 'application/json')124+ .set('Content-Length', '1034')125+ .send(JSON.stringify({ str: buf.toString() }))126+ .expect(413, done)127+ })128+129+ it('should error with type = "entity.too.large"', function (done) {130+ var buf = Buffer.alloc(1024, '.')131+ request(createApp({ limit: '1kb' }))132+ .post('/')133+ .set('Content-Type', 'application/json')134+ .set('Content-Length', '1034')135+ .set('X-Error-Property', 'type')136+ .send(JSON.stringify({ str: buf.toString() }))137+ .expect(413, 'entity.too.large', done)138+ })139+140+ it('should 413 when over limit with chunked encoding', function (done) {141+ var buf = Buffer.alloc(1024, '.')142+ var server = createApp({ limit: '1kb' })143+ var test = request(server).post('/')144+ test.set('Content-Type', 'application/json')145+ test.set('Transfer-Encoding', 'chunked')146+ test.write('{"str":')147+ test.write('"' + buf.toString() + '"}')148+ test.expect(413, done)149+ })150+151+ it('should accept number of bytes', function (done) {152+ var buf = Buffer.alloc(1024, '.')153+ request(createApp({ limit: 1024 }))154+ .post('/')155+ .set('Content-Type', 'application/json')156+ .send(JSON.stringify({ str: buf.toString() }))157+ .expect(413, done)158+ })159+160+ it('should not change when options altered', function (done) {161+ var buf = Buffer.alloc(1024, '.')162+ var options = { limit: '1kb' }163+ var server = createApp(options)164+165+ options.limit = '100kb'166+167+ request(server)168+ .post('/')169+ .set('Content-Type', 'application/json')170+ .send(JSON.stringify({ str: buf.toString() }))171+ .expect(413, done)172+ })173+174+ it('should not hang response', function (done) {175+ var buf = Buffer.alloc(10240, '.')176+ var server = createApp({ limit: '8kb' })177+ var test = request(server).post('/')178+ test.set('Content-Type', 'application/json')179+ test.write(buf)180+ test.write(buf)181+ test.write(buf)182+ test.expect(413, done)183+ })184+ })185+186+ describe('with inflate option', function () {187+ describe('when false', function () {188+ before(function () {189+ this.app = createApp({ inflate: false })190+ })191+192+ it('should not accept content-encoding', function (done) {193+ var test = request(this.app).post('/')194+ test.set('Content-Encoding', 'gzip')195+ test.set('Content-Type', 'application/json')196+ test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))197+ test.expect(415, 'content encoding unsupported', done)198+ })199+ })200+201+ describe('when true', function () {202+ before(function () {203+ this.app = createApp({ inflate: true })204+ })205+206+ it('should accept content-encoding', function (done) {207+ var test = request(this.app).post('/')208+ test.set('Content-Encoding', 'gzip')209+ test.set('Content-Type', 'application/json')210+ test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))211+ test.expect(200, '{"name":"论"}', done)212+ })213+ })214+ })215+216+ describe('with strict option', function () {217+ describe('when undefined', function () {218+ before(function () {219+ this.app = createApp()220+ })221+222+ it('should 400 on primitives', function (done) {223+ request(this.app)224+ .post('/')225+ .set('Content-Type', 'application/json')226+ .send('true')227+ .expect(400, parseError('#rue').replace('#', 't'), done)228+ })229+ })230+231+ describe('when false', function () {232+ before(function () {233+ this.app = createApp({ strict: false })234+ })235+236+ it('should parse primitives', function (done) {237+ request(this.app)238+ .post('/')239+ .set('Content-Type', 'application/json')240+ .send('true')241+ .expect(200, 'true', done)242+ })243+ })244+245+ describe('when true', function () {246+ before(function () {247+ this.app = createApp({ strict: true })248+ })249+250+ it('should not parse primitives', function (done) {251+ request(this.app)252+ .post('/')253+ .set('Content-Type', 'application/json')254+ .send('true')255+ .expect(400, parseError('#rue').replace('#', 't'), done)256+ })257+258+ it('should not parse primitives with leading whitespaces', function (done) {259+ request(this.app)260+ .post('/')261+ .set('Content-Type', 'application/json')262+ .send(' true')263+ .expect(400, parseError(' #rue').replace('#', 't'), done)264+ })265+266+ it('should allow leading whitespaces in JSON', function (done) {267+ request(this.app)268+ .post('/')269+ .set('Content-Type', 'application/json')270+ .send(' { "user": "tobi" }')271+ .expect(200, '{"user":"tobi"}', done)272+ })273+274+ it('should error with type = "entity.parse.failed"', function (done) {275+ request(this.app)276+ .post('/')277+ .set('Content-Type', 'application/json')278+ .set('X-Error-Property', 'type')279+ .send('true')280+ .expect(400, 'entity.parse.failed', done)281+ })282+283+ it('should include correct message in stack trace', function (done) {284+ request(this.app)285+ .post('/')286+ .set('Content-Type', 'application/json')287+ .set('X-Error-Property', 'stack')288+ .send('true')289+ .expect(400)290+ .expect(shouldContainInBody(parseError('#rue').replace('#', 't')))291+ .end(done)292+ })293+ })294+ })295+296+ describe('with type option', function () {297+ describe('when "application/vnd.api+json"', function () {298+ before(function () {299+ this.app = createApp({ type: 'application/vnd.api+json' })300+ })301+302+ it('should parse JSON for custom type', function (done) {303+ request(this.app)304+ .post('/')305+ .set('Content-Type', 'application/vnd.api+json')306+ .send('{"user":"tobi"}')307+ .expect(200, '{"user":"tobi"}', done)308+ })309+310+ it('should ignore standard type', function (done) {311+ request(this.app)312+ .post('/')313+ .set('Content-Type', 'application/json')314+ .send('{"user":"tobi"}')315+ .expect(200, '{}', done)316+ })317+ })318+319+ describe('when ["application/json", "application/vnd.api+json"]', function () {320+ before(function () {321+ this.app = createApp({322+ type: ['application/json', 'application/vnd.api+json']323+ })324+ })325+326+ it('should parse JSON for "application/json"', function (done) {327+ request(this.app)328+ .post('/')329+ .set('Content-Type', 'application/json')330+ .send('{"user":"tobi"}')331+ .expect(200, '{"user":"tobi"}', done)332+ })333+334+ it('should parse JSON for "application/vnd.api+json"', function (done) {335+ request(this.app)336+ .post('/')337+ .set('Content-Type', 'application/vnd.api+json')338+ .send('{"user":"tobi"}')339+ .expect(200, '{"user":"tobi"}', done)340+ })341+342+ it('should ignore "application/x-json"', function (done) {343+ request(this.app)344+ .post('/')345+ .set('Content-Type', 'application/x-json')346+ .send('{"user":"tobi"}')347+ .expect(200, '{}', done)348+ })349+ })350+351+ describe('when a function', function () {352+ it('should parse when truthy value returned', function (done) {353+ var app = createApp({ type: accept })354+355+ function accept (req) {356+ return req.headers['content-type'] === 'application/vnd.api+json'357+ }358+359+ request(app)360+ .post('/')361+ .set('Content-Type', 'application/vnd.api+json')362+ .send('{"user":"tobi"}')363+ .expect(200, '{"user":"tobi"}', done)364+ })365+366+ it('should work without content-type', function (done) {367+ var app = createApp({ type: accept })368+369+ function accept (req) {370+ return true371+ }372+373+ var test = request(app).post('/')374+ test.write('{"user":"tobi"}')375+ test.expect(200, '{"user":"tobi"}', done)376+ })377+378+ it('should not invoke without a body', function (done) {379+ var app = createApp({ type: accept })380+381+ function accept (req) {382+ throw new Error('oops!')383+ }384+385+ request(app)386+ .get('/')387+ .expect(404, done)388+ })389+ })390+ })391+392+ describe('with verify option', function () {393+ it('should assert value if function', function () {394+ assert.throws(createApp.bind(null, { verify: 'lol' }),395+ /TypeError: option verify must be function/)396+ })397+398+ it('should error from verify', function (done) {399+ var app = createApp({ verify: function (req, res, buf) {400+ if (buf[0] === 0x5b) throw new Error('no arrays')401+ } })402+403+ request(app)404+ .post('/')405+ .set('Content-Type', 'application/json')406+ .send('["tobi"]')407+ .expect(403, 'no arrays', done)408+ })409+410+ it('should error with type = "entity.verify.failed"', function (done) {411+ var app = createApp({ verify: function (req, res, buf) {412+ if (buf[0] === 0x5b) throw new Error('no arrays')413+ } })414+415+ request(app)416+ .post('/')417+ .set('Content-Type', 'application/json')418+ .set('X-Error-Property', 'type')419+ .send('["tobi"]')420+ .expect(403, 'entity.verify.failed', done)421+ })422+423+ it('should allow custom codes', function (done) {424+ var app = createApp({ verify: function (req, res, buf) {425+ if (buf[0] !== 0x5b) return426+ var err = new Error('no arrays')427+ err.status = 400428+ throw err429+ } })430+431+ request(app)432+ .post('/')433+ .set('Content-Type', 'application/json')434+ .send('["tobi"]')435+ .expect(400, 'no arrays', done)436+ })437+438+ it('should allow custom type', function (done) {439+ var app = createApp({ verify: function (req, res, buf) {440+ if (buf[0] !== 0x5b) return441+ var err = new Error('no arrays')442+ err.type = 'foo.bar'443+ throw err444+ } })445+446+ request(app)447+ .post('/')448+ .set('Content-Type', 'application/json')449+ .set('X-Error-Property', 'type')450+ .send('["tobi"]')451+ .expect(403, 'foo.bar', done)452+ })453+454+ it('should include original body on error object', function (done) {455+ var app = createApp({ verify: function (req, res, buf) {456+ if (buf[0] === 0x5b) throw new Error('no arrays')457+ } })458+459+ request(app)460+ .post('/')461+ .set('Content-Type', 'application/json')462+ .set('X-Error-Property', 'body')463+ .send('["tobi"]')464+ .expect(403, '["tobi"]', done)465+ })466+467+ it('should allow pass-through', function (done) {468+ var app = createApp({ verify: function (req, res, buf) {469+ if (buf[0] === 0x5b) throw new Error('no arrays')470+ } })471+472+ request(app)473+ .post('/')474+ .set('Content-Type', 'application/json')475+ .send('{"user":"tobi"}')476+ .expect(200, '{"user":"tobi"}', done)477+ })478+479+ it('should work with different charsets', function (done) {480+ var app = createApp({ verify: function (req, res, buf) {481+ if (buf[0] === 0x5b) throw new Error('no arrays')482+ } })483+484+ var test = request(app).post('/')485+ test.set('Content-Type', 'application/json; charset=utf-16')486+ test.write(Buffer.from('feff007b0022006e0061006d00650022003a00228bba0022007d', 'hex'))487+ test.expect(200, '{"name":"论"}', done)488+ })489+490+ it('should 415 on unknown charset prior to verify', function (done) {491+ var app = createApp({ verify: function (req, res, buf) {492+ throw new Error('unexpected verify call')493+ } })494+495+ var test = request(app).post('/')496+ test.set('Content-Type', 'application/json; charset=x-bogus')497+ test.write(Buffer.from('00000000', 'hex'))498+ test.expect(415, 'unsupported charset "X-BOGUS"', done)499+ })500+ })501+502+ describe('charset', function () {503+ before(function () {504+ this.app = createApp()505+ })506+507+ it('should parse utf-8', function (done) {508+ var test = request(this.app).post('/')509+ test.set('Content-Type', 'application/json; charset=utf-8')510+ test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex'))511+ test.expect(200, '{"name":"论"}', done)512+ })513+514+ it('should parse utf-16', function (done) {515+ var test = request(this.app).post('/')516+ test.set('Content-Type', 'application/json; charset=utf-16')517+ test.write(Buffer.from('feff007b0022006e0061006d00650022003a00228bba0022007d', 'hex'))518+ test.expect(200, '{"name":"论"}', done)519+ })520+521+ it('should parse when content-length != char length', function (done) {522+ var test = request(this.app).post('/')523+ test.set('Content-Type', 'application/json; charset=utf-8')524+ test.set('Content-Length', '13')525+ test.write(Buffer.from('7b2274657374223a22c3a5227d', 'hex'))526+ test.expect(200, '{"test":"å"}', done)527+ })528+529+ it('should default to utf-8', function (done) {530+ var test = request(this.app).post('/')531+ test.set('Content-Type', 'application/json')532+ test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex'))533+ test.expect(200, '{"name":"论"}', done)534+ })535+536+ it('should fail on unknown charset', function (done) {537+ var test = request(this.app).post('/')538+ test.set('Content-Type', 'application/json; charset=koi8-r')539+ test.write(Buffer.from('7b226e616d65223a22cec5d4227d', 'hex'))540+ test.expect(415, 'unsupported charset "KOI8-R"', done)541+ })542+543+ it('should error with type = "charset.unsupported"', function (done) {544+ var test = request(this.app).post('/')545+ test.set('Content-Type', 'application/json; charset=koi8-r')546+ test.set('X-Error-Property', 'type')547+ test.write(Buffer.from('7b226e616d65223a22cec5d4227d', 'hex'))548+ test.expect(415, 'charset.unsupported', done)549+ })550+ })551+552+ describe('encoding', function () {553+ before(function () {554+ this.app = createApp({ limit: '1kb' })555+ })556+557+ it('should parse without encoding', function (done) {558+ var test = request(this.app).post('/')559+ test.set('Content-Type', 'application/json')560+ test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex'))561+ test.expect(200, '{"name":"论"}', done)562+ })563+564+ it('should support identity encoding', function (done) {565+ var test = request(this.app).post('/')566+ test.set('Content-Encoding', 'identity')567+ test.set('Content-Type', 'application/json')568+ test.write(Buffer.from('7b226e616d65223a22e8aeba227d', 'hex'))569+ test.expect(200, '{"name":"论"}', done)570+ })571+572+ it('should support gzip encoding', function (done) {573+ var test = request(this.app).post('/')574+ test.set('Content-Encoding', 'gzip')575+ test.set('Content-Type', 'application/json')576+ test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))577+ test.expect(200, '{"name":"论"}', done)578+ })579+580+ it('should support deflate encoding', function (done) {581+ var test = request(this.app).post('/')582+ test.set('Content-Encoding', 'deflate')583+ test.set('Content-Type', 'application/json')584+ test.write(Buffer.from('789cab56ca4bcc4d55b2527ab16e97522d00274505ac', 'hex'))585+ test.expect(200, '{"name":"论"}', done)586+ })587+588+ it('should be case-insensitive', function (done) {589+ var test = request(this.app).post('/')590+ test.set('Content-Encoding', 'GZIP')591+ test.set('Content-Type', 'application/json')592+ test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))593+ test.expect(200, '{"name":"论"}', done)594+ })595+596+ it('should 415 on unknown encoding', function (done) {597+ var test = request(this.app).post('/')598+ test.set('Content-Encoding', 'nulls')599+ test.set('Content-Type', 'application/json')600+ test.write(Buffer.from('000000000000', 'hex'))601+ test.expect(415, 'unsupported content encoding "nulls"', done)602+ })603+604+ it('should error with type = "encoding.unsupported"', function (done) {605+ var test = request(this.app).post('/')606+ test.set('Content-Encoding', 'nulls')607+ test.set('Content-Type', 'application/json')608+ test.set('X-Error-Property', 'type')609+ test.write(Buffer.from('000000000000', 'hex'))610+ test.expect(415, 'encoding.unsupported', done)611+ })612+613+ it('should 400 on malformed encoding', function (done) {614+ var test = request(this.app).post('/')615+ test.set('Content-Encoding', 'gzip')616+ test.set('Content-Type', 'application/json')617+ test.write(Buffer.from('1f8b080000000000000bab56cc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))618+ test.expect(400, done)619+ })620+621+ it('should 413 when inflated value exceeds limit', function (done) {622+ // gzip'd data exceeds 1kb, but deflated below 1kb623+ var test = request(this.app).post('/')624+ test.set('Content-Encoding', 'gzip')625+ test.set('Content-Type', 'application/json')626+ test.write(Buffer.from('1f8b080000000000000bedc1010d000000c2a0f74f6d0f071400000000000000', 'hex'))627+ test.write(Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex'))628+ test.write(Buffer.from('0000000000000000004f0625b3b71650c30000', 'hex'))629+ test.expect(413, done)630+ })631+ })632+})633+634+function createApp (options) {635+ var app = express()636+637+ app.use(express.json(options))638+639+ app.use(function (err, req, res, next) {640+ res.status(err.status || 500)641+ res.send(String(err[req.headers['x-error-property'] || 'message']))642+ })643+644+ app.post('/', function (req, res) {645+ res.json(req.body)646+ })647+648+ return app649+}650+651+function parseError (str) {652+ try {653+ JSON.parse(str); throw new SyntaxError('strict violation')654+ } catch (e) {655+ return e.message656+ }657+}658+659+function shouldContainInBody (str) {660+ return function (res) {661+ assert.ok(res.text.indexOf(str) !== -1,662+ 'expected \'' + res.text + '\' to contain \'' + str + '\'')663+ }664+}added:test/express.raw.js+387 added
1+2+var assert = require('assert')3+var Buffer = require('safe-buffer').Buffer4+var express = require('..')5+var request = require('supertest')6+7+describe('express.raw()', function () {8+ before(function () {9+ this.app = createApp()10+ })11+12+ it('should parse application/octet-stream', function (done) {13+ request(this.app)14+ .post('/')15+ .set('Content-Type', 'application/octet-stream')16+ .send('the user is tobi')17+ .expect(200, { buf: '746865207573657220697320746f6269' }, done)18+ })19+20+ it('should 400 when invalid content-length', function (done) {21+ var app = express()22+23+ app.use(function (req, res, next) {24+ req.headers['content-length'] = '20' // bad length25+ next()26+ })27+28+ app.use(express.raw())29+30+ app.post('/', function (req, res) {31+ if (Buffer.isBuffer(req.body)) {32+ res.json({ buf: req.body.toString('hex') })33+ } else {34+ res.json(req.body)35+ }36+ })37+38+ request(app)39+ .post('/')40+ .set('Content-Type', 'application/octet-stream')41+ .send('stuff')42+ .expect(400, /content length/, done)43+ })44+45+ it('should handle Content-Length: 0', function (done) {46+ request(this.app)47+ .post('/')48+ .set('Content-Type', 'application/octet-stream')49+ .set('Content-Length', '0')50+ .expect(200, { buf: '' }, done)51+ })52+53+ it('should handle empty message-body', function (done) {54+ request(this.app)55+ .post('/')56+ .set('Content-Type', 'application/octet-stream')57+ .set('Transfer-Encoding', 'chunked')58+ .send('')59+ .expect(200, { buf: '' }, done)60+ })61+62+ it('should handle duplicated middleware', function (done) {63+ var app = express()64+65+ app.use(express.raw())66+ app.use(express.raw())67+68+ app.post('/', function (req, res) {69+ if (Buffer.isBuffer(req.body)) {70+ res.json({ buf: req.body.toString('hex') })71+ } else {72+ res.json(req.body)73+ }74+ })75+76+ request(app)77+ .post('/')78+ .set('Content-Type', 'application/octet-stream')79+ .send('the user is tobi')80+ .expect(200, { buf: '746865207573657220697320746f6269' }, done)81+ })82+83+ describe('with limit option', function () {84+ it('should 413 when over limit with Content-Length', function (done) {85+ var buf = Buffer.alloc(1028, '.')86+ var app = createApp({ limit: '1kb' })87+ var test = request(app).post('/')88+ test.set('Content-Type', 'application/octet-stream')89+ test.set('Content-Length', '1028')90+ test.write(buf)91+ test.expect(413, done)92+ })93+94+ it('should 413 when over limit with chunked encoding', function (done) {95+ var buf = Buffer.alloc(1028, '.')96+ var app = createApp({ limit: '1kb' })97+ var test = request(app).post('/')98+ test.set('Content-Type', 'application/octet-stream')99+ test.set('Transfer-Encoding', 'chunked')100+ test.write(buf)101+ test.expect(413, done)102+ })103+104+ it('should accept number of bytes', function (done) {105+ var buf = Buffer.alloc(1028, '.')106+ var app = createApp({ limit: 1024 })107+ var test = request(app).post('/')108+ test.set('Content-Type', 'application/octet-stream')109+ test.write(buf)110+ test.expect(413, done)111+ })112+113+ it('should not change when options altered', function (done) {114+ var buf = Buffer.alloc(1028, '.')115+ var options = { limit: '1kb' }116+ var app = createApp(options)117+118+ options.limit = '100kb'119+120+ var test = request(app).post('/')121+ test.set('Content-Type', 'application/octet-stream')122+ test.write(buf)123+ test.expect(413, done)124+ })125+126+ it('should not hang response', function (done) {127+ var buf = Buffer.alloc(10240, '.')128+ var app = createApp({ limit: '8kb' })129+ var test = request(app).post('/')130+ test.set('Content-Type', 'application/octet-stream')131+ test.write(buf)132+ test.write(buf)133+ test.write(buf)134+ test.expect(413, done)135+ })136+ })137+138+ describe('with inflate option', function () {139+ describe('when false', function () {140+ before(function () {141+ this.app = createApp({ inflate: false })142+ })143+144+ it('should not accept content-encoding', function (done) {145+ var test = request(this.app).post('/')146+ test.set('Content-Encoding', 'gzip')147+ test.set('Content-Type', 'application/octet-stream')148+ test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))149+ test.expect(415, 'content encoding unsupported', done)150+ })151+ })152+153+ describe('when true', function () {154+ before(function () {155+ this.app = createApp({ inflate: true })156+ })157+158+ it('should accept content-encoding', function (done) {159+ var test = request(this.app).post('/')160+ test.set('Content-Encoding', 'gzip')161+ test.set('Content-Type', 'application/octet-stream')162+ test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))163+ test.expect(200, { buf: '6e616d653de8aeba' }, done)164+ })165+ })166+ })167+168+ describe('with type option', function () {169+ describe('when "application/vnd+octets"', function () {170+ before(function () {171+ this.app = createApp({ type: 'application/vnd+octets' })172+ })173+174+ it('should parse for custom type', function (done) {175+ var test = request(this.app).post('/')176+ test.set('Content-Type', 'application/vnd+octets')177+ test.write(Buffer.from('000102', 'hex'))178+ test.expect(200, { buf: '000102' }, done)179+ })180+181+ it('should ignore standard type', function (done) {182+ var test = request(this.app).post('/')183+ test.set('Content-Type', 'application/octet-stream')184+ test.write(Buffer.from('000102', 'hex'))185+ test.expect(200, '{}', done)186+ })187+ })188+189+ describe('when ["application/octet-stream", "application/vnd+octets"]', function () {190+ before(function () {191+ this.app = createApp({192+ type: ['application/octet-stream', 'application/vnd+octets']193+ })194+ })195+196+ it('should parse "application/octet-stream"', function (done) {197+ var test = request(this.app).post('/')198+ test.set('Content-Type', 'application/octet-stream')199+ test.write(Buffer.from('000102', 'hex'))200+ test.expect(200, { buf: '000102' }, done)201+ })202+203+ it('should parse "application/vnd+octets"', function (done) {204+ var test = request(this.app).post('/')205+ test.set('Content-Type', 'application/vnd+octets')206+ test.write(Buffer.from('000102', 'hex'))207+ test.expect(200, { buf: '000102' }, done)208+ })209+210+ it('should ignore "application/x-foo"', function (done) {211+ var test = request(this.app).post('/')212+ test.set('Content-Type', 'application/x-foo')213+ test.write(Buffer.from('000102', 'hex'))214+ test.expect(200, '{}', done)215+ })216+ })217+218+ describe('when a function', function () {219+ it('should parse when truthy value returned', function (done) {220+ var app = createApp({ type: accept })221+222+ function accept (req) {223+ return req.headers['content-type'] === 'application/vnd.octet'224+ }225+226+ var test = request(app).post('/')227+ test.set('Content-Type', 'application/vnd.octet')228+ test.write(Buffer.from('000102', 'hex'))229+ test.expect(200, { buf: '000102' }, done)230+ })231+232+ it('should work without content-type', function (done) {233+ var app = createApp({ type: accept })234+235+ function accept (req) {236+ return true237+ }238+239+ var test = request(app).post('/')240+ test.write(Buffer.from('000102', 'hex'))241+ test.expect(200, { buf: '000102' }, done)242+ })243+244+ it('should not invoke without a body', function (done) {245+ var app = createApp({ type: accept })246+247+ function accept (req) {248+ throw new Error('oops!')249+ }250+251+ request(app)252+ .get('/')253+ .expect(404, done)254+ })255+ })256+ })257+258+ describe('with verify option', function () {259+ it('should assert value is function', function () {260+ assert.throws(createApp.bind(null, { verify: 'lol' }),261+ /TypeError: option verify must be function/)262+ })263+264+ it('should error from verify', function (done) {265+ var app = createApp({ verify: function (req, res, buf) {266+ if (buf[0] === 0x00) throw new Error('no leading null')267+ } })268+269+ var test = request(app).post('/')270+ test.set('Content-Type', 'application/octet-stream')271+ test.write(Buffer.from('000102', 'hex'))272+ test.expect(403, 'no leading null', done)273+ })274+275+ it('should allow custom codes', function (done) {276+ var app = createApp({ verify: function (req, res, buf) {277+ if (buf[0] !== 0x00) return278+ var err = new Error('no leading null')279+ err.status = 400280+ throw err281+ } })282+283+ var test = request(app).post('/')284+ test.set('Content-Type', 'application/octet-stream')285+ test.write(Buffer.from('000102', 'hex'))286+ test.expect(400, 'no leading null', done)287+ })288+289+ it('should allow pass-through', function (done) {290+ var app = createApp({ verify: function (req, res, buf) {291+ if (buf[0] === 0x00) throw new Error('no leading null')292+ } })293+294+ var test = request(app).post('/')295+ test.set('Content-Type', 'application/octet-stream')296+ test.write(Buffer.from('0102', 'hex'))297+ test.expect(200, { buf: '0102' }, done)298+ })299+ })300+301+ describe('charset', function () {302+ before(function () {303+ this.app = createApp()304+ })305+306+ it('should ignore charset', function (done) {307+ var test = request(this.app).post('/')308+ test.set('Content-Type', 'application/octet-stream; charset=utf-8')309+ test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))310+ test.expect(200, { buf: '6e616d6520697320e8aeba' }, done)311+ })312+ })313+314+ describe('encoding', function () {315+ before(function () {316+ this.app = createApp({ limit: '10kb' })317+ })318+319+ it('should parse without encoding', function (done) {320+ var test = request(this.app).post('/')321+ test.set('Content-Type', 'application/octet-stream')322+ test.write(Buffer.from('6e616d653de8aeba', 'hex'))323+ test.expect(200, { buf: '6e616d653de8aeba' }, done)324+ })325+326+ it('should support identity encoding', function (done) {327+ var test = request(this.app).post('/')328+ test.set('Content-Encoding', 'identity')329+ test.set('Content-Type', 'application/octet-stream')330+ test.write(Buffer.from('6e616d653de8aeba', 'hex'))331+ test.expect(200, { buf: '6e616d653de8aeba' }, done)332+ })333+334+ it('should support gzip encoding', function (done) {335+ var test = request(this.app).post('/')336+ test.set('Content-Encoding', 'gzip')337+ test.set('Content-Type', 'application/octet-stream')338+ test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))339+ test.expect(200, { buf: '6e616d653de8aeba' }, done)340+ })341+342+ it('should support deflate encoding', function (done) {343+ var test = request(this.app).post('/')344+ test.set('Content-Encoding', 'deflate')345+ test.set('Content-Type', 'application/octet-stream')346+ test.write(Buffer.from('789ccb4bcc4db57db16e17001068042f', 'hex'))347+ test.expect(200, { buf: '6e616d653de8aeba' }, done)348+ })349+350+ it('should be case-insensitive', function (done) {351+ var test = request(this.app).post('/')352+ test.set('Content-Encoding', 'GZIP')353+ test.set('Content-Type', 'application/octet-stream')354+ test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))355+ test.expect(200, { buf: '6e616d653de8aeba' }, done)356+ })357+358+ it('should fail on unknown encoding', function (done) {359+ var test = request(this.app).post('/')360+ test.set('Content-Encoding', 'nulls')361+ test.set('Content-Type', 'application/octet-stream')362+ test.write(Buffer.from('000000000000', 'hex'))363+ test.expect(415, 'unsupported content encoding "nulls"', done)364+ })365+ })366+})367+368+function createApp (options) {369+ var app = express()370+371+ app.use(express.raw(options))372+373+ app.use(function (err, req, res, next) {374+ res.status(err.status || 500)375+ res.send(String(err[req.headers['x-error-property'] || 'message']))376+ })377+378+ app.post('/', function (req, res) {379+ if (Buffer.isBuffer(req.body)) {380+ res.json({ buf: req.body.toString('hex') })381+ } else {382+ res.json(req.body)383+ }384+ })385+386+ return app387+}added:test/express.static.js+813 added
1+2+var assert = require('assert')3+var Buffer = require('safe-buffer').Buffer4+var express = require('..')5+var path = require('path')6+var request = require('supertest')7+var utils = require('./support/utils')8+9+var fixtures = path.join(__dirname, '/fixtures')10+var relative = path.relative(process.cwd(), fixtures)11+12+var skipRelative = ~relative.indexOf('..') || path.resolve(relative) === relative13+14+describe('express.static()', function () {15+ describe('basic operations', function () {16+ before(function () {17+ this.app = createApp()18+ })19+20+ it('should require root path', function () {21+ assert.throws(express.static.bind(), /root path required/)22+ })23+24+ it('should require root path to be string', function () {25+ assert.throws(express.static.bind(null, 42), /root path.*string/)26+ })27+28+ it('should serve static files', function (done) {29+ request(this.app)30+ .get('/todo.txt')31+ .expect(200, '- groceries', done)32+ })33+34+ it('should support nesting', function (done) {35+ request(this.app)36+ .get('/users/tobi.txt')37+ .expect(200, 'ferret', done)38+ })39+40+ it('should set Content-Type', function (done) {41+ request(this.app)42+ .get('/todo.txt')43+ .expect('Content-Type', 'text/plain; charset=UTF-8')44+ .expect(200, done)45+ })46+47+ it('should set Last-Modified', function (done) {48+ request(this.app)49+ .get('/todo.txt')50+ .expect('Last-Modified', /\d{2} \w{3} \d{4}/)51+ .expect(200, done)52+ })53+54+ it('should default max-age=0', function (done) {55+ request(this.app)56+ .get('/todo.txt')57+ .expect('Cache-Control', 'public, max-age=0')58+ .expect(200, done)59+ })60+61+ it('should support urlencoded pathnames', function (done) {62+ request(this.app)63+ .get('/%25%20of%20dogs.txt')64+ .expect(200, '20%', done)65+ })66+67+ it('should not choke on auth-looking URL', function (done) {68+ request(this.app)69+ .get('//todo@txt')70+ .expect(404, 'Not Found', done)71+ })72+73+ it('should support index.html', function (done) {74+ request(this.app)75+ .get('/users/')76+ .expect(200)77+ .expect('Content-Type', /html/)78+ .expect('<p>tobi, loki, jane</p>', done)79+ })80+81+ it('should support ../', function (done) {82+ request(this.app)83+ .get('/users/../todo.txt')84+ .expect(200, '- groceries', done)85+ })86+87+ it('should support HEAD', function (done) {88+ request(this.app)89+ .head('/todo.txt')90+ .expect(200)91+ .expect(utils.shouldNotHaveBody())92+ .end(done)93+ })94+95+ it('should skip POST requests', function (done) {96+ request(this.app)97+ .post('/todo.txt')98+ .expect(404, 'Not Found', done)99+ })100+101+ it('should support conditional requests', function (done) {102+ var app = this.app103+104+ request(app)105+ .get('/todo.txt')106+ .end(function (err, res) {107+ if (err) throw err108+ request(app)109+ .get('/todo.txt')110+ .set('If-None-Match', res.headers.etag)111+ .expect(304, done)112+ })113+ })114+115+ it('should support precondition checks', function (done) {116+ request(this.app)117+ .get('/todo.txt')118+ .set('If-Match', '"foo"')119+ .expect(412, done)120+ })121+122+ it('should serve zero-length files', function (done) {123+ request(this.app)124+ .get('/empty.txt')125+ .expect(200, '', done)126+ })127+128+ it('should ignore hidden files', function (done) {129+ request(this.app)130+ .get('/.name')131+ .expect(404, 'Not Found', done)132+ })133+ });134+135+ (skipRelative ? describe.skip : describe)('current dir', function () {136+ before(function () {137+ this.app = createApp('.')138+ })139+140+ it('should be served with "."', function (done) {141+ var dest = relative.split(path.sep).join('/')142+ request(this.app)143+ .get('/' + dest + '/todo.txt')144+ .expect(200, '- groceries', done)145+ })146+ })147+148+ describe('acceptRanges', function () {149+ describe('when false', function () {150+ it('should not include Accept-Ranges', function (done) {151+ request(createApp(fixtures, { 'acceptRanges': false }))152+ .get('/nums.txt')153+ .expect(utils.shouldNotHaveHeader('Accept-Ranges'))154+ .expect(200, '123456789', done)155+ })156+157+ it('should ignore Rage request header', function (done) {158+ request(createApp(fixtures, { 'acceptRanges': false }))159+ .get('/nums.txt')160+ .set('Range', 'bytes=0-3')161+ .expect(utils.shouldNotHaveHeader('Accept-Ranges'))162+ .expect(utils.shouldNotHaveHeader('Content-Range'))163+ .expect(200, '123456789', done)164+ })165+ })166+167+ describe('when true', function () {168+ it('should include Accept-Ranges', function (done) {169+ request(createApp(fixtures, { 'acceptRanges': true }))170+ .get('/nums.txt')171+ .expect('Accept-Ranges', 'bytes')172+ .expect(200, '123456789', done)173+ })174+175+ it('should obey Rage request header', function (done) {176+ request(createApp(fixtures, { 'acceptRanges': true }))177+ .get('/nums.txt')178+ .set('Range', 'bytes=0-3')179+ .expect('Accept-Ranges', 'bytes')180+ .expect('Content-Range', 'bytes 0-3/9')181+ .expect(206, '1234', done)182+ })183+ })184+ })185+186+ describe('cacheControl', function () {187+ describe('when false', function () {188+ it('should not include Cache-Control', function (done) {189+ request(createApp(fixtures, { 'cacheControl': false }))190+ .get('/nums.txt')191+ .expect(utils.shouldNotHaveHeader('Cache-Control'))192+ .expect(200, '123456789', done)193+ })194+195+ it('should ignore maxAge', function (done) {196+ request(createApp(fixtures, { 'cacheControl': false, 'maxAge': 12000 }))197+ .get('/nums.txt')198+ .expect(utils.shouldNotHaveHeader('Cache-Control'))199+ .expect(200, '123456789', done)200+ })201+ })202+203+ describe('when true', function () {204+ it('should include Cache-Control', function (done) {205+ request(createApp(fixtures, { 'cacheControl': true }))206+ .get('/nums.txt')207+ .expect('Cache-Control', 'public, max-age=0')208+ .expect(200, '123456789', done)209+ })210+ })211+ })212+213+ describe('extensions', function () {214+ it('should be not be enabled by default', function (done) {215+ request(createApp(fixtures))216+ .get('/todo')217+ .expect(404, done)218+ })219+220+ it('should be configurable', function (done) {221+ request(createApp(fixtures, { 'extensions': 'txt' }))222+ .get('/todo')223+ .expect(200, '- groceries', done)224+ })225+226+ it('should support disabling extensions', function (done) {227+ request(createApp(fixtures, { 'extensions': false }))228+ .get('/todo')229+ .expect(404, done)230+ })231+232+ it('should support fallbacks', function (done) {233+ request(createApp(fixtures, { 'extensions': ['htm', 'html', 'txt'] }))234+ .get('/todo')235+ .expect(200, '<li>groceries</li>', done)236+ })237+238+ it('should 404 if nothing found', function (done) {239+ request(createApp(fixtures, { 'extensions': ['htm', 'html', 'txt'] }))240+ .get('/bob')241+ .expect(404, done)242+ })243+ })244+245+ describe('fallthrough', function () {246+ it('should default to true', function (done) {247+ request(createApp())248+ .get('/does-not-exist')249+ .expect(404, 'Not Found', done)250+ })251+252+ describe('when true', function () {253+ before(function () {254+ this.app = createApp(fixtures, { 'fallthrough': true })255+ })256+257+ it('should fall-through when OPTIONS request', function (done) {258+ request(this.app)259+ .options('/todo.txt')260+ .expect(404, 'Not Found', done)261+ })262+263+ it('should fall-through when URL malformed', function (done) {264+ request(this.app)265+ .get('/%')266+ .expect(404, 'Not Found', done)267+ })268+269+ it('should fall-through when traversing past root', function (done) {270+ request(this.app)271+ .get('/users/../../todo.txt')272+ .expect(404, 'Not Found', done)273+ })274+275+ it('should fall-through when URL too long', function (done) {276+ var app = express()277+ var root = fixtures + Array(10000).join('/foobar')278+279+ app.use(express.static(root, { 'fallthrough': true }))280+ app.use(function (req, res, next) {281+ res.sendStatus(404)282+ })283+284+ request(app)285+ .get('/')286+ .expect(404, 'Not Found', done)287+ })288+289+ describe('with redirect: true', function () {290+ before(function () {291+ this.app = createApp(fixtures, { 'fallthrough': true, 'redirect': true })292+ })293+294+ it('should fall-through when directory', function (done) {295+ request(this.app)296+ .get('/pets/')297+ .expect(404, 'Not Found', done)298+ })299+300+ it('should redirect when directory without slash', function (done) {301+ request(this.app)302+ .get('/pets')303+ .expect(301, /Redirecting/, done)304+ })305+ })306+307+ describe('with redirect: false', function () {308+ before(function () {309+ this.app = createApp(fixtures, { 'fallthrough': true, 'redirect': false })310+ })311+312+ it('should fall-through when directory', function (done) {313+ request(this.app)314+ .get('/pets/')315+ .expect(404, 'Not Found', done)316+ })317+318+ it('should fall-through when directory without slash', function (done) {319+ request(this.app)320+ .get('/pets')321+ .expect(404, 'Not Found', done)322+ })323+ })324+ })325+326+ describe('when false', function () {327+ before(function () {328+ this.app = createApp(fixtures, { 'fallthrough': false })329+ })330+331+ it('should 405 when OPTIONS request', function (done) {332+ request(this.app)333+ .options('/todo.txt')334+ .expect('Allow', 'GET, HEAD')335+ .expect(405, done)336+ })337+338+ it('should 400 when URL malformed', function (done) {339+ request(this.app)340+ .get('/%')341+ .expect(400, /BadRequestError/, done)342+ })343+344+ it('should 403 when traversing past root', function (done) {345+ request(this.app)346+ .get('/users/../../todo.txt')347+ .expect(403, /ForbiddenError/, done)348+ })349+350+ it('should 404 when URL too long', function (done) {351+ var app = express()352+ var root = fixtures + Array(10000).join('/foobar')353+354+ app.use(express.static(root, { 'fallthrough': false }))355+ app.use(function (req, res, next) {356+ res.sendStatus(404)357+ })358+359+ request(app)360+ .get('/')361+ .expect(404, /ENAMETOOLONG/, done)362+ })363+364+ describe('with redirect: true', function () {365+ before(function () {366+ this.app = createApp(fixtures, { 'fallthrough': false, 'redirect': true })367+ })368+369+ it('should 404 when directory', function (done) {370+ request(this.app)371+ .get('/pets/')372+ .expect(404, /NotFoundError|ENOENT/, done)373+ })374+375+ it('should redirect when directory without slash', function (done) {376+ request(this.app)377+ .get('/pets')378+ .expect(301, /Redirecting/, done)379+ })380+ })381+382+ describe('with redirect: false', function () {383+ before(function () {384+ this.app = createApp(fixtures, { 'fallthrough': false, 'redirect': false })385+ })386+387+ it('should 404 when directory', function (done) {388+ request(this.app)389+ .get('/pets/')390+ .expect(404, /NotFoundError|ENOENT/, done)391+ })392+393+ it('should 404 when directory without slash', function (done) {394+ request(this.app)395+ .get('/pets')396+ .expect(404, /NotFoundError|ENOENT/, done)397+ })398+ })399+ })400+ })401+402+ describe('hidden files', function () {403+ before(function () {404+ this.app = createApp(fixtures, { 'dotfiles': 'allow' })405+ })406+407+ it('should be served when dotfiles: "allow" is given', function (done) {408+ request(this.app)409+ .get('/.name')410+ .expect(200)411+ .expect(utils.shouldHaveBody(Buffer.from('tobi')))412+ .end(done)413+ })414+ })415+416+ describe('immutable', function () {417+ it('should default to false', function (done) {418+ request(createApp(fixtures))419+ .get('/nums.txt')420+ .expect('Cache-Control', 'public, max-age=0', done)421+ })422+423+ it('should set immutable directive in Cache-Control', function (done) {424+ request(createApp(fixtures, { 'immutable': true, 'maxAge': '1h' }))425+ .get('/nums.txt')426+ .expect('Cache-Control', 'public, max-age=3600, immutable', done)427+ })428+ })429+430+ describe('lastModified', function () {431+ describe('when false', function () {432+ it('should not include Last-Modifed', function (done) {433+ request(createApp(fixtures, { 'lastModified': false }))434+ .get('/nums.txt')435+ .expect(utils.shouldNotHaveHeader('Last-Modified'))436+ .expect(200, '123456789', done)437+ })438+ })439+440+ describe('when true', function () {441+ it('should include Last-Modifed', function (done) {442+ request(createApp(fixtures, { 'lastModified': true }))443+ .get('/nums.txt')444+ .expect('Last-Modified', /^\w{3}, \d+ \w+ \d+ \d+:\d+:\d+ \w+$/)445+ .expect(200, '123456789', done)446+ })447+ })448+ })449+450+ describe('maxAge', function () {451+ it('should accept string', function (done) {452+ request(createApp(fixtures, { 'maxAge': '30d' }))453+ .get('/todo.txt')454+ .expect('cache-control', 'public, max-age=' + (60 * 60 * 24 * 30))455+ .expect(200, done)456+ })457+458+ it('should be reasonable when infinite', function (done) {459+ request(createApp(fixtures, { 'maxAge': Infinity }))460+ .get('/todo.txt')461+ .expect('cache-control', 'public, max-age=' + (60 * 60 * 24 * 365))462+ .expect(200, done)463+ })464+ })465+466+ describe('redirect', function () {467+ before(function () {468+ this.app = express()469+ this.app.use(function (req, res, next) {470+ req.originalUrl = req.url =471+ req.originalUrl.replace(/\/snow(\/|$)/, '/snow \u2603$1')472+ next()473+ })474+ this.app.use(express.static(fixtures))475+ })476+477+ it('should redirect directories', function (done) {478+ request(this.app)479+ .get('/users')480+ .expect('Location', '/users/')481+ .expect(301, done)482+ })483+484+ it('should include HTML link', function (done) {485+ request(this.app)486+ .get('/users')487+ .expect('Location', '/users/')488+ .expect(301, /<a href="\/users\/">/, done)489+ })490+491+ it('should redirect directories with query string', function (done) {492+ request(this.app)493+ .get('/users?name=john')494+ .expect('Location', '/users/?name=john')495+ .expect(301, done)496+ })497+498+ it('should not redirect to protocol-relative locations', function (done) {499+ request(this.app)500+ .get('//users')501+ .expect('Location', '/users/')502+ .expect(301, done)503+ })504+505+ it('should ensure redirect URL is properly encoded', function (done) {506+ request(this.app)507+ .get('/snow')508+ .expect('Location', '/snow%20%E2%98%83/')509+ .expect('Content-Type', /html/)510+ .expect(301, />Redirecting to <a href="\/snow%20%E2%98%83\/">\/snow%20%E2%98%83\/<\/a></, done)511+ })512+513+ it('should respond with default Content-Security-Policy', function (done) {514+ request(this.app)515+ .get('/users')516+ .expect('Content-Security-Policy', "default-src 'none'")517+ .expect(301, done)518+ })519+520+ it('should not redirect incorrectly', function (done) {521+ request(this.app)522+ .get('/')523+ .expect(404, done)524+ })525+526+ describe('when false', function () {527+ before(function () {528+ this.app = createApp(fixtures, { 'redirect': false })529+ })530+531+ it('should disable redirect', function (done) {532+ request(this.app)533+ .get('/users')534+ .expect(404, done)535+ })536+ })537+ })538+539+ describe('setHeaders', function () {540+ before(function () {541+ this.app = express()542+ this.app.use(express.static(fixtures, { 'setHeaders': function (res) {543+ res.setHeader('x-custom', 'set')544+ } }))545+ })546+547+ it('should reject non-functions', function () {548+ assert.throws(express.static.bind(null, fixtures, { 'setHeaders': 3 }), /setHeaders.*function/)549+ })550+551+ it('should get called when sending file', function (done) {552+ request(this.app)553+ .get('/nums.txt')554+ .expect('x-custom', 'set')555+ .expect(200, done)556+ })557+558+ it('should not get called on 404', function (done) {559+ request(this.app)560+ .get('/bogus')561+ .expect(utils.shouldNotHaveHeader('x-custom'))562+ .expect(404, done)563+ })564+565+ it('should not get called on redirect', function (done) {566+ request(this.app)567+ .get('/users')568+ .expect(utils.shouldNotHaveHeader('x-custom'))569+ .expect(301, done)570+ })571+ })572+573+ describe('when traversing past root', function () {574+ before(function () {575+ this.app = createApp(fixtures, { 'fallthrough': false })576+ })577+578+ it('should catch urlencoded ../', function (done) {579+ request(this.app)580+ .get('/users/%2e%2e/%2e%2e/todo.txt')581+ .expect(403, done)582+ })583+584+ it('should not allow root path disclosure', function (done) {585+ request(this.app)586+ .get('/users/../../fixtures/todo.txt')587+ .expect(403, done)588+ })589+ })590+591+ describe('when request has "Range" header', function () {592+ before(function () {593+ this.app = createApp()594+ })595+596+ it('should support byte ranges', function (done) {597+ request(this.app)598+ .get('/nums.txt')599+ .set('Range', 'bytes=0-4')600+ .expect('12345', done)601+ })602+603+ it('should be inclusive', function (done) {604+ request(this.app)605+ .get('/nums.txt')606+ .set('Range', 'bytes=0-0')607+ .expect('1', done)608+ })609+610+ it('should set Content-Range', function (done) {611+ request(this.app)612+ .get('/nums.txt')613+ .set('Range', 'bytes=2-5')614+ .expect('Content-Range', 'bytes 2-5/9', done)615+ })616+617+ it('should support -n', function (done) {618+ request(this.app)619+ .get('/nums.txt')620+ .set('Range', 'bytes=-3')621+ .expect('789', done)622+ })623+624+ it('should support n-', function (done) {625+ request(this.app)626+ .get('/nums.txt')627+ .set('Range', 'bytes=3-')628+ .expect('456789', done)629+ })630+631+ it('should respond with 206 "Partial Content"', function (done) {632+ request(this.app)633+ .get('/nums.txt')634+ .set('Range', 'bytes=0-4')635+ .expect(206, done)636+ })637+638+ it('should set Content-Length to the # of octets transferred', function (done) {639+ request(this.app)640+ .get('/nums.txt')641+ .set('Range', 'bytes=2-3')642+ .expect('Content-Length', '2')643+ .expect(206, '34', done)644+ })645+646+ describe('when last-byte-pos of the range is greater than current length', function () {647+ it('is taken to be equal to one less than the current length', function (done) {648+ request(this.app)649+ .get('/nums.txt')650+ .set('Range', 'bytes=2-50')651+ .expect('Content-Range', 'bytes 2-8/9', done)652+ })653+654+ it('should adapt the Content-Length accordingly', function (done) {655+ request(this.app)656+ .get('/nums.txt')657+ .set('Range', 'bytes=2-50')658+ .expect('Content-Length', '7')659+ .expect(206, done)660+ })661+ })662+663+ describe('when the first- byte-pos of the range is greater than the current length', function () {664+ it('should respond with 416', function (done) {665+ request(this.app)666+ .get('/nums.txt')667+ .set('Range', 'bytes=9-50')668+ .expect(416, done)669+ })670+671+ it('should include a Content-Range header of complete length', function (done) {672+ request(this.app)673+ .get('/nums.txt')674+ .set('Range', 'bytes=9-50')675+ .expect('Content-Range', 'bytes */9')676+ .expect(416, done)677+ })678+ })679+680+ describe('when syntactically invalid', function () {681+ it('should respond with 200 and the entire contents', function (done) {682+ request(this.app)683+ .get('/nums.txt')684+ .set('Range', 'asdf')685+ .expect('123456789', done)686+ })687+ })688+ })689+690+ describe('when index at mount point', function () {691+ before(function () {692+ this.app = express()693+ this.app.use('/users', express.static(fixtures + '/users'))694+ })695+696+ it('should redirect correctly', function (done) {697+ request(this.app)698+ .get('/users')699+ .expect('Location', '/users/')700+ .expect(301, done)701+ })702+ })703+704+ describe('when mounted', function () {705+ before(function () {706+ this.app = express()707+ this.app.use('/static', express.static(fixtures))708+ })709+710+ it('should redirect relative to the originalUrl', function (done) {711+ request(this.app)712+ .get('/static/users')713+ .expect('Location', '/static/users/')714+ .expect(301, done)715+ })716+717+ it('should not choke on auth-looking URL', function (done) {718+ request(this.app)719+ .get('//todo@txt')720+ .expect(404, done)721+ })722+ })723+724+ //725+ // NOTE: This is not a real part of the API, but726+ // over time this has become something users727+ // are doing, so this will prevent unseen728+ // regressions around this use-case.729+ //730+ describe('when mounted "root" as a file', function () {731+ before(function () {732+ this.app = express()733+ this.app.use('/todo.txt', express.static(fixtures + '/todo.txt'))734+ })735+736+ it('should load the file when on trailing slash', function (done) {737+ request(this.app)738+ .get('/todo.txt')739+ .expect(200, '- groceries', done)740+ })741+742+ it('should 404 when trailing slash', function (done) {743+ request(this.app)744+ .get('/todo.txt/')745+ .expect(404, done)746+ })747+ })748+749+ describe('when responding non-2xx or 304', function () {750+ it('should not alter the status', function (done) {751+ var app = express()752+753+ app.use(function (req, res, next) {754+ res.status(501)755+ next()756+ })757+ app.use(express.static(fixtures))758+759+ request(app)760+ .get('/todo.txt')761+ .expect(501, '- groceries', done)762+ })763+ })764+765+ describe('when index file serving disabled', function () {766+ before(function () {767+ this.app = express()768+ this.app.use('/static', express.static(fixtures, { 'index': false }))769+ this.app.use(function (req, res, next) {770+ res.sendStatus(404)771+ })772+ })773+774+ it('should next() on directory', function (done) {775+ request(this.app)776+ .get('/static/users/')777+ .expect(404, 'Not Found', done)778+ })779+780+ it('should redirect to trailing slash', function (done) {781+ request(this.app)782+ .get('/static/users')783+ .expect('Location', '/static/users/')784+ .expect(301, done)785+ })786+787+ it('should next() on mount point', function (done) {788+ request(this.app)789+ .get('/static/')790+ .expect(404, 'Not Found', done)791+ })792+793+ it('should redirect to trailing slash mount point', function (done) {794+ request(this.app)795+ .get('/static')796+ .expect('Location', '/static/')797+ .expect(301, done)798+ })799+ })800+})801+802+function createApp (dir, options, fn) {803+ var app = express()804+ var root = dir || fixtures805+806+ app.use(express.static(root, options))807+808+ app.use(function (req, res, next) {809+ res.sendStatus(404)810+ })811+812+ return app813+}added:test/express.text.js+441 added
1+2+var assert = require('assert')3+var Buffer = require('safe-buffer').Buffer4+var express = require('..')5+var request = require('supertest')6+7+describe('express.text()', function () {8+ before(function () {9+ this.app = createApp()10+ })11+12+ it('should parse text/plain', function (done) {13+ request(this.app)14+ .post('/')15+ .set('Content-Type', 'text/plain')16+ .send('user is tobi')17+ .expect(200, '"user is tobi"', done)18+ })19+20+ it('should 400 when invalid content-length', function (done) {21+ var app = express()22+23+ app.use(function (req, res, next) {24+ req.headers['content-length'] = '20' // bad length25+ next()26+ })27+28+ app.use(express.text())29+30+ app.post('/', function (req, res) {31+ res.json(req.body)32+ })33+34+ request(app)35+ .post('/')36+ .set('Content-Type', 'text/plain')37+ .send('user')38+ .expect(400, /content length/, done)39+ })40+41+ it('should handle Content-Length: 0', function (done) {42+ request(createApp({ limit: '1kb' }))43+ .post('/')44+ .set('Content-Type', 'text/plain')45+ .set('Content-Length', '0')46+ .expect(200, '""', done)47+ })48+49+ it('should handle empty message-body', function (done) {50+ request(createApp({ limit: '1kb' }))51+ .post('/')52+ .set('Content-Type', 'text/plain')53+ .set('Transfer-Encoding', 'chunked')54+ .send('')55+ .expect(200, '""', done)56+ })57+58+ it('should handle duplicated middleware', function (done) {59+ var app = express()60+61+ app.use(express.text())62+ app.use(express.text())63+64+ app.post('/', function (req, res) {65+ res.json(req.body)66+ })67+68+ request(app)69+ .post('/')70+ .set('Content-Type', 'text/plain')71+ .send('user is tobi')72+ .expect(200, '"user is tobi"', done)73+ })74+75+ describe('with defaultCharset option', function () {76+ it('should change default charset', function (done) {77+ var app = createApp({ defaultCharset: 'koi8-r' })78+ var test = request(app).post('/')79+ test.set('Content-Type', 'text/plain')80+ test.write(Buffer.from('6e616d6520697320cec5d4', 'hex'))81+ test.expect(200, '"name is нет"', done)82+ })83+84+ it('should honor content-type charset', function (done) {85+ var app = createApp({ defaultCharset: 'koi8-r' })86+ var test = request(app).post('/')87+ test.set('Content-Type', 'text/plain; charset=utf-8')88+ test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))89+ test.expect(200, '"name is 论"', done)90+ })91+ })92+93+ describe('with limit option', function () {94+ it('should 413 when over limit with Content-Length', function (done) {95+ var buf = Buffer.alloc(1028, '.')96+ request(createApp({ limit: '1kb' }))97+ .post('/')98+ .set('Content-Type', 'text/plain')99+ .set('Content-Length', '1028')100+ .send(buf.toString())101+ .expect(413, done)102+ })103+104+ it('should 413 when over limit with chunked encoding', function (done) {105+ var buf = Buffer.alloc(1028, '.')106+ var app = createApp({ limit: '1kb' })107+ var test = request(app).post('/')108+ test.set('Content-Type', 'text/plain')109+ test.set('Transfer-Encoding', 'chunked')110+ test.write(buf.toString())111+ test.expect(413, done)112+ })113+114+ it('should accept number of bytes', function (done) {115+ var buf = Buffer.alloc(1028, '.')116+ request(createApp({ limit: 1024 }))117+ .post('/')118+ .set('Content-Type', 'text/plain')119+ .send(buf.toString())120+ .expect(413, done)121+ })122+123+ it('should not change when options altered', function (done) {124+ var buf = Buffer.alloc(1028, '.')125+ var options = { limit: '1kb' }126+ var app = createApp(options)127+128+ options.limit = '100kb'129+130+ request(app)131+ .post('/')132+ .set('Content-Type', 'text/plain')133+ .send(buf.toString())134+ .expect(413, done)135+ })136+137+ it('should not hang response', function (done) {138+ var buf = Buffer.alloc(10240, '.')139+ var app = createApp({ limit: '8kb' })140+ var test = request(app).post('/')141+ test.set('Content-Type', 'text/plain')142+ test.write(buf)143+ test.write(buf)144+ test.write(buf)145+ test.expect(413, done)146+ })147+ })148+149+ describe('with inflate option', function () {150+ describe('when false', function () {151+ before(function () {152+ this.app = createApp({ inflate: false })153+ })154+155+ it('should not accept content-encoding', function (done) {156+ var test = request(this.app).post('/')157+ test.set('Content-Encoding', 'gzip')158+ test.set('Content-Type', 'text/plain')159+ test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex'))160+ test.expect(415, 'content encoding unsupported', done)161+ })162+ })163+164+ describe('when true', function () {165+ before(function () {166+ this.app = createApp({ inflate: true })167+ })168+169+ it('should accept content-encoding', function (done) {170+ var test = request(this.app).post('/')171+ test.set('Content-Encoding', 'gzip')172+ test.set('Content-Type', 'text/plain')173+ test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex'))174+ test.expect(200, '"name is 论"', done)175+ })176+ })177+ })178+179+ describe('with type option', function () {180+ describe('when "text/html"', function () {181+ before(function () {182+ this.app = createApp({ type: 'text/html' })183+ })184+185+ it('should parse for custom type', function (done) {186+ request(this.app)187+ .post('/')188+ .set('Content-Type', 'text/html')189+ .send('<b>tobi</b>')190+ .expect(200, '"<b>tobi</b>"', done)191+ })192+193+ it('should ignore standard type', function (done) {194+ request(this.app)195+ .post('/')196+ .set('Content-Type', 'text/plain')197+ .send('user is tobi')198+ .expect(200, '{}', done)199+ })200+ })201+202+ describe('when ["text/html", "text/plain"]', function () {203+ before(function () {204+ this.app = createApp({ type: ['text/html', 'text/plain'] })205+ })206+207+ it('should parse "text/html"', function (done) {208+ request(this.app)209+ .post('/')210+ .set('Content-Type', 'text/html')211+ .send('<b>tobi</b>')212+ .expect(200, '"<b>tobi</b>"', done)213+ })214+215+ it('should parse "text/plain"', function (done) {216+ request(this.app)217+ .post('/')218+ .set('Content-Type', 'text/plain')219+ .send('tobi')220+ .expect(200, '"tobi"', done)221+ })222+223+ it('should ignore "text/xml"', function (done) {224+ request(this.app)225+ .post('/')226+ .set('Content-Type', 'text/xml')227+ .send('<user>tobi</user>')228+ .expect(200, '{}', done)229+ })230+ })231+232+ describe('when a function', function () {233+ it('should parse when truthy value returned', function (done) {234+ var app = createApp({ type: accept })235+236+ function accept (req) {237+ return req.headers['content-type'] === 'text/vnd.something'238+ }239+240+ request(app)241+ .post('/')242+ .set('Content-Type', 'text/vnd.something')243+ .send('user is tobi')244+ .expect(200, '"user is tobi"', done)245+ })246+247+ it('should work without content-type', function (done) {248+ var app = createApp({ type: accept })249+250+ function accept (req) {251+ return true252+ }253+254+ var test = request(app).post('/')255+ test.write('user is tobi')256+ test.expect(200, '"user is tobi"', done)257+ })258+259+ it('should not invoke without a body', function (done) {260+ var app = createApp({ type: accept })261+262+ function accept (req) {263+ throw new Error('oops!')264+ }265+266+ request(app)267+ .get('/')268+ .expect(404, done)269+ })270+ })271+ })272+273+ describe('with verify option', function () {274+ it('should assert value is function', function () {275+ assert.throws(createApp.bind(null, { verify: 'lol' }),276+ /TypeError: option verify must be function/)277+ })278+279+ it('should error from verify', function (done) {280+ var app = createApp({ verify: function (req, res, buf) {281+ if (buf[0] === 0x20) throw new Error('no leading space')282+ } })283+284+ request(app)285+ .post('/')286+ .set('Content-Type', 'text/plain')287+ .send(' user is tobi')288+ .expect(403, 'no leading space', done)289+ })290+291+ it('should allow custom codes', function (done) {292+ var app = createApp({ verify: function (req, res, buf) {293+ if (buf[0] !== 0x20) return294+ var err = new Error('no leading space')295+ err.status = 400296+ throw err297+ } })298+299+ request(app)300+ .post('/')301+ .set('Content-Type', 'text/plain')302+ .send(' user is tobi')303+ .expect(400, 'no leading space', done)304+ })305+306+ it('should allow pass-through', function (done) {307+ var app = createApp({ verify: function (req, res, buf) {308+ if (buf[0] === 0x20) throw new Error('no leading space')309+ } })310+311+ request(app)312+ .post('/')313+ .set('Content-Type', 'text/plain')314+ .send('user is tobi')315+ .expect(200, '"user is tobi"', done)316+ })317+318+ it('should 415 on unknown charset prior to verify', function (done) {319+ var app = createApp({ verify: function (req, res, buf) {320+ throw new Error('unexpected verify call')321+ } })322+323+ var test = request(app).post('/')324+ test.set('Content-Type', 'text/plain; charset=x-bogus')325+ test.write(Buffer.from('00000000', 'hex'))326+ test.expect(415, 'unsupported charset "X-BOGUS"', done)327+ })328+ })329+330+ describe('charset', function () {331+ before(function () {332+ this.app = createApp()333+ })334+335+ it('should parse utf-8', function (done) {336+ var test = request(this.app).post('/')337+ test.set('Content-Type', 'text/plain; charset=utf-8')338+ test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))339+ test.expect(200, '"name is 论"', done)340+ })341+342+ it('should parse codepage charsets', function (done) {343+ var test = request(this.app).post('/')344+ test.set('Content-Type', 'text/plain; charset=koi8-r')345+ test.write(Buffer.from('6e616d6520697320cec5d4', 'hex'))346+ test.expect(200, '"name is нет"', done)347+ })348+349+ it('should parse when content-length != char length', function (done) {350+ var test = request(this.app).post('/')351+ test.set('Content-Type', 'text/plain; charset=utf-8')352+ test.set('Content-Length', '11')353+ test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))354+ test.expect(200, '"name is 论"', done)355+ })356+357+ it('should default to utf-8', function (done) {358+ var test = request(this.app).post('/')359+ test.set('Content-Type', 'text/plain')360+ test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))361+ test.expect(200, '"name is 论"', done)362+ })363+364+ it('should 415 on unknown charset', function (done) {365+ var test = request(this.app).post('/')366+ test.set('Content-Type', 'text/plain; charset=x-bogus')367+ test.write(Buffer.from('00000000', 'hex'))368+ test.expect(415, 'unsupported charset "X-BOGUS"', done)369+ })370+ })371+372+ describe('encoding', function () {373+ before(function () {374+ this.app = createApp({ limit: '10kb' })375+ })376+377+ it('should parse without encoding', function (done) {378+ var test = request(this.app).post('/')379+ test.set('Content-Type', 'text/plain')380+ test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))381+ test.expect(200, '"name is 论"', done)382+ })383+384+ it('should support identity encoding', function (done) {385+ var test = request(this.app).post('/')386+ test.set('Content-Encoding', 'identity')387+ test.set('Content-Type', 'text/plain')388+ test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))389+ test.expect(200, '"name is 论"', done)390+ })391+392+ it('should support gzip encoding', function (done) {393+ var test = request(this.app).post('/')394+ test.set('Content-Encoding', 'gzip')395+ test.set('Content-Type', 'text/plain')396+ test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex'))397+ test.expect(200, '"name is 论"', done)398+ })399+400+ it('should support deflate encoding', function (done) {401+ var test = request(this.app).post('/')402+ test.set('Content-Encoding', 'deflate')403+ test.set('Content-Type', 'text/plain')404+ test.write(Buffer.from('789ccb4bcc4d55c82c5678b16e17001a6f050e', 'hex'))405+ test.expect(200, '"name is 论"', done)406+ })407+408+ it('should be case-insensitive', function (done) {409+ var test = request(this.app).post('/')410+ test.set('Content-Encoding', 'GZIP')411+ test.set('Content-Type', 'text/plain')412+ test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex'))413+ test.expect(200, '"name is 论"', done)414+ })415+416+ it('should fail on unknown encoding', function (done) {417+ var test = request(this.app).post('/')418+ test.set('Content-Encoding', 'nulls')419+ test.set('Content-Type', 'text/plain')420+ test.write(Buffer.from('000000000000', 'hex'))421+ test.expect(415, 'unsupported content encoding "nulls"', done)422+ })423+ })424+})425+426+function createApp (options) {427+ var app = express()428+429+ app.use(express.text(options))430+431+ app.use(function (err, req, res, next) {432+ res.status(err.status || 500)433+ res.send(err.message)434+ })435+436+ app.post('/', function (req, res) {437+ res.json(req.body)438+ })439+440+ return app441+}added:test/express.urlencoded.js+734 added
1+2+var assert = require('assert')3+var Buffer = require('safe-buffer').Buffer4+var express = require('..')5+var request = require('supertest')6+7+describe('express.urlencoded()', function () {8+ before(function () {9+ this.app = createApp()10+ })11+12+ it('should parse x-www-form-urlencoded', function (done) {13+ request(this.app)14+ .post('/')15+ .set('Content-Type', 'application/x-www-form-urlencoded')16+ .send('user=tobi')17+ .expect(200, '{"user":"tobi"}', done)18+ })19+20+ it('should 400 when invalid content-length', function (done) {21+ var app = express()22+23+ app.use(function (req, res, next) {24+ req.headers['content-length'] = '20' // bad length25+ next()26+ })27+28+ app.use(express.urlencoded())29+30+ app.post('/', function (req, res) {31+ res.json(req.body)32+ })33+34+ request(app)35+ .post('/')36+ .set('Content-Type', 'application/x-www-form-urlencoded')37+ .send('str=')38+ .expect(400, /content length/, done)39+ })40+41+ it('should handle Content-Length: 0', function (done) {42+ request(this.app)43+ .post('/')44+ .set('Content-Type', 'application/x-www-form-urlencoded')45+ .set('Content-Length', '0')46+ .send('')47+ .expect(200, '{}', done)48+ })49+50+ it('should handle empty message-body', function (done) {51+ request(createApp({ limit: '1kb' }))52+ .post('/')53+ .set('Content-Type', 'application/x-www-form-urlencoded')54+ .set('Transfer-Encoding', 'chunked')55+ .send('')56+ .expect(200, '{}', done)57+ })58+59+ it('should handle duplicated middleware', function (done) {60+ var app = express()61+62+ app.use(express.urlencoded())63+ app.use(express.urlencoded())64+65+ app.post('/', function (req, res) {66+ res.json(req.body)67+ })68+69+ request(app)70+ .post('/')71+ .set('Content-Type', 'application/x-www-form-urlencoded')72+ .send('user=tobi')73+ .expect(200, '{"user":"tobi"}', done)74+ })75+76+ it('should parse extended syntax', function (done) {77+ request(this.app)78+ .post('/')79+ .set('Content-Type', 'application/x-www-form-urlencoded')80+ .send('user[name][first]=Tobi')81+ .expect(200, '{"user":{"name":{"first":"Tobi"}}}', done)82+ })83+84+ describe('with extended option', function () {85+ describe('when false', function () {86+ before(function () {87+ this.app = createApp({ extended: false })88+ })89+90+ it('should not parse extended syntax', function (done) {91+ request(this.app)92+ .post('/')93+ .set('Content-Type', 'application/x-www-form-urlencoded')94+ .send('user[name][first]=Tobi')95+ .expect(200, '{"user[name][first]":"Tobi"}', done)96+ })97+98+ it('should parse multiple key instances', function (done) {99+ request(this.app)100+ .post('/')101+ .set('Content-Type', 'application/x-www-form-urlencoded')102+ .send('user=Tobi&user=Loki')103+ .expect(200, '{"user":["Tobi","Loki"]}', done)104+ })105+ })106+107+ describe('when true', function () {108+ before(function () {109+ this.app = createApp({ extended: true })110+ })111+112+ it('should parse multiple key instances', function (done) {113+ request(this.app)114+ .post('/')115+ .set('Content-Type', 'application/x-www-form-urlencoded')116+ .send('user=Tobi&user=Loki')117+ .expect(200, '{"user":["Tobi","Loki"]}', done)118+ })119+120+ it('should parse extended syntax', function (done) {121+ request(this.app)122+ .post('/')123+ .set('Content-Type', 'application/x-www-form-urlencoded')124+ .send('user[name][first]=Tobi')125+ .expect(200, '{"user":{"name":{"first":"Tobi"}}}', done)126+ })127+128+ it('should parse parameters with dots', function (done) {129+ request(this.app)130+ .post('/')131+ .set('Content-Type', 'application/x-www-form-urlencoded')132+ .send('user.name=Tobi')133+ .expect(200, '{"user.name":"Tobi"}', done)134+ })135+136+ it('should parse fully-encoded extended syntax', function (done) {137+ request(this.app)138+ .post('/')139+ .set('Content-Type', 'application/x-www-form-urlencoded')140+ .send('user%5Bname%5D%5Bfirst%5D=Tobi')141+ .expect(200, '{"user":{"name":{"first":"Tobi"}}}', done)142+ })143+144+ it('should parse array index notation', function (done) {145+ request(this.app)146+ .post('/')147+ .set('Content-Type', 'application/x-www-form-urlencoded')148+ .send('foo[0]=bar&foo[1]=baz')149+ .expect(200, '{"foo":["bar","baz"]}', done)150+ })151+152+ it('should parse array index notation with large array', function (done) {153+ var str = 'f[0]=0'154+155+ for (var i = 1; i < 500; i++) {156+ str += '&f[' + i + ']=' + i.toString(16)157+ }158+159+ request(this.app)160+ .post('/')161+ .set('Content-Type', 'application/x-www-form-urlencoded')162+ .send(str)163+ .expect(function (res) {164+ var obj = JSON.parse(res.text)165+ assert.strictEqual(Object.keys(obj).length, 1)166+ assert.strictEqual(Array.isArray(obj.f), true)167+ assert.strictEqual(obj.f.length, 500)168+ })169+ .expect(200, done)170+ })171+172+ it('should parse array of objects syntax', function (done) {173+ request(this.app)174+ .post('/')175+ .set('Content-Type', 'application/x-www-form-urlencoded')176+ .send('foo[0][bar]=baz&foo[0][fizz]=buzz&foo[]=done!')177+ .expect(200, '{"foo":[{"bar":"baz","fizz":"buzz"},"done!"]}', done)178+ })179+180+ it('should parse deep object', function (done) {181+ var str = 'foo'182+183+ for (var i = 0; i < 500; i++) {184+ str += '[p]'185+ }186+187+ str += '=bar'188+189+ request(this.app)190+ .post('/')191+ .set('Content-Type', 'application/x-www-form-urlencoded')192+ .send(str)193+ .expect(function (res) {194+ var obj = JSON.parse(res.text)195+ assert.strictEqual(Object.keys(obj).length, 1)196+ assert.strictEqual(typeof obj.foo, 'object')197+198+ var depth = 0199+ var ref = obj.foo200+ while ((ref = ref.p)) { depth++ }201+ assert.strictEqual(depth, 500)202+ })203+ .expect(200, done)204+ })205+ })206+ })207+208+ describe('with inflate option', function () {209+ describe('when false', function () {210+ before(function () {211+ this.app = createApp({ inflate: false })212+ })213+214+ it('should not accept content-encoding', function (done) {215+ var test = request(this.app).post('/')216+ test.set('Content-Encoding', 'gzip')217+ test.set('Content-Type', 'application/x-www-form-urlencoded')218+ test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))219+ test.expect(415, 'content encoding unsupported', done)220+ })221+ })222+223+ describe('when true', function () {224+ before(function () {225+ this.app = createApp({ inflate: true })226+ })227+228+ it('should accept content-encoding', function (done) {229+ var test = request(this.app).post('/')230+ test.set('Content-Encoding', 'gzip')231+ test.set('Content-Type', 'application/x-www-form-urlencoded')232+ test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))233+ test.expect(200, '{"name":"论"}', done)234+ })235+ })236+ })237+238+ describe('with limit option', function () {239+ it('should 413 when over limit with Content-Length', function (done) {240+ var buf = Buffer.alloc(1024, '.')241+ request(createApp({ limit: '1kb' }))242+ .post('/')243+ .set('Content-Type', 'application/x-www-form-urlencoded')244+ .set('Content-Length', '1028')245+ .send('str=' + buf.toString())246+ .expect(413, done)247+ })248+249+ it('should 413 when over limit with chunked encoding', function (done) {250+ var buf = Buffer.alloc(1024, '.')251+ var app = createApp({ limit: '1kb' })252+ var test = request(app).post('/')253+ test.set('Content-Type', 'application/x-www-form-urlencoded')254+ test.set('Transfer-Encoding', 'chunked')255+ test.write('str=')256+ test.write(buf.toString())257+ test.expect(413, done)258+ })259+260+ it('should accept number of bytes', function (done) {261+ var buf = Buffer.alloc(1024, '.')262+ request(createApp({ limit: 1024 }))263+ .post('/')264+ .set('Content-Type', 'application/x-www-form-urlencoded')265+ .send('str=' + buf.toString())266+ .expect(413, done)267+ })268+269+ it('should not change when options altered', function (done) {270+ var buf = Buffer.alloc(1024, '.')271+ var options = { limit: '1kb' }272+ var app = createApp(options)273+274+ options.limit = '100kb'275+276+ request(app)277+ .post('/')278+ .set('Content-Type', 'application/x-www-form-urlencoded')279+ .send('str=' + buf.toString())280+ .expect(413, done)281+ })282+283+ it('should not hang response', function (done) {284+ var buf = Buffer.alloc(10240, '.')285+ var app = createApp({ limit: '8kb' })286+ var test = request(app).post('/')287+ test.set('Content-Type', 'application/x-www-form-urlencoded')288+ test.write(buf)289+ test.write(buf)290+ test.write(buf)291+ test.expect(413, done)292+ })293+ })294+295+ describe('with parameterLimit option', function () {296+ describe('with extended: false', function () {297+ it('should reject 0', function () {298+ assert.throws(createApp.bind(null, { extended: false, parameterLimit: 0 }),299+ /TypeError: option parameterLimit must be a positive number/)300+ })301+302+ it('should reject string', function () {303+ assert.throws(createApp.bind(null, { extended: false, parameterLimit: 'beep' }),304+ /TypeError: option parameterLimit must be a positive number/)305+ })306+307+ it('should 413 if over limit', function (done) {308+ request(createApp({ extended: false, parameterLimit: 10 }))309+ .post('/')310+ .set('Content-Type', 'application/x-www-form-urlencoded')311+ .send(createManyParams(11))312+ .expect(413, /too many parameters/, done)313+ })314+315+ it('should error with type = "parameters.too.many"', function (done) {316+ request(createApp({ extended: false, parameterLimit: 10 }))317+ .post('/')318+ .set('Content-Type', 'application/x-www-form-urlencoded')319+ .set('X-Error-Property', 'type')320+ .send(createManyParams(11))321+ .expect(413, 'parameters.too.many', done)322+ })323+324+ it('should work when at the limit', function (done) {325+ request(createApp({ extended: false, parameterLimit: 10 }))326+ .post('/')327+ .set('Content-Type', 'application/x-www-form-urlencoded')328+ .send(createManyParams(10))329+ .expect(expectKeyCount(10))330+ .expect(200, done)331+ })332+333+ it('should work if number is floating point', function (done) {334+ request(createApp({ extended: false, parameterLimit: 10.1 }))335+ .post('/')336+ .set('Content-Type', 'application/x-www-form-urlencoded')337+ .send(createManyParams(11))338+ .expect(413, /too many parameters/, done)339+ })340+341+ it('should work with large limit', function (done) {342+ request(createApp({ extended: false, parameterLimit: 5000 }))343+ .post('/')344+ .set('Content-Type', 'application/x-www-form-urlencoded')345+ .send(createManyParams(5000))346+ .expect(expectKeyCount(5000))347+ .expect(200, done)348+ })349+350+ it('should work with Infinity limit', function (done) {351+ request(createApp({ extended: false, parameterLimit: Infinity }))352+ .post('/')353+ .set('Content-Type', 'application/x-www-form-urlencoded')354+ .send(createManyParams(10000))355+ .expect(expectKeyCount(10000))356+ .expect(200, done)357+ })358+ })359+360+ describe('with extended: true', function () {361+ it('should reject 0', function () {362+ assert.throws(createApp.bind(null, { extended: true, parameterLimit: 0 }),363+ /TypeError: option parameterLimit must be a positive number/)364+ })365+366+ it('should reject string', function () {367+ assert.throws(createApp.bind(null, { extended: true, parameterLimit: 'beep' }),368+ /TypeError: option parameterLimit must be a positive number/)369+ })370+371+ it('should 413 if over limit', function (done) {372+ request(createApp({ extended: true, parameterLimit: 10 }))373+ .post('/')374+ .set('Content-Type', 'application/x-www-form-urlencoded')375+ .send(createManyParams(11))376+ .expect(413, /too many parameters/, done)377+ })378+379+ it('should error with type = "parameters.too.many"', function (done) {380+ request(createApp({ extended: true, parameterLimit: 10 }))381+ .post('/')382+ .set('Content-Type', 'application/x-www-form-urlencoded')383+ .set('X-Error-Property', 'type')384+ .send(createManyParams(11))385+ .expect(413, 'parameters.too.many', done)386+ })387+388+ it('should work when at the limit', function (done) {389+ request(createApp({ extended: true, parameterLimit: 10 }))390+ .post('/')391+ .set('Content-Type', 'application/x-www-form-urlencoded')392+ .send(createManyParams(10))393+ .expect(expectKeyCount(10))394+ .expect(200, done)395+ })396+397+ it('should work if number is floating point', function (done) {398+ request(createApp({ extended: true, parameterLimit: 10.1 }))399+ .post('/')400+ .set('Content-Type', 'application/x-www-form-urlencoded')401+ .send(createManyParams(11))402+ .expect(413, /too many parameters/, done)403+ })404+405+ it('should work with large limit', function (done) {406+ request(createApp({ extended: true, parameterLimit: 5000 }))407+ .post('/')408+ .set('Content-Type', 'application/x-www-form-urlencoded')409+ .send(createManyParams(5000))410+ .expect(expectKeyCount(5000))411+ .expect(200, done)412+ })413+414+ it('should work with Infinity limit', function (done) {415+ request(createApp({ extended: true, parameterLimit: Infinity }))416+ .post('/')417+ .set('Content-Type', 'application/x-www-form-urlencoded')418+ .send(createManyParams(10000))419+ .expect(expectKeyCount(10000))420+ .expect(200, done)421+ })422+ })423+ })424+425+ describe('with type option', function () {426+ describe('when "application/vnd.x-www-form-urlencoded"', function () {427+ before(function () {428+ this.app = createApp({ type: 'application/vnd.x-www-form-urlencoded' })429+ })430+431+ it('should parse for custom type', function (done) {432+ request(this.app)433+ .post('/')434+ .set('Content-Type', 'application/vnd.x-www-form-urlencoded')435+ .send('user=tobi')436+ .expect(200, '{"user":"tobi"}', done)437+ })438+439+ it('should ignore standard type', function (done) {440+ request(this.app)441+ .post('/')442+ .set('Content-Type', 'application/x-www-form-urlencoded')443+ .send('user=tobi')444+ .expect(200, '{}', done)445+ })446+ })447+448+ describe('when ["urlencoded", "application/x-pairs"]', function () {449+ before(function () {450+ this.app = createApp({451+ type: ['urlencoded', 'application/x-pairs']452+ })453+ })454+455+ it('should parse "application/x-www-form-urlencoded"', function (done) {456+ request(this.app)457+ .post('/')458+ .set('Content-Type', 'application/x-www-form-urlencoded')459+ .send('user=tobi')460+ .expect(200, '{"user":"tobi"}', done)461+ })462+463+ it('should parse "application/x-pairs"', function (done) {464+ request(this.app)465+ .post('/')466+ .set('Content-Type', 'application/x-pairs')467+ .send('user=tobi')468+ .expect(200, '{"user":"tobi"}', done)469+ })470+471+ it('should ignore application/x-foo', function (done) {472+ request(this.app)473+ .post('/')474+ .set('Content-Type', 'application/x-foo')475+ .send('user=tobi')476+ .expect(200, '{}', done)477+ })478+ })479+480+ describe('when a function', function () {481+ it('should parse when truthy value returned', function (done) {482+ var app = createApp({ type: accept })483+484+ function accept (req) {485+ return req.headers['content-type'] === 'application/vnd.something'486+ }487+488+ request(app)489+ .post('/')490+ .set('Content-Type', 'application/vnd.something')491+ .send('user=tobi')492+ .expect(200, '{"user":"tobi"}', done)493+ })494+495+ it('should work without content-type', function (done) {496+ var app = createApp({ type: accept })497+498+ function accept (req) {499+ return true500+ }501+502+ var test = request(app).post('/')503+ test.write('user=tobi')504+ test.expect(200, '{"user":"tobi"}', done)505+ })506+507+ it('should not invoke without a body', function (done) {508+ var app = createApp({ type: accept })509+510+ function accept (req) {511+ throw new Error('oops!')512+ }513+514+ request(app)515+ .get('/')516+ .expect(404, done)517+ })518+ })519+ })520+521+ describe('with verify option', function () {522+ it('should assert value if function', function () {523+ assert.throws(createApp.bind(null, { verify: 'lol' }),524+ /TypeError: option verify must be function/)525+ })526+527+ it('should error from verify', function (done) {528+ var app = createApp({ verify: function (req, res, buf) {529+ if (buf[0] === 0x20) throw new Error('no leading space')530+ } })531+532+ request(app)533+ .post('/')534+ .set('Content-Type', 'application/x-www-form-urlencoded')535+ .send(' user=tobi')536+ .expect(403, 'no leading space', done)537+ })538+539+ it('should error with type = "entity.verify.failed"', function (done) {540+ var app = createApp({ verify: function (req, res, buf) {541+ if (buf[0] === 0x20) throw new Error('no leading space')542+ } })543+544+ request(app)545+ .post('/')546+ .set('Content-Type', 'application/x-www-form-urlencoded')547+ .set('X-Error-Property', 'type')548+ .send(' user=tobi')549+ .expect(403, 'entity.verify.failed', done)550+ })551+552+ it('should allow custom codes', function (done) {553+ var app = createApp({ verify: function (req, res, buf) {554+ if (buf[0] !== 0x20) return555+ var err = new Error('no leading space')556+ err.status = 400557+ throw err558+ } })559+560+ request(app)561+ .post('/')562+ .set('Content-Type', 'application/x-www-form-urlencoded')563+ .send(' user=tobi')564+ .expect(400, 'no leading space', done)565+ })566+567+ it('should allow custom type', function (done) {568+ var app = createApp({ verify: function (req, res, buf) {569+ if (buf[0] !== 0x20) return570+ var err = new Error('no leading space')571+ err.type = 'foo.bar'572+ throw err573+ } })574+575+ request(app)576+ .post('/')577+ .set('Content-Type', 'application/x-www-form-urlencoded')578+ .set('X-Error-Property', 'type')579+ .send(' user=tobi')580+ .expect(403, 'foo.bar', done)581+ })582+583+ it('should allow pass-through', function (done) {584+ var app = createApp({ verify: function (req, res, buf) {585+ if (buf[0] === 0x5b) throw new Error('no arrays')586+ } })587+588+ request(app)589+ .post('/')590+ .set('Content-Type', 'application/x-www-form-urlencoded')591+ .send('user=tobi')592+ .expect(200, '{"user":"tobi"}', done)593+ })594+595+ it('should 415 on unknown charset prior to verify', function (done) {596+ var app = createApp({ verify: function (req, res, buf) {597+ throw new Error('unexpected verify call')598+ } })599+600+ var test = request(app).post('/')601+ test.set('Content-Type', 'application/x-www-form-urlencoded; charset=x-bogus')602+ test.write(Buffer.from('00000000', 'hex'))603+ test.expect(415, 'unsupported charset "X-BOGUS"', done)604+ })605+ })606+607+ describe('charset', function () {608+ before(function () {609+ this.app = createApp()610+ })611+612+ it('should parse utf-8', function (done) {613+ var test = request(this.app).post('/')614+ test.set('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8')615+ test.write(Buffer.from('6e616d653de8aeba', 'hex'))616+ test.expect(200, '{"name":"论"}', done)617+ })618+619+ it('should parse when content-length != char length', function (done) {620+ var test = request(this.app).post('/')621+ test.set('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8')622+ test.set('Content-Length', '7')623+ test.write(Buffer.from('746573743dc3a5', 'hex'))624+ test.expect(200, '{"test":"å"}', done)625+ })626+627+ it('should default to utf-8', function (done) {628+ var test = request(this.app).post('/')629+ test.set('Content-Type', 'application/x-www-form-urlencoded')630+ test.write(Buffer.from('6e616d653de8aeba', 'hex'))631+ test.expect(200, '{"name":"论"}', done)632+ })633+634+ it('should fail on unknown charset', function (done) {635+ var test = request(this.app).post('/')636+ test.set('Content-Type', 'application/x-www-form-urlencoded; charset=koi8-r')637+ test.write(Buffer.from('6e616d653dcec5d4', 'hex'))638+ test.expect(415, 'unsupported charset "KOI8-R"', done)639+ })640+ })641+642+ describe('encoding', function () {643+ before(function () {644+ this.app = createApp({ limit: '10kb' })645+ })646+647+ it('should parse without encoding', function (done) {648+ var test = request(this.app).post('/')649+ test.set('Content-Type', 'application/x-www-form-urlencoded')650+ test.write(Buffer.from('6e616d653de8aeba', 'hex'))651+ test.expect(200, '{"name":"论"}', done)652+ })653+654+ it('should support identity encoding', function (done) {655+ var test = request(this.app).post('/')656+ test.set('Content-Encoding', 'identity')657+ test.set('Content-Type', 'application/x-www-form-urlencoded')658+ test.write(Buffer.from('6e616d653de8aeba', 'hex'))659+ test.expect(200, '{"name":"论"}', done)660+ })661+662+ it('should support gzip encoding', function (done) {663+ var test = request(this.app).post('/')664+ test.set('Content-Encoding', 'gzip')665+ test.set('Content-Type', 'application/x-www-form-urlencoded')666+ test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))667+ test.expect(200, '{"name":"论"}', done)668+ })669+670+ it('should support deflate encoding', function (done) {671+ var test = request(this.app).post('/')672+ test.set('Content-Encoding', 'deflate')673+ test.set('Content-Type', 'application/x-www-form-urlencoded')674+ test.write(Buffer.from('789ccb4bcc4db57db16e17001068042f', 'hex'))675+ test.expect(200, '{"name":"论"}', done)676+ })677+678+ it('should be case-insensitive', function (done) {679+ var test = request(this.app).post('/')680+ test.set('Content-Encoding', 'GZIP')681+ test.set('Content-Type', 'application/x-www-form-urlencoded')682+ test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))683+ test.expect(200, '{"name":"论"}', done)684+ })685+686+ it('should fail on unknown encoding', function (done) {687+ var test = request(this.app).post('/')688+ test.set('Content-Encoding', 'nulls')689+ test.set('Content-Type', 'application/x-www-form-urlencoded')690+ test.write(Buffer.from('000000000000', 'hex'))691+ test.expect(415, 'unsupported content encoding "nulls"', done)692+ })693+ })694+})695+696+function createManyParams (count) {697+ var str = ''698+699+ if (count === 0) {700+ return str701+ }702+703+ str += '0=0'704+705+ for (var i = 1; i < count; i++) {706+ var n = i.toString(36)707+ str += '&' + n + '=' + n708+ }709+710+ return str711+}712+713+function createApp (options) {714+ var app = express()715+716+ app.use(express.urlencoded(options))717+718+ app.use(function (err, req, res, next) {719+ res.status(err.status || 500)720+ res.send(String(err[req.headers['x-error-property'] || 'message']))721+ })722+723+ app.post('/', function (req, res) {724+ res.json(req.body)725+ })726+727+ return app728+}729+730+function expectKeyCount (count) {731+ return function (res) {732+ assert.strictEqual(Object.keys(JSON.parse(res.text)).length, count)733+ }734+}modified:test/middleware.basic.js+2 added
1 2+var assert = require('assert')3 var express = require('../');4 var request = require('supertest');5 6 describe('middleware', function(){26 unmodified lines33 .get('/')34 .set('Content-Type', 'application/json')35 .send('{"foo":"bar"}')36 .expect('Content-Type', 'application/json')37+ .expect(function () { assert.deepEqual(calls, ['one', 'two']) })38 .expect(200, '{"foo":"bar"}', done)39 })40 })41 })modified:test/req.acceptsCharsets.js+2 added-2 removed
16 unmodified lines17 .expect('yes', done);18 })19 })20 21- describe('when Accept-Charset is not present', function(){22- it('should return true when present', function(done){21+ describe('when Accept-Charset is present', function () {22+ it('should return true', function (done) {23 var app = express();24 25 app.use(function(req, res, next){26 res.end(req.acceptsCharsets('utf-8') ? 'yes' : 'no');23 unmodified linesmodified:test/req.acceptsEncodings.js+1 added-1 removed
1 unmodified line2 var express = require('../')3 , request = require('supertest');4 5 describe('req', function(){6- describe('.acceptsEncodingss', function(){6+ describe('.acceptsEncodings', function () {7 it('should be true if encoding accepted', function(done){8 var app = express();9 10 app.use(function(req, res){26 unmodified linesmodified:test/req.hostname.js+50 added
114 unmodified lines115 .get('/')116 .set('Host', 'example.com')117 .expect('example.com', done);118 })119+120+ describe('when multiple X-Forwarded-Host', function () {121+ it('should use the first value', function (done) {122+ var app = express()123+124+ app.enable('trust proxy')125+126+ app.use(function (req, res) {127+ res.send(req.hostname)128+ })129+130+ request(app)131+ .get('/')132+ .set('Host', 'localhost')133+ .set('X-Forwarded-Host', 'example.com, foobar.com')134+ .expect(200, 'example.com', done)135+ })136+137+ it('should remove OWS around comma', function (done) {138+ var app = express()139+140+ app.enable('trust proxy')141+142+ app.use(function (req, res) {143+ res.send(req.hostname)144+ })145+146+ request(app)147+ .get('/')148+ .set('Host', 'localhost')149+ .set('X-Forwarded-Host', 'example.com , foobar.com')150+ .expect(200, 'example.com', done)151+ })152+153+ it('should strip port number', function (done) {154+ var app = express()155+156+ app.enable('trust proxy')157+158+ app.use(function (req, res) {159+ res.send(req.hostname)160+ })161+162+ request(app)163+ .get('/')164+ .set('Host', 'localhost')165+ .set('X-Forwarded-Host', 'example.com:8080 , foobar.com:8888')166+ .expect(200, 'example.com', done)167+ })168+ })169 })170 171 describe('when "trust proxy" is disabled', function(){172 it('should ignore X-Forwarded-Host', function(done){15 unmodified linesmodified:test/req.query.js+3 added-3 removed
23 unmodified lines24 it('should parse complex keys', function (done) {25 var app = createApp('extended');26 27 request(app)28- .get('/?user[name]=tj')29- .expect(200, '{"user":{"name":"tj"}}', done);28+ .get('/?foo[0][bar]=baz&foo[0][fizz]=buzz&foo[]=done!')29+ .expect(200, '{"foo":[{"bar":"baz","fizz":"buzz"},"done!"]}', done);30 });31 32 it('should parse parameters with dots', function (done) {33 var app = createApp('extended');35 unmodified lines69 .expect(200, '{}', done);70 });71 });72 73- describe('when "query parser" disabled', function () {73+ describe('when "query parser" enabled', function () {74 it('should not parse complex keys', function (done) {75 var app = createApp(true);76 77 request(app)26 unmodified linesmodified:test/res.cookie.js+2 added-5 removed
106 unmodified lines107 var optionsCopy = merge({}, options);108 109 app.use(function(req, res){110 res.cookie('name', 'tobi', options)111- res.end();111+ res.json(options)112 });113 114 request(app)115 .get('/')116- .end(function(err, res){117- options.should.eql(optionsCopy);118- done();119- })116+ .expect(200, optionsCopy, done)117 })118 })119 120 describe('signed', function(){54 unmodified linesmodified:test/res.download.js+2 added-2 removed
108 unmodified lines109 .end(done)110 })111 112 describe('when options.headers contains Content-Disposition', function () {113- it('should should be ignored', function (done) {113+ it('should be ignored', function (done) {114 var app = express()115 116 app.use(function (req, res) {117 res.download('test/fixtures/user.html', 'document', {11 unmodified lines129 .expect('Content-Disposition', 'attachment; filename="document"')130 .end(done)131 })132 133- it('should should be ignored case-insensitively', function (done) {133+ it('should be ignored case-insensitively', function (done) {134 var app = express()135 136 app.use(function (req, res) {137 res.download('test/fixtures/user.html', 'document', {66 unmodified linesmodified:test/res.locals.js+4 added-6 removed
6 unmodified lines7 it('should be empty by default', function(done){8 var app = express();9 10 app.use(function(req, res){11- Object.keys(res.locals).should.eql([]);12- res.end();11+ res.json(res.locals)12 });13 14 request(app)15 .get('/')17- .expect(200, done);16+ .expect(200, {}, done)17 })18 })19 20 it('should work when mounted', function(done){7 unmodified lines28 next();29 });30 31 app.use(function(req, res){33- res.locals.foo.should.equal('bar');34- res.end();32+ res.json(res.locals)33 });34 35 request(app)36 .get('/')39- .expect(200, done);37+ .expect(200, { foo: 'bar' }, done)38 })39 })modified:test/res.sendFile.js+8 added
18 unmodified lines19 .get('/')20 .expect(500, /path.*required/, done);21 });22 23+ it('should error for non-string path', function (done) {24+ var app = createApp(42)25+26+ request(app)27+ .get('/')28+ .expect(500, /TypeError: path must be a string to res.sendFile/, done)29+ })30+31 it('should transfer a file', function (done) {32 var app = createApp(path.resolve(fixtures, 'name.txt'));33 34 request(app)358 unmodified linesmodified:.travis.yml+8 added-6 removed
5 unmodified lines6 - "2.5"7 - "3.3"8 - "4.9"9 - "5.12"10- - "6.14"10+ - "6.17"11 - "7.10"12- - "8.12"12+ - "8.16"13+ - "9.11"14+ - "10.15"15+ - "11.15"16+ - "12.3"17 matrix:18 include:15- - node_js: "9"19+ - node_js: "13"20 env: "NVM_NODEJS_ORG_MIRROR=https://nodejs.org/download/nightly"17- - node_js: "10"18- env: "NVM_NODEJS_ORG_MIRROR=https://nodejs.org/download/nightly"21 allow_failures:22 # Allow the nightly installs to fail23 - env: "NVM_NODEJS_ORG_MIRROR=https://nodejs.org/download/nightly"24 sudo: false36 unmodified lines61 - npm run lint62 after_script:63 - |64 # Upload coverage to coveralls63- npm install --save-dev coveralls@2.10.065+ npm install --save-dev coveralls@2.12.066 coveralls < ./coverage/lcov.infomodified:appveyor.yml+6 added-2 removed
5 unmodified lines6 - nodejs_version: "2.5"7 - nodejs_version: "3.3"8 - nodejs_version: "4.9"9 - nodejs_version: "5.12"10- - nodejs_version: "6.14"10+ - nodejs_version: "6.17"11 - nodejs_version: "7.10"12- - nodejs_version: "8.12"12+ - nodejs_version: "8.16"13+ - nodejs_version: "9.11"14+ - nodejs_version: "10.15"15+ - nodejs_version: "11.15"16+ - nodejs_version: "12.3"17 cache:18 - node_modules19 install:20 # Install Node.js44 unmodified linesmodified:Contributing.md+1 added-1 removed
17 unmodified lines18 # Logging Issues19 20 Log an issue for any question or problem you might have. When in doubt, log an issue, and21 any additional policies about what to include will be provided in the responses. The only22-exception is security dislosures which should be sent privately.22+exception is security disclosures which should be sent privately.23 24 Committers may direct you to another repository, ask for additional clarifications, and25 add appropriate metadata before the issue is addressed.26 59 unmodified linesmodified:History.md+70 added-9 removed
1+5.x2+===3+4+This incorporates all changes after 4.16.4 up to 4.17.1.5+6 5.0.0-alpha.7 / 2018-10-267 ==========================8 9 This is the seventh Express 5.0 alpha release, based off 4.16.4 and includes107 unmodified lines117 - `req.query` is now a getter instead of a plain property118 * add:119 - `app.router` is a reference to the base router120 121+4.17.1 / 2019-05-25122+===================123+124+ * Revert "Improve error message for `null`/`undefined` to `res.status`"125+126+4.17.0 / 2019-05-16127+===================128+129+ * Add `express.raw` to parse bodies into `Buffer`130+ * Add `express.text` to parse bodies into string131+ * Improve error message for non-strings to `res.sendFile`132+ * Improve error message for `null`/`undefined` to `res.status`133+ * Support multiple hosts in `X-Forwarded-Host`134+ * deps: accepts@~1.3.7135+ * deps: body-parser@1.19.0136+ - Add encoding MIK137+ - Add petabyte (`pb`) support138+ - Fix parsing array brackets after index139+ - deps: bytes@3.1.0140+ - deps: http-errors@1.7.2141+ - deps: iconv-lite@0.4.24142+ - deps: qs@6.7.0143+ - deps: raw-body@2.4.0144+ - deps: type-is@~1.6.17145+ * deps: content-disposition@0.5.3146+ * deps: cookie@0.4.0147+ - Add `SameSite=None` support148+ * deps: finalhandler@~1.1.2149+ - Set stricter `Content-Security-Policy` header150+ - deps: parseurl@~1.3.3151+ - deps: statuses@~1.5.0152+ * deps: parseurl@~1.3.3153+ * deps: proxy-addr@~2.0.5154+ - deps: ipaddr.js@1.9.0155+ * deps: qs@6.7.0156+ - Fix parsing array brackets after index157+ * deps: range-parser@~1.2.1158+ * deps: send@0.17.1159+ - Set stricter CSP header in redirect & error responses160+ - deps: http-errors@~1.7.2161+ - deps: mime@1.6.0162+ - deps: ms@2.1.1163+ - deps: range-parser@~1.2.1164+ - deps: statuses@~1.5.0165+ - perf: remove redundant `path.normalize` call166+ * deps: serve-static@1.14.1167+ - Set stricter CSP header in redirect response168+ - deps: parseurl@~1.3.3169+ - deps: send@0.17.1170+ * deps: setprototypeof@1.1.1171+ * deps: statuses@~1.5.0172+ - Add `103 Early Hints`173+ * deps: type-is@~1.6.18174+ - deps: mime-types@~2.1.24175+ - perf: prevent internal `throw` on invalid type176+177 4.16.4 / 2018-10-10178 ===================179 180 * Fix issue where `"Request aborted"` may be logged in `res.sendfile`288 unmodified lines469 * deps: accepts@~1.3.3470 - Fix including type extensions in parameters in `Accept` parsing471 - Fix parsing `Accept` parameters with quoted equals472 - Fix parsing `Accept` parameters with quoted semicolons412- - Many performance improvments473+ - Many performance improvements474 - deps: mime-types@~2.1.11475 - deps: negotiator@0.6.1476 * deps: content-type@~1.0.2477 - perf: enable strict mode6 unmodified lines484 - Throw on invalid values provided to `serialize`485 - perf: enable strict mode486 - perf: hoist regular expression487 - perf: use for loop in parse427- - perf: use string concatination for serialization488+ - perf: use string concatenation for serialization489 * deps: finalhandler@0.5.0490 - Change invalid or non-numeric status code to 500491 - Overwrite status message to match set status code492 - Prefer `err.statusCode` if `err.status` is invalid1 unmodified line494 - Use `statuses` instead of `http` module for status messages495 * deps: proxy-addr@~1.1.2496 - Fix accepting various invalid netmasks497 - Fix IPv6-mapped IPv4 validation edge cases437- - IPv4 netmasks must be contingous498+ - IPv4 netmasks must be contiguous499 - IPv6 addresses cannot be used as a netmask500 - deps: ipaddr.js@1.1.1501 * deps: qs@6.2.0502 - Add `decoder` option in `parse` function769 unmodified lines1272 * deps: accepts@1.0.31273 - deps: negotiator@0.4.61274 * deps: debug@1.0.21275 * deps: send@0.4.31215- - Do not throw un-catchable error on file open race condition1276+ - Do not throw uncatchable error on file open race condition1277 - Use `escape-html` for HTML escaping1278 - deps: debug@1.0.21279 - deps: finished@1.2.21280 - deps: fresh@0.2.21281 * deps: serve-static@1.2.31221- - Do not throw un-catchable error on file open race condition1282+ - Do not throw uncatchable error on file open race condition1283 - deps: send@0.4.31284 1285 4.4.2 / 2014-06-091286 ==================871 unmodified lines2158 - deps: serve-index@1.1.12159 - deps: serve-static@1.2.32160 * deps: debug@1.0.22161 * deps: send@0.4.32101- - Do not throw un-catchable error on file open race condition2162+ - Do not throw uncatchable error on file open race condition2163 - Use `escape-html` for HTML escaping2164 - deps: debug@1.0.22165 - deps: finished@1.2.22166 - deps: fresh@0.2.21176 unmodified lines3343 * Added view `helpers` export which act as additional local variables3344 * Updated haml submodule3345 * Changed ETag; removed inode, modified time only3346 * Fixed LF to CRLF for setting multiple cookies3286- * Fixed cookie complation; values are now urlencoded3347+ * Fixed cookie compilation; values are now urlencoded3348 * Fixed cookies parsing; accepts quoted values and url escaped cookies3349 3350 0.11.0 / 2010-05-063351 ==================186 unmodified lines3538 ==================3539 3540 * Added "plot" format option for Profiler (for gnuplot processing)3541 * Added request number to Profiler plugin3481- * Fixed binary encoding for multi-part file uploads, was previously defaulting to UTF83542+ * Fixed binary encoding for multipart file uploads, was previously defaulting to UTF83543 * Fixed issue with routes not firing when not files are present. Closes #1843544 * Fixed process.Promise -> events.Promise3545 3546 0.2.0 / 2010-02-0337 unmodified lines3584 * Updated Haml3585 * Updated sample chat app to show messages on load3586 * Updated libxmljs parseString -> parseHtmlString3587 * Fixed `make init` to work with older versions of git3527- * Fixed specs can now run independent specs for those who cant build deps. Closes #1273588+ * Fixed specs can now run independent specs for those who can't build deps. Closes #1273589 * Fixed issues introduced by the node url module changes. Closes 126.3590 * Fixed two assertions failing due to Collection#keys() returning strings3591 * Fixed faulty Collection#toArray() spec due to keys() returning strings3592 * Fixed `make test` now builds libxmljs.node before testing5 unmodified linesmodified:package.json+20 added-20 removed
25 unmodified lines26 "app",27 "api"28 ],29 "dependencies": {30- "accepts": "~1.3.5",30+ "accepts": "~1.3.7",31 "array-flatten": "2.1.1",32- "body-parser": "1.18.3",33- "content-disposition": "0.5.2",32+ "body-parser": "1.19.0",33+ "content-disposition": "0.5.3",34 "content-type": "~1.0.4",35- "cookie": "0.3.1",35+ "cookie": "0.4.0",36 "cookie-signature": "1.0.6",37 "debug": "3.1.0",38 "depd": "~1.1.2",39 "encodeurl": "~1.0.2",40 "escape-html": "~1.0.3",41 "etag": "~1.8.1",42- "finalhandler": "1.1.1",42+ "finalhandler": "~1.1.2",43 "fresh": "0.5.2",44 "merge-descriptors": "1.0.1",45 "methods": "~1.1.2",46 "on-finished": "~2.3.0",47- "parseurl": "~1.3.2",47+ "parseurl": "~1.3.3",48 "path-is-absolute": "1.0.1",49- "proxy-addr": "~2.0.4",50- "qs": "6.5.2",51- "range-parser": "~1.2.0",49+ "proxy-addr": "~2.0.5",50+ "qs": "6.7.0",51+ "range-parser": "~1.2.1",52 "router": "2.0.0-alpha.1",53 "safe-buffer": "5.1.2",54- "send": "0.16.2",55- "serve-static": "1.13.2",56- "setprototypeof": "1.1.0",57- "statuses": "~1.4.0",58- "type-is": "~1.6.16",54+ "send": "0.17.1",55+ "serve-static": "1.14.1",56+ "setprototypeof": "1.1.1",57+ "statuses": "~1.5.0",58+ "type-is": "~1.6.18",59 "utils-merge": "1.0.1",60 "vary": "~1.1.2"61 },62 "devDependencies": {63 "after": "0.8.2",64- "connect-redis": "3.4.0",65- "cookie-parser": "~1.4.3",66- "cookie-session": "1.3.2",64+ "connect-redis": "3.4.1",65+ "cookie-parser": "~1.4.4",66+ "cookie-session": "1.3.3",67 "ejs": "2.6.1",68 "eslint": "2.13.1",69- "express-session": "1.15.6",70- "hbs": "4.0.1",69+ "express-session": "1.16.1",70+ "hbs": "4.0.4",71 "istanbul": "0.4.5",72- "marked": "0.5.1",72+ "marked": "0.6.2",73 "method-override": "3.0.0",74 "mocha": "5.2.0",75 "morgan": "1.9.1",76 "multiparty": "4.2.1",23 unmodified linesmodified:Readme.md+8 added-6 removed
7 unmodified lines8 [![Windows Build][appveyor-image]][appveyor-url]9 [![Test Coverage][coveralls-image]][coveralls-url]10 11 ```js12-var express = require('express')13-var app = express()12+const express = require('express')13+const app = express()14 15 app.get('/', function (req, res) {16 res.send('Hello World')17 })71 unmodified lines89 ```bash90 $ npm start91 ```92 93+ View the website at: http://localhost:300094+95 ## Philosophy96 97 The Express philosophy is to provide small, robust tooling for HTTP servers, making98 it a great solution for single page applications, web sites, hybrids, or public27 unmodified lines126 $ npm install127 $ npm test128 ```129 130+## Contributing131+132+[Contributing Guide](Contributing.md)133+134 ## People135 136 The original author of Express is [TJ Holowaychuk](https://github.com/tj)137 14 unmodified lines152 [appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/express/master.svg?label=windows153 [appveyor-url]: https://ci.appveyor.com/project/dougwilson/express154 [coveralls-image]: https://img.shields.io/coveralls/expressjs/express/master.svg155 [coveralls-url]: https://coveralls.io/r/expressjs/express?branch=master150-[gratipay-image-visionmedia]: https://img.shields.io/gratipay/visionmedia.svg151-[gratipay-url-visionmedia]: https://gratipay.com/visionmedia/152-[gratipay-image-dougwilson]: https://img.shields.io/gratipay/dougwilson.svg153-[gratipay-url-dougwilson]: https://gratipay.com/dougwilson/