Skip to content
Myr

Merge tag '4.19.0' into 5.x

Before adoption: this commit came in with the history the project adopted, so no landing records it.

4.19.0

authored by Wes Todd · committed by Wes Todd · parents 318fd4b, 084e365 · Browse files · 53 files+2818 added−769 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

53 files+2818 added−769 removed

  • tests:+2343 added−547 removed
  • other:+475 added−222 removed

53 files+2818 added−769 removed

modified:.github/workflows/ci.yml+74 added-17 removed
modified:benchmarks/Makefile+12 added-8 removed
12all:3 @./run 1 middleware4 @./run 5 middleware5 @./run 10 middleware6 @./run 15 middleware7 @./run 20 middleware8 @./run 30 middleware9 @./run 50 middleware10 @./run 100 middleware3 @./run 1 middleware 504 @./run 5 middleware 505 @./run 10 middleware 506 @./run 15 middleware 507 @./run 20 middleware 508 @./run 30 middleware 509 @./run 50 middleware 5010 @./run 100 middleware 5011 @./run 10 middleware 10012 @./run 10 middleware 25013 @./run 10 middleware 50014 @./run 10 middleware 100015 @echo1617.PHONY: all
modified:benchmarks/middleware.js+1 added-1 removed
added:benchmarks/README.md+34 added
1# Express Benchmarks23## Installation45You will need to install [wrk](https://github.com/wg/wrk/blob/master/INSTALL) in order to run the benchmarks.67## Running89To run the benchmarks, first install the dependencies `npm i`, then run `make`1011The output will look something like this:1213```14 50 connections15 1 middleware16 7.15ms17 6784.011819 [...redacted...]2021 1000 connections22 10 middleware23 139.21ms24 6155.192526```2728### Tip: Include Node.js version in output2930You can use `make && node -v` to include the node.js version in the output.3132### Tip: Save the results to a file3334You can use `make > results.log` to save the results to a file `results.log`.
modified:benchmarks/run+5 added-3 removed
2 unmodified lines
3echo4MW=$1 node $2 &5pid=$!67echo " $3 connections"89sleep 21011wrk 'http://localhost:3333/?foo[bar]=baz' \12 -d 3 \11 -c 50 \13 -c $3 \14 -t 8 \13 | grep 'Requests/sec' \14 | awk '{ print " " $2 }'15 | grep 'Requests/sec\|Latency' \16 | awk '{ print " " $2 }'1718kill $pid
modified:examples/auth/views/login.ejs+4 added-4 removed
4 unmodified lines
5<%- message %>6Try accessing <a href="/restricted">/restricted</a>, then authenticate with "tj" and "foobar".7<form method="post" action="/login">8 <p>9 <label>Username:</label>10 <input type="text" name="username">9 <label for="username">Username:</label>10 <input type="text" name="username" id="username">11 </p>12 <p>13 <label>Password:</label>14 <input type="text" name="password">13 <label for="password">Password:</label>14 <input type="text" name="password" id="password">15 </p>16 <p>17 <input type="submit" value="Login">18 </p>
3 unmodified lines
modified:examples/cookie-sessions/index.js+2 added-5 removed
11 unmodified lines
12// add req.session cookie support13app.use(cookieSession({ secret: 'manny is cool' }));1415// do something with the session16app.use(count);1718// custom middleware19function count(req, res) {16app.get('/', function (req, res) {17 req.session.count = (req.session.count || 0) + 118 res.send('viewed ' + req.session.count + ' times\n')22}19})2021/* istanbul ignore next */22if (!module.parent) {23 app.listen(3000);
2 unmodified lines
modified:examples/downloads/index.js+1 added-4 removed
4 unmodified lines
5 */67var express = require('../../');8var path = require('path');9var resolvePath = require('resolve-path')910var app = module.exports = express();1112// path to where the files are stored on disk
10 unmodified lines
2324// /files/* is accessed via req.params[0]25// but here we name it :file26app.get('/files/:file+', function (req, res, next) {28 var filePath = resolvePath(FILES_DIR, req.params.file)2930 res.download(filePath, function (err) {27 res.download(req.params.file, { root: FILES_DIR }, function (err) {28 if (!err) return; // file sent29 if (err.status !== 404) return next(err); // non-404 error30 // file for download not found31 res.statusCode = 404;
9 unmodified lines
modified:examples/error/index.js+1 added-1 removed
24 unmodified lines
25 res.status(500);26 res.send('Internal Server Error');27}2829app.get('/', function(req, res){29app.get('/', function () {30 // Caught and passed down to the errorHandler middleware31 throw new Error('something broke!');32});33
20 unmodified lines
modified:examples/markdown/index.js+1 added-1 removed
24 unmodified lines
25});2627app.set('views', path.join(__dirname, 'views'));2829// make it the default so we dont need .md29// make it the default, so we don't need .md30app.set('view engine', 'md');3132app.get('/', function(req, res){33 res.render('index', { title: 'Markdown Example' });
11 unmodified lines
deleted:examples/multipart/index.js-62 removed
1'use strict'23/**4 * Module dependencies.5 */67var express = require('../..');8var multiparty = require('multiparty');9var format = require('util').format;1011var app = module.exports = express();1213app.get('/', function(req, res){14 res.send('<form method="post" enctype="multipart/form-data">'15 + '<p>Title: <input type="text" name="title" /></p>'16 + '<p>Image: <input type="file" name="image" /></p>'17 + '<p><input type="submit" value="Upload" /></p>'18 + '</form>');19});2021app.post('/', function(req, res, next){22 // create a form to begin parsing23 var form = new multiparty.Form();24 var image;25 var title;2627 form.on('error', next);28 form.on('close', function(){29 res.send(format('\nuploaded %s (%d Kb) as %s'30 , image.filename31 , image.size / 1024 | 032 , title));33 });3435 // listen on field event for title36 form.on('field', function(name, val){37 if (name !== 'title') return;38 title = val;39 });4041 // listen on part event for image file42 form.on('part', function(part){43 if (!part.filename) return;44 if (part.name !== 'image') return part.resume();45 image = {};46 image.filename = part.filename;47 image.size = 0;48 part.on('data', function(buf){49 image.size += buf.length;50 });51 });525354 // parse the form55 form.parse(req);56});5758/* istanbul ignore next */59if (!module.parent) {60 app.listen(4000);61 console.log('Express started on port 4000');62}
modified:examples/params/index.js+3 added-10 removed
2 unmodified lines
3/**4 * Module dependencies.5 */67var createError = require('http-errors')8var express = require('../../');9var app = module.exports = express();1011// Faux database
5 unmodified lines
17 , { name: 'jane' }18 , { name: 'bandit' }19];2020// Create HTTP error2122function createError(status, message) {23 var err = new Error(message);24 err.status = status;25 return err;26}2721// Convert :to and :from to integers2223app.param(['to', 'from'], function(req, res, next, num, name){24 req.params[name] = parseInt(num, 10);
25 unmodified lines
50/**51 * GET :user.52 */5361app.get('/user/:user', function(req, res, next){54app.get('/user/:user', function (req, res) {55 res.send('user ' + req.user.name);56});5758/**59 * GET users :from - :to.60 */6169app.get('/users/:from-:to', function(req, res, next){62app.get('/users/:from-:to', function (req, res) {63 var from = req.params.from;64 var to = req.params.to;65 var names = users.map(function(user){ return user.name; });66 res.send('users ' + names.slice(from, to + 1).join(', '));
7 unmodified lines
modified:examples/route-separation/views/users/edit.ejs+1 added-1 removed
1 unmodified line
23<h1>Editing <%= user.name %></h1>45<div id="user">6 <form action="?_method=put", method="post">6 <form action="?_method=put" method="post">7 <p>8 Name:9 <input type="text" value="<%= user.name %>" name="user[name]" />10 </p>
13 unmodified lines
modified:examples/search/public/index.html+2 added-2 removed
2 unmodified lines
3<head>4 <meta charset="utf-8">5 <meta name="viewport" content="width=device-width,initial-scale=1">6 <title>Search example</title>7 <style type="text/css">7 <style>8 body {9 font: 14px "Helvetica Neue", Helvetica;10 padding: 50px;11 }
2 unmodified lines
14<body>15 <h2>Search</h2>16 <p>Try searching for "ferret" or "cat".</p>17 <input type="search" name="search" value="" />18 <pre />18 <pre></pre>19 <script src="/client.js" charset="utf-8"></script>20</body>21</html>
modified:examples/view-locals/index.js+2 added-2 removed
59 unmodified lines
60 next();61 })62}6364app.get('/middleware', count, users, function(req, res, next){64app.get('/middleware', count, users, function (req, res) {65 res.render('index', {66 title: 'Users',67 count: req.count,68 users: req.users.filter(ferrets)
29 unmodified lines
98 next();99 })100}101102app.get('/middleware-locals', count2, users2, function(req, res, next){102app.get('/middleware-locals', count2, users2, function (req, res) {103 // you can see now how we have much less104 // to pass to res.render(). If we have105 // several routes related to users this106 // can be a great productivity booster
49 unmodified lines
modified:examples/web-service/index.js+2 added-2 removed
70 unmodified lines
71// we now can assume the api key is valid,72// and simply expose the data7374// example: http://localhost:3000/api/users/?api-key=foo75app.get('/api/users', function(req, res, next){75app.get('/api/users', function (req, res) {76 res.send(users);77});7879// example: http://localhost:3000/api/repos/?api-key=foo80app.get('/api/repos', function(req, res, next){80app.get('/api/repos', function (req, res) {81 res.send(repos);82});8384// example: http://localhost:3000/api/user/tobi/repos/?api-key=foo
33 unmodified lines
modified:examples/README.md-1 removed
11 unmodified lines
12- [error](./error) - Working with error middleware13- [hello-world](./hello-world) - Simple request handler14- [markdown](./markdown) - Markdown as template engine15- [multi-router](./multi-router) - Working with multiple Express routers16- [multipart](./multipart) - Accepting multipart-encoded forms16- [mvc](./mvc) - MVC-style controllers17- [online](./online) - Tracking online user activity with `online` and `redis` packages18- [params](./params) - Working with route parameters19- [resource](./resource) - Multiple HTTP operations on the same resource
10 unmodified lines
modified:lib/application.js+18 added-1 removed
24 unmodified lines
25var merge = require('utils-merge');26var resolve = require('path').resolve;27var Router = require('router');28var setPrototypeOf = require('setprototypeof')2930/**31 * Module variables.32 * @private33 */3435var hasOwnProperty = Object.prototype.hasOwnProperty36var slice = Array.prototype.slice;3738/**39 * Application prototype.
312 unmodified lines
352353app.set = function set(setting, val) {354 if (arguments.length === 1) {355 // app.get(setting)349 return this.settings[setting];356 var settings = this.settings357358 while (settings && settings !== Object.prototype) {359 if (hasOwnProperty.call(settings, setting)) {360 return settings[setting]361 }362363 settings = Object.getPrototypeOf(settings)364 }365366 return undefined367 }368369 debug('set "%s" to %o', setting, val);370
277 unmodified lines
modified:lib/response.js+59 added-18 removed
12 unmodified lines
13 */1415var Buffer = require('safe-buffer').Buffer16var contentDisposition = require('content-disposition');17var createError = require('http-errors')18var deprecate = require('depd')('express');19var encodeUrl = require('encodeurl');20var escapeHtml = require('escape-html');21var http = require('http');22var onFinished = require('on-finished');
10 unmodified lines
33var send = require('send');34var extname = path.extname;35var resolve = path.resolve;36var vary = require('vary');37var urlParse = require('url').parse;3839/**40 * Response prototype.41 * @public
16 unmodified lines
58 * @public59 */6061res.status = function status(code) {62 if ((typeof code === 'string' || Math.floor(code) !== code) && code > 99 && code < 1000) {63 deprecate('res.status(' + JSON.stringify(code) + '): use res.status(' + Math.floor(code) + ') instead')64 }65 this.statusCode = code;66 return this;67};68
116 unmodified lines
185 this.removeHeader('Transfer-Encoding');186 chunk = '';187 }188189 // alter headers for 205190 if (this.statusCode === 205) {191 this.set('Content-Length', '0')192 this.removeHeader('Transfer-Encoding')193 chunk = ''194 }195196 if (req.method === 'HEAD') {197 // skip body for HEAD198 this.end();199 } else {
105 unmodified lines
305 * @public306 */307308res.sendStatus = function sendStatus(statusCode) {296 var body = statuses[statusCode] || String(statusCode)309 var body = statuses.message[statusCode] || String(statusCode)310311 this.statusCode = statusCode;312 this.type('txt');313
114 unmodified lines
428 done = options429 opts = null430 }431432 // support optional filename, where options may be in it's place433 if (typeof filename === 'object' &&434 (typeof options === 'function' || options === undefined)) {435 name = null436 opts = filename437 }438439 // set Content-Disposition when file is sent440 var headers = {441 'Content-Disposition': contentDisposition(name || path)442 };
13 unmodified lines
456 opts = Object.create(opts)457 opts.headers = headers458459 // Resolve the full path for sendFile440 var fullPath = resolve(path);460 var fullPath = !opts.root461 ? resolve(path)462 : path463464 // send file465 return this.sendFile(fullPath, opts, done)466};
86 unmodified lines
553res.format = function(obj){554 var req = this.req;555 var next = req.next;556535 var fn = obj.default;536 if (fn) delete obj.default;537 var keys = Object.keys(obj);557 var keys = Object.keys(obj)558 .filter(function (v) { return v !== 'default' })559560 var key = keys.length > 0561 ? req.accepts(keys)562 : false;
2 unmodified lines
565566 if (key) {567 this.set('Content-Type', normalizeType(key).value);568 obj[key](req, this, next);548 } else if (fn) {549 fn();569 } else if (obj.default) {570 obj.default(req, this, next)571 } else {551 var err = new Error('Not Acceptable');552 err.status = err.statusCode = 406;553 err.types = normalizeTypes(keys).map(function(o){ return o.value });554 next(err);572 next(createError(406, {573 types: normalizeTypes(keys).map(function (o) { return o.value })574 }))575 }576577 return this;578};
157 unmodified lines
736 if (signed) {737 val = 's:' + sign(val, secret);738 }739720 if ('maxAge' in opts) {721 opts.expires = new Date(Date.now() + opts.maxAge);722 opts.maxAge /= 1000;740 if (opts.maxAge != null) {741 var maxAge = opts.maxAge - 0742743 if (!isNaN(maxAge)) {744 opts.expires = new Date(Date.now() + maxAge)745 opts.maxAge = Math.floor(maxAge / 1000)746 }747 }748749 if (opts.path == null) {750 opts.path = '/';
28 unmodified lines
779 if (url === 'back') {780 loc = this.req.get('Referrer') || '/';781 }782783 var lowerLoc = loc.toLowerCase();784 var encodedUrl = encodeUrl(loc);785 if (lowerLoc.indexOf('https://') === 0 || lowerLoc.indexOf('http://') === 0) {786 try {787 var parsedUrl = urlParse(loc);788 var parsedEncodedUrl = urlParse(encodedUrl);789 // Because this can encode the host, check that we did not change the host790 if (parsedUrl.host !== parsedEncodedUrl.host) {791 // If the host changes after encodeUrl, return the original url792 return this.set('Location', loc);793 }794 } catch (e) {795 // If parse fails, return the original url796 return this.set('Location', loc);797 }798 }799800 // set location760 return this.set('Location', encodeUrl(loc));801 return this.set('Location', encodedUrl);802};803804/**805 * Redirect to the given `url` with optional response `status`
29 unmodified lines
835836 // Support text/{plain,html} by default837 this.format({838 text: function(){798 body = statuses[status] + '. Redirecting to ' + address839 body = statuses.message[status] + '. Redirecting to ' + address840 },841842 html: function(){843 var u = escapeHtml(address);803 body = '<p>' + statuses[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'844 body = '<p>' + statuses.message[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'845 },846847 default: function(){848 body = '';
160 unmodified lines
1009 * Stringify JSON, like JSON.stringify, but v8 optimized, with the1010 * ability to escape characters that can trigger HTML sniffing.1011 *1012 * @param {*} value972 * @param {function} replaces1013 * @param {function} replacer1014 * @param {number} spaces1015 * @param {boolean} escape1016 * @returns {string}1017 * @private
27 unmodified lines
modified:lib/utils.js+3 added-3 removed
75 unmodified lines
7677/**78 * Parse accept params `str` returning an79 * object with `.value`, `.quality` and `.params`.80 * also includes `.originalIndex` for stable sorting80 *81 * @param {String} str82 * @return {Object}83 * @api private84 */8587function acceptParams(str, index) {86function acceptParams (str) {87 var parts = str.split(/ *; */);89 var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index };88 var ret = { value: parts[0], quality: 1, params: {} }8990 for (var i = 1; i < parts.length; ++i) {91 var pms = parts[i].split(/ *= */);92 if ('q' === pms[0]) {
145 unmodified lines
238239/**240 * Parse an extended query string with qs.241 *242 * @param {String} str243 * @return {Object}244 * @private245 */246
5 unmodified lines
modified:lib/view.js+1 added-1 removed
72 unmodified lines
73 }7475 if (!opts.engines[this.ext]) {76 // load engine77 var mod = this.ext.substr(1)77 var mod = this.ext.slice(1)78 debug('require "%s"', mod)7980 // default engine export81 var fn = require(mod).__express
124 unmodified lines
modified:test/support/utils.js+14 added
11 unmodified lines
12 * @public13 */1415exports.shouldHaveBody = shouldHaveBody16exports.shouldHaveHeader = shouldHaveHeader17exports.shouldNotHaveBody = shouldNotHaveBody18exports.shouldNotHaveHeader = shouldNotHaveHeader;1920/**
13 unmodified lines
34 }35}3637/**38 * Assert that a supertest response does have a header.39 *40 * @param {string} header Header name to check41 * @returns {function}42 */4344function shouldHaveHeader (header) {45 return function (res) {46 assert.ok((header.toLowerCase() in res.headers), 'should have header ' + header)47 }48}4950/**51 * Assert that a supertest response does not have a body.52 *53 * @returns {function}54 */
18 unmodified lines
modified:test/app.listen.js+2 added-3 removed
4 unmodified lines
5describe('app.listen()', function(){6 it('should wrap with an HTTP server', function(done){7 var app = express();89 var server = app.listen(9999, function(){10 server.close();11 done();9 var server = app.listen(0, function () {10 server.close(done)11 });12 })13})
modified:test/app.locals.js+14 added-18 removed
1'use strict'23var assert = require('assert')4var express = require('../')5var should = require('should')56describe('app', function(){8 describe('.locals(obj)', function(){9 it('should merge locals', function(){10 var app = express();11 should(Object.keys(app.locals)).eql(['settings'])12 app.locals.user = 'tobi';13 app.locals.age = 2;14 should(Object.keys(app.locals)).eql(['settings', 'user', 'age'])15 assert.strictEqual(app.locals.user, 'tobi')16 assert.strictEqual(app.locals.age, 2)7 describe('.locals', function () {8 it('should default object', function () {9 var app = express()10 assert.ok(app.locals)11 assert.strictEqual(typeof app.locals, 'object')12 })18 })1320 describe('.locals.settings', function(){21 it('should expose app settings', function(){22 var app = express();23 app.set('title', 'House of Manny');24 var obj = app.locals.settings;25 should(obj).have.property('env', 'test')26 should(obj).have.property('title', 'House of Manny')14 describe('.settings', function () {15 it('should contain app settings ', function () {16 var app = express()17 app.set('title', 'Express')18 assert.ok(app.locals.settings)19 assert.strictEqual(typeof app.locals.settings, 'object')20 assert.strictEqual(app.locals.settings, app.settings)21 assert.strictEqual(app.locals.settings.title, 'Express')22 })23 })24 })25})
modified:test/app.param.js+3 added-3 removed
122 unmodified lines
123124 app.get('/:user', function(req, res, next) {125 next('route');126 });127 app.get('/:user', function(req, res, next) {127 app.get('/:user', function (req, res) {128 res.send(req.params.user);129 });130131 request(app)
12 unmodified lines
144 app.param('user', function(req, res, next, user) {145 next(new Error('invalid invocation'))146 });147148 app.post('/:user', function(req, res, next) {148 app.post('/:user', function (req, res) {149 res.send(req.params.user);150 });151152 app.get('/:thing', function(req, res, next) {152 app.get('/:thing', function (req, res) {153 res.send(req.thing);154 });155156 request(app)
167 unmodified lines
modified:test/app.router.js+12 added-12 removed
90 unmodified lines
91 describe('decode params', function () {92 it('should decode correct params', function(done){93 var app = express();9495 app.get('/:name', function(req, res, next){95 app.get('/:name', function (req, res) {96 res.send(req.params.name);97 });9899 request(app)
3 unmodified lines
103104 it('should not accept params in malformed paths', function(done) {105 var app = express();106107 app.get('/:name', function(req, res, next){107 app.get('/:name', function (req, res) {108 res.send(req.params.name);109 });110111 request(app)
3 unmodified lines
115116 it('should not decode spaces', function(done) {117 var app = express();118119 app.get('/:name', function(req, res, next){119 app.get('/:name', function (req, res) {120 res.send(req.params.name);121 });122123 request(app)
3 unmodified lines
127128 it('should work with unicode', function(done) {129 var app = express();130131 app.get('/:name', function(req, res, next){131 app.get('/:name', function (req, res) {132 res.send(req.params.name);133 });134135 request(app)
654 unmodified lines
790 .expect(200, 'foo as html', cb)791792 request(app)793 .get('/foo.json')794 .expect(200, 'foo as json', done)794 .expect(200, 'foo as json', cb)795 })796 })797798 describe('when next() is called', function(){
5 unmodified lines
804 calls.push('/foo/:bar?');805 next();806 });807808 app.get('/bar', function(req, res){808 app.get('/bar', function () {809 assert(0);810 });811812 app.get('/foo', function(req, res, next){813 calls.push('/foo');814 next();815 });816817 app.get('/foo', function(req, res, next){817 app.get('/foo', function (req, res) {818 calls.push('/foo 2');819 res.json(calls)820 });821
11 unmodified lines
833 res.set('X-Hit', '1')834 next('route')835 }836837 app.get('/foo', fn, function(req, res, next){837 app.get('/foo', fn, function (req, res) {838 res.end('failure')839 });840841 app.get('/foo', function(req, res){
16 unmodified lines
858 res.set('X-Hit', '1')859 next('router')860 }861862 router.get('/foo', fn, function (req, res, next) {862 router.get('/foo', fn, function (req, res) {863 res.end('failure')864 })865866 router.get('/foo', function (req, res, next) {866 router.get('/foo', function (req, res) {867 res.end('failure')868 })869870 app.use(router)
18 unmodified lines
889 calls.push('/foo/:bar?');890 next();891 });892893 app.get('/bar', function(req, res){893 app.get('/bar', function () {894 assert(0);895 });896897 app.get('/foo', function(req, res, next){898 calls.push('/foo');899 next(new Error('fail'));900 });901902 app.get('/foo', function(req, res, next){902 app.get('/foo', function () {903 assert(0);904 });905906 app.use(function(err, req, res, next){
232 unmodified lines
modified:test/app.use.js+1 added-1 removed
55 unmodified lines
56 .expect(200, 'blog', cb)5758 request(app)59 .get('/forum')60 .expect(200, 'forum', done)60 .expect(200, 'forum', cb)61 })6263 it('should set the child\'s .parent', function(){64 var blog = express()
478 unmodified lines
modified:test/config.js+44 added
9 unmodified lines
10 app.set('foo', 'bar');11 assert.equal(app.get('foo'), 'bar');12 })1314 it('should set prototype values', function () {15 var app = express()16 app.set('hasOwnProperty', 42)17 assert.strictEqual(app.get('hasOwnProperty'), 42)18 })1920 it('should return the app', function () {21 var app = express();22 assert.equal(app.set('foo', 'bar'), app);23 })
2 unmodified lines
26 var app = express();27 assert.equal(app.set('foo', undefined), app);28 })2930 it('should return set value', function () {31 var app = express()32 app.set('foo', 'bar')33 assert.strictEqual(app.set('foo'), 'bar')34 })3536 it('should return undefined for prototype values', function () {37 var app = express()38 assert.strictEqual(app.set('hasOwnProperty'), undefined)39 })4041 describe('"etag"', function(){42 it('should throw on bad value', function(){43 var app = express();44 assert.throws(app.set.bind(app, 'etag', 42), /unknown value/);
22 unmodified lines
67 var app = express();68 assert.strictEqual(app.get('foo'), undefined);69 })7071 it('should return undefined for prototype values', function () {72 var app = express()73 assert.strictEqual(app.get('hasOwnProperty'), undefined)74 })7576 it('should otherwise return the value', function(){77 var app = express();78 app.set('foo', 'bar');79 assert.equal(app.get('foo'), 'bar');
66 unmodified lines
146 var app = express();147 assert.equal(app.enable('tobi'), app);148 assert.strictEqual(app.get('tobi'), true);149 })150151 it('should set prototype values', function () {152 var app = express()153 app.enable('hasOwnProperty')154 assert.strictEqual(app.get('hasOwnProperty'), true)155 })156 })157158 describe('.disable()', function(){159 it('should set the value to false', function(){160 var app = express();161 assert.equal(app.disable('tobi'), app);162 assert.strictEqual(app.get('tobi'), false);163 })164165 it('should set prototype values', function () {166 var app = express()167 app.disable('hasOwnProperty')168 assert.strictEqual(app.get('hasOwnProperty'), false)169 })170 })171172 describe('.enabled()', function(){173 it('should default to false', function(){
5 unmodified lines
179 var app = express();180 app.set('foo', 'bar');181 assert.strictEqual(app.enabled('foo'), true);182 })183184 it('should default to false for prototype values', function () {185 var app = express()186 assert.strictEqual(app.enabled('hasOwnProperty'), false)187 })188 })189190 describe('.disabled()', function(){191 it('should default to true', function(){
5 unmodified lines
197 var app = express();198 app.set('foo', 'bar');199 assert.strictEqual(app.disabled('foo'), false);200 })201202 it('should default to true for prototype values', function () {203 var app = express()204 assert.strictEqual(app.disabled('hasOwnProperty'), true)205 })206 })207})
modified:test/exports.js+8 added-5 removed
4 unmodified lines
5var request = require('supertest');67describe('exports', function(){8 it('should expose Router', function(){9 express.Router.should.be.a.Function()9 assert.strictEqual(typeof express.Router, 'function')10 })1112 it('should expose json middleware', function () {13 assert.equal(typeof express.json, 'function')
20 unmodified lines
34 assert.equal(express.urlencoded.length, 1)35 })3637 it('should expose the application prototype', function(){38 express.application.set.should.be.a.Function()38 assert.strictEqual(typeof express.application, 'object')39 assert.strictEqual(typeof express.application.set, 'function')40 })4142 it('should expose the request prototype', function(){42 express.request.accepts.should.be.a.Function()43 assert.strictEqual(typeof express.request, 'object')44 assert.strictEqual(typeof express.request.accepts, 'function')45 })4647 it('should expose the response prototype', function(){46 express.response.send.should.be.a.Function()48 assert.strictEqual(typeof express.response, 'object')49 assert.strictEqual(typeof express.response.send, 'function')50 })5152 it('should permit modifying the .application prototype', function(){53 express.application.foo = function(){ return 'bar'; };51 express().foo().should.equal('bar');54 assert.strictEqual(express().foo(), 'bar')55 })5657 it('should permit modifying the .request prototype', function(done){58 express.request.foo = function(){ return 'bar'; };
24 unmodified lines
modified:test/express.json.js+209 added-108 removed
1'use strict'23var assert = require('assert')4var asyncHooks = tryRequire('async_hooks')5var Buffer = require('safe-buffer').Buffer6var express = require('..')7var request = require('supertest')89var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function'10 ? describe11 : describe.skip1213describe('express.json()', function () {14 it('should parse JSON', function (done) {15 request(createApp())16 .post('/')
25 unmodified lines
42 .unset('Transfer-Encoding')43 .expect(200, '{}', done)44 })4546 // The old node error message modification in body parser is catching this47 it('should 400 when only whitespace', function (done) {48 request(createApp())49 .post('/')50 .set('Content-Type', 'application/json')51 .send(' \n')52 .expect(400, '[entity.parse.failed] ' + parseError(' \n'), done)53 })5455 it('should 400 when invalid content-length', function (done) {56 var app = express()5758 app.use(function (req, res, next) {
40 unmodified lines
99 request(this.app)100 .post('/')101 .set('Content-Type', 'application/json')102 .send('{:')89 .expect(400, parseError('{:'), done)103 .expect(400, '[entity.parse.failed] ' + parseError('{:'), done)104 })105106 it('should 400 for incomplete', function (done) {107 request(this.app)108 .post('/')109 .set('Content-Type', 'application/json')110 .send('{"user"')97 .expect(400, parseError('{"user"'), done)111 .expect(400, '[entity.parse.failed] ' + parseError('{"user"'), done)112 })113100 it('should error with type = "entity.parse.failed"', function (done) {101 request(this.app)102 .post('/')103 .set('Content-Type', 'application/json')104 .set('X-Error-Property', 'type')105 .send(' {"user"')106 .expect(400, 'entity.parse.failed', done)107 })108114 it('should include original body on error object', function (done) {115 request(this.app)116 .post('/')117 .set('Content-Type', 'application/json')
10 unmodified lines
128 .post('/')129 .set('Content-Type', 'application/json')130 .set('Content-Length', '1034')131 .send(JSON.stringify({ str: buf.toString() }))127 .expect(413, done)132 .expect(413, '[entity.too.large] request entity too large', done)133 })134130 it('should error with type = "entity.too.large"', function (done) {131 var buf = Buffer.alloc(1024, '.')132 request(createApp({ limit: '1kb' }))133 .post('/')134 .set('Content-Type', 'application/json')135 .set('Content-Length', '1034')136 .set('X-Error-Property', 'type')137 .send(JSON.stringify({ str: buf.toString() }))138 .expect(413, 'entity.too.large', done)139 })140135 it('should 413 when over limit with chunked encoding', function (done) {136 var app = createApp({ limit: '1kb' })137 var buf = Buffer.alloc(1024, '.')143 var server = createApp({ limit: '1kb' })144 var test = request(server).post('/')138 var test = request(app).post('/')139 test.set('Content-Type', 'application/json')140 test.set('Transfer-Encoding', 'chunked')141 test.write('{"str":')142 test.write('"' + buf.toString() + '"}')143 test.expect(413, done)144 })145146 it('should 413 when inflated body over limit', function (done) {147 var app = createApp({ limit: '1kb' })148 var test = request(app).post('/')149 test.set('Content-Encoding', 'gzip')150 test.set('Content-Type', 'application/json')151 test.write(Buffer.from('1f8b080000000000000aab562a2e2952b252d21b05a360148c58a0540b0066f7ce1e0a040000', 'hex'))152 test.expect(413, done)153 })154155 it('should accept number of bytes', function (done) {156 var buf = Buffer.alloc(1024, '.')157 request(createApp({ limit: 1024 }))158 .post('/')
4 unmodified lines
163164 it('should not change when options altered', function (done) {165 var buf = Buffer.alloc(1024, '.')166 var options = { limit: '1kb' }164 var server = createApp(options)167 var app = createApp(options)168169 options.limit = '100kb'170168 request(server)171 request(app)172 .post('/')173 .set('Content-Type', 'application/json')174 .send(JSON.stringify({ str: buf.toString() }))175 .expect(413, done)176 })177178 it('should not hang response', function (done) {179 var buf = Buffer.alloc(10240, '.')177 var server = createApp({ limit: '8kb' })178 var test = request(server).post('/')180 var app = createApp({ limit: '8kb' })181 var test = request(app).post('/')182 test.set('Content-Type', 'application/json')183 test.write(buf)184 test.write(buf)185 test.write(buf)186 test.expect(413, done)187 })188189 it('should not error when inflating', function (done) {190 var app = createApp({ limit: '1kb' })191 var test = request(app).post('/')192 test.set('Content-Encoding', 'gzip')193 test.set('Content-Type', 'application/json')194 test.write(Buffer.from('1f8b080000000000000aab562a2e2952b252d21b05a360148c58a0540b0066f7ce1e0a0400', 'hex'))195 test.expect(413, done)196 })197 })198199 describe('with inflate option', function () {200 describe('when false', function () {
5 unmodified lines
206 var test = request(this.app).post('/')207 test.set('Content-Encoding', 'gzip')208 test.set('Content-Type', 'application/json')209 test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))198 test.expect(415, 'content encoding unsupported', done)210 test.expect(415, '[encoding.unsupported] content encoding unsupported', done)211 })212 })213214 describe('when true', function () {
21 unmodified lines
236 request(this.app)237 .post('/')238 .set('Content-Type', 'application/json')239 .send('true')228 .expect(400, parseError('#rue').replace('#', 't'), done)240 .expect(400, '[entity.parse.failed] ' + parseError('#rue').replace(/#/g, 't'), done)241 })242 })243244 describe('when false', function () {
19 unmodified lines
264 request(this.app)265 .post('/')266 .set('Content-Type', 'application/json')267 .send('true')256 .expect(400, parseError('#rue').replace('#', 't'), done)268 .expect(400, '[entity.parse.failed] ' + parseError('#rue').replace(/#/g, 't'), done)269 })270271 it('should not parse primitives with leading whitespaces', function (done) {272 request(this.app)273 .post('/')274 .set('Content-Type', 'application/json')275 .send(' true')264 .expect(400, parseError(' #rue').replace('#', 't'), done)276 .expect(400, '[entity.parse.failed] ' + parseError(' #rue').replace(/#/g, 't'), done)277 })278279 it('should allow leading whitespaces in JSON', function (done) {280 request(this.app)
2 unmodified lines
283 .send(' { "user": "tobi" }')284 .expect(200, '{"user":"tobi"}', done)285 })286275 it('should error with type = "entity.parse.failed"', function (done) {276 request(this.app)277 .post('/')278 .set('Content-Type', 'application/json')279 .set('X-Error-Property', 'type')280 .send('true')281 .expect(400, 'entity.parse.failed', done)282 })283287 it('should include correct message in stack trace', function (done) {288 request(this.app)289 .post('/')290 .set('Content-Type', 'application/json')291 .set('X-Error-Property', 'stack')292 .send('true')293 .expect(400)291 .expect(shouldContainInBody(parseError('#rue').replace('#', 't')))294 .expect(shouldContainInBody(parseError('#rue').replace(/#/g, 't')))295 .end(done)296 })297 })298 })
100 unmodified lines
399 /TypeError: option verify must be function/)400 })401402 it('should error from verify', function (done) {403 var app = createApp({400 var app = createApp({ verify: function (req, res, buf) {401 if (buf[0] === 0x5b) throw new Error('no arrays')402 } })404 verify: function (req, res, buf) {405 if (buf[0] === 0x5b) throw new Error('no arrays')406 }407 })408409 request(app)410 .post('/')411 .set('Content-Type', 'application/json')412 .send('["tobi"]')408 .expect(403, 'no arrays', done)413 .expect(403, '[entity.verify.failed] no arrays', done)414 })415411 it('should error with type = "entity.verify.failed"', function (done) {412 var app = createApp({ verify: function (req, res, buf) {413 if (buf[0] === 0x5b) throw new Error('no arrays')414 } })415416 request(app)417 .post('/')418 .set('Content-Type', 'application/json')419 .set('X-Error-Property', 'type')420 .send('["tobi"]')421 .expect(403, 'entity.verify.failed', done)422 })423416 it('should allow custom codes', function (done) {417 var app = createApp({425 var app = createApp({ verify: function (req, res, buf) {426 if (buf[0] !== 0x5b) return427 var err = new Error('no arrays')428 err.status = 400429 throw err430 } })418 verify: function (req, res, buf) {419 if (buf[0] !== 0x5b) return420 var err = new Error('no arrays')421 err.status = 400422 throw err423 }424 })425426 request(app)427 .post('/')428 .set('Content-Type', 'application/json')429 .send('["tobi"]')436 .expect(400, 'no arrays', done)430 .expect(400, '[entity.verify.failed] no arrays', done)431 })432433 it('should allow custom type', function (done) {434 var app = createApp({440 var app = createApp({ verify: function (req, res, buf) {441 if (buf[0] !== 0x5b) return442 var err = new Error('no arrays')443 err.type = 'foo.bar'444 throw err445 } })435 verify: function (req, res, buf) {436 if (buf[0] !== 0x5b) return437 var err = new Error('no arrays')438 err.type = 'foo.bar'439 throw err440 }441 })442443 request(app)444 .post('/')445 .set('Content-Type', 'application/json')450 .set('X-Error-Property', 'type')446 .send('["tobi"]')452 .expect(403, 'foo.bar', done)447 .expect(403, '[foo.bar] no arrays', done)448 })449450 it('should include original body on error object', function (done) {451 var app = createApp({456 var app = createApp({ verify: function (req, res, buf) {457 if (buf[0] === 0x5b) throw new Error('no arrays')458 } })452 verify: function (req, res, buf) {453 if (buf[0] === 0x5b) throw new Error('no arrays')454 }455 })456457 request(app)458 .post('/')459 .set('Content-Type', 'application/json')
2 unmodified lines
462 .expect(403, '["tobi"]', done)463 })464465 it('should allow pass-through', function (done) {466 var app = createApp({469 var app = createApp({ verify: function (req, res, buf) {470 if (buf[0] === 0x5b) throw new Error('no arrays')471 } })467 verify: function (req, res, buf) {468 if (buf[0] === 0x5b) throw new Error('no arrays')469 }470 })471472 request(app)473 .post('/')474 .set('Content-Type', 'application/json')
1 unmodified line
476 .expect(200, '{"user":"tobi"}', done)477 })478479 it('should work with different charsets', function (done) {480 var app = createApp({481 var app = createApp({ verify: function (req, res, buf) {482 if (buf[0] === 0x5b) throw new Error('no arrays')483 } })481 verify: function (req, res, buf) {482 if (buf[0] === 0x5b) throw new Error('no arrays')483 }484 })485486 var test = request(app).post('/')487 test.set('Content-Type', 'application/json; charset=utf-16')488 test.write(Buffer.from('feff007b0022006e0061006d00650022003a00228bba0022007d', 'hex'))489 test.expect(200, '{"name":"论"}', done)490 })491492 it('should 415 on unknown charset prior to verify', function (done) {493 var app = createApp({492 var app = createApp({ verify: function (req, res, buf) {493 throw new Error('unexpected verify call')494 } })494 verify: function (req, res, buf) {495 throw new Error('unexpected verify call')496 }497 })498499 var test = request(app).post('/')500 test.set('Content-Type', 'application/json; charset=x-bogus')501 test.write(Buffer.from('00000000', 'hex'))499 test.expect(415, 'unsupported charset "X-BOGUS"', done)502 test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done)503 })504 })505506 describeAsyncHooks('async local storage', function () {507 before(function () {508 var app = express()509 var store = { foo: 'bar' }510511 app.use(function (req, res, next) {512 req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()513 req.asyncLocalStorage.run(store, next)514 })515516 app.use(express.json())517518 app.use(function (req, res, next) {519 var local = req.asyncLocalStorage.getStore()520521 if (local) {522 res.setHeader('x-store-foo', String(local.foo))523 }524525 next()526 })527528 app.use(function (err, req, res, next) {529 var local = req.asyncLocalStorage.getStore()530531 if (local) {532 res.setHeader('x-store-foo', String(local.foo))533 }534535 res.status(err.status || 500)536 res.send('[' + err.type + '] ' + err.message)537 })538539 app.post('/', function (req, res) {540 res.json(req.body)541 })542543 this.app = app544 })545546 it('should presist store', function (done) {547 request(this.app)548 .post('/')549 .set('Content-Type', 'application/json')550 .send('{"user":"tobi"}')551 .expect(200)552 .expect('x-store-foo', 'bar')553 .expect('{"user":"tobi"}')554 .end(done)555 })556557 it('should persist store when unmatched content-type', function (done) {558 request(this.app)559 .post('/')560 .set('Content-Type', 'application/fizzbuzz')561 .send('buzz')562 .expect(200)563 .expect('x-store-foo', 'bar')564 .expect('')565 .end(done)566 })567568 it('should presist store when inflated', function (done) {569 var test = request(this.app).post('/')570 test.set('Content-Encoding', 'gzip')571 test.set('Content-Type', 'application/json')572 test.write(Buffer.from('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))573 test.expect(200)574 test.expect('x-store-foo', 'bar')575 test.expect('{"name":"论"}')576 test.end(done)577 })578579 it('should presist store when inflate error', function (done) {580 var test = request(this.app).post('/')581 test.set('Content-Encoding', 'gzip')582 test.set('Content-Type', 'application/json')583 test.write(Buffer.from('1f8b080000000000000bab56cc4d55b2527ab16e97522d00515be1cc0e000000', 'hex'))584 test.expect(400)585 test.expect('x-store-foo', 'bar')586 test.end(done)587 })588589 it('should presist store when parse error', function (done) {590 request(this.app)591 .post('/')592 .set('Content-Type', 'application/json')593 .send('{"user":')594 .expect(400)595 .expect('x-store-foo', 'bar')596 .end(done)597 })598599 it('should presist store when limit exceeded', function (done) {600 request(this.app)601 .post('/')602 .set('Content-Type', 'application/json')603 .send('{"user":"' + Buffer.alloc(1024 * 100, '.').toString() + '"}')604 .expect(413)605 .expect('x-store-foo', 'bar')606 .end(done)607 })608 })609610 describe('charset', function () {611 before(function () {612 this.app = createApp()613 })
30 unmodified lines
644 it('should fail on unknown charset', function (done) {645 var test = request(this.app).post('/')646 test.set('Content-Type', 'application/json; charset=koi8-r')647 test.write(Buffer.from('7b226e616d65223a22cec5d4227d', 'hex'))541 test.expect(415, 'unsupported charset "KOI8-R"', done)648 test.expect(415, '[charset.unsupported] unsupported charset "KOI8-R"', done)649 })543544 it('should error with type = "charset.unsupported"', function (done) {545 var test = request(this.app).post('/')546 test.set('Content-Type', 'application/json; charset=koi8-r')547 test.set('X-Error-Property', 'type')548 test.write(Buffer.from('7b226e616d65223a22cec5d4227d', 'hex'))549 test.expect(415, 'charset.unsupported', done)550 })650 })651652 describe('encoding', function () {653 before(function () {
43 unmodified lines
697 var test = request(this.app).post('/')698 test.set('Content-Encoding', 'nulls')699 test.set('Content-Type', 'application/json')700 test.write(Buffer.from('000000000000', 'hex'))602 test.expect(415, 'unsupported content encoding "nulls"', done)701 test.expect(415, '[encoding.unsupported] unsupported content encoding "nulls"', done)702 })703605 it('should error with type = "encoding.unsupported"', function (done) {606 var test = request(this.app).post('/')607 test.set('Content-Encoding', 'nulls')608 test.set('Content-Type', 'application/json')609 test.set('X-Error-Property', 'type')610 test.write(Buffer.from('000000000000', 'hex'))611 test.expect(415, 'encoding.unsupported', done)612 })613704 it('should 400 on malformed encoding', function (done) {705 var test = request(this.app).post('/')706 test.set('Content-Encoding', 'gzip')707 test.set('Content-Type', 'application/json')
19 unmodified lines
727728 app.use(express.json(options))729730 app.use(function (err, req, res, next) {731 // console.log(err)732 res.status(err.status || 500)642 res.send(String(err[req.headers['x-error-property'] || 'message']))733 res.send(String(req.headers['x-error-property']734 ? err[req.headers['x-error-property']]735 : ('[' + err.type + '] ' + err.message)))736 })737738 app.post('/', function (req, res) {739 res.json(req.body)
15 unmodified lines
755 assert.ok(res.text.indexOf(str) !== -1,756 'expected \'' + res.text + '\' to contain \'' + str + '\'')757 }758}759760function tryRequire (name) {761 try {762 return require(name)763 } catch (e) {764 return {}765 }766}
modified:test/express.raw.js+154 added-18 removed
1'use strict'23var assert = require('assert')4var asyncHooks = tryRequire('async_hooks')5var Buffer = require('safe-buffer').Buffer6var express = require('..')7var request = require('supertest')89var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function'10 ? describe11 : describe.skip1213describe('express.raw()', function () {14 before(function () {15 this.app = createApp()16 })
89 unmodified lines
106 test.write(buf)107 test.expect(413, done)108 })109110 it('should 413 when inflated body over limit', function (done) {111 var app = createApp({ limit: '1kb' })112 var test = request(app).post('/')113 test.set('Content-Encoding', 'gzip')114 test.set('Content-Type', 'application/octet-stream')115 test.write(Buffer.from('1f8b080000000000000ad3d31b05a360148c64000087e5a14704040000', 'hex'))116 test.expect(413, done)117 })118119 it('should accept number of bytes', function (done) {120 var buf = Buffer.alloc(1028, '.')121 var app = createApp({ limit: 1024 })122 var test = request(app).post('/')
24 unmodified lines
147 test.write(buf)148 test.write(buf)149 test.expect(413, done)150 })151152 it('should not error when inflating', function (done) {153 var app = createApp({ limit: '1kb' })154 var test = request(app).post('/')155 test.set('Content-Encoding', 'gzip')156 test.set('Content-Type', 'application/octet-stream')157 test.write(Buffer.from('1f8b080000000000000ad3d31b05a360148c64000087e5a147040400', 'hex'))158 test.expect(413, done)159 })160 })161162 describe('with inflate option', function () {163 describe('when false', function () {
5 unmodified lines
169 var test = request(this.app).post('/')170 test.set('Content-Encoding', 'gzip')171 test.set('Content-Type', 'application/octet-stream')172 test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))150 test.expect(415, 'content encoding unsupported', done)173 test.expect(415, '[encoding.unsupported] content encoding unsupported', done)174 })175 })176177 describe('when true', function () {
107 unmodified lines
285 /TypeError: option verify must be function/)286 })287288 it('should error from verify', function (done) {289 var app = createApp({266 var app = createApp({ verify: function (req, res, buf) {267 if (buf[0] === 0x00) throw new Error('no leading null')268 } })290 verify: function (req, res, buf) {291 if (buf[0] === 0x00) throw new Error('no leading null')292 }293 })294295 var test = request(app).post('/')296 test.set('Content-Type', 'application/octet-stream')297 test.write(Buffer.from('000102', 'hex'))273 test.expect(403, 'no leading null', done)298 test.expect(403, '[entity.verify.failed] no leading null', done)299 })300301 it('should allow custom codes', function (done) {302 var app = createApp({277 var app = createApp({ verify: function (req, res, buf) {278 if (buf[0] !== 0x00) return279 var err = new Error('no leading null')280 err.status = 400281 throw err282 } })303 verify: function (req, res, buf) {304 if (buf[0] !== 0x00) return305 var err = new Error('no leading null')306 err.status = 400307 throw err308 }309 })310311 var test = request(app).post('/')312 test.set('Content-Type', 'application/octet-stream')313 test.write(Buffer.from('000102', 'hex'))287 test.expect(400, 'no leading null', done)314 test.expect(400, '[entity.verify.failed] no leading null', done)315 })316317 it('should allow pass-through', function (done) {318 var app = createApp({291 var app = createApp({ verify: function (req, res, buf) {292 if (buf[0] === 0x00) throw new Error('no leading null')293 } })319 verify: function (req, res, buf) {320 if (buf[0] === 0x00) throw new Error('no leading null')321 }322 })323324 var test = request(app).post('/')325 test.set('Content-Type', 'application/octet-stream')326 test.write(Buffer.from('0102', 'hex'))327 test.expect(200, { buf: '0102' }, done)328 })329 })330331 describeAsyncHooks('async local storage', function () {332 before(function () {333 var app = express()334 var store = { foo: 'bar' }335336 app.use(function (req, res, next) {337 req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()338 req.asyncLocalStorage.run(store, next)339 })340341 app.use(express.raw())342343 app.use(function (req, res, next) {344 var local = req.asyncLocalStorage.getStore()345346 if (local) {347 res.setHeader('x-store-foo', String(local.foo))348 }349350 next()351 })352353 app.use(function (err, req, res, next) {354 var local = req.asyncLocalStorage.getStore()355356 if (local) {357 res.setHeader('x-store-foo', String(local.foo))358 }359360 res.status(err.status || 500)361 res.send('[' + err.type + '] ' + err.message)362 })363364 app.post('/', function (req, res) {365 if (Buffer.isBuffer(req.body)) {366 res.json({ buf: req.body.toString('hex') })367 } else {368 res.json(req.body)369 }370 })371372 this.app = app373 })374375 it('should presist store', function (done) {376 request(this.app)377 .post('/')378 .set('Content-Type', 'application/octet-stream')379 .send('the user is tobi')380 .expect(200)381 .expect('x-store-foo', 'bar')382 .expect({ buf: '746865207573657220697320746f6269' })383 .end(done)384 })385386 it('should presist store when unmatched content-type', function (done) {387 request(this.app)388 .post('/')389 .set('Content-Type', 'application/fizzbuzz')390 .send('buzz')391 .expect(200)392 .expect('x-store-foo', 'bar')393 .end(done)394 })395396 it('should presist store when inflated', function (done) {397 var test = request(this.app).post('/')398 test.set('Content-Encoding', 'gzip')399 test.set('Content-Type', 'application/octet-stream')400 test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))401 test.expect(200)402 test.expect('x-store-foo', 'bar')403 test.expect({ buf: '6e616d653de8aeba' })404 test.end(done)405 })406407 it('should presist store when inflate error', function (done) {408 var test = request(this.app).post('/')409 test.set('Content-Encoding', 'gzip')410 test.set('Content-Type', 'application/octet-stream')411 test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad6080000', 'hex'))412 test.expect(400)413 test.expect('x-store-foo', 'bar')414 test.end(done)415 })416417 it('should presist store when limit exceeded', function (done) {418 request(this.app)419 .post('/')420 .set('Content-Type', 'application/octet-stream')421 .send('the user is ' + Buffer.alloc(1024 * 100, '.').toString())422 .expect(413)423 .expect('x-store-foo', 'bar')424 .end(done)425 })426 })427428 describe('charset', function () {429 before(function () {430 this.app = createApp()431 })
49 unmodified lines
481 test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))482 test.expect(200, { buf: '6e616d653de8aeba' }, done)483 })484359 it('should fail on unknown encoding', function (done) {485 it('should 415 on unknown encoding', function (done) {486 var test = request(this.app).post('/')487 test.set('Content-Encoding', 'nulls')488 test.set('Content-Type', 'application/octet-stream')489 test.write(Buffer.from('000000000000', 'hex'))364 test.expect(415, 'unsupported content encoding "nulls"', done)490 test.expect(415, '[encoding.unsupported] unsupported content encoding "nulls"', done)491 })492 })493})494
3 unmodified lines
498 app.use(express.raw(options))499500 app.use(function (err, req, res, next) {501 res.status(err.status || 500)376 res.send(String(err[req.headers['x-error-property'] || 'message']))502 res.send(String(req.headers['x-error-property']503 ? err[req.headers['x-error-property']]504 : ('[' + err.type + '] ' + err.message)))505 })506507 app.post('/', function (req, res) {508 if (Buffer.isBuffer(req.body)) {
4 unmodified lines
513 })514515 return app516}517518function tryRequire (name) {519 try {520 return require(name)521 } catch (e) {522 return {}523 }524}
modified:test/express.text.js+165 added-29 removed
1'use strict'23var assert = require('assert')4var asyncHooks = tryRequire('async_hooks')5var Buffer = require('safe-buffer').Buffer6var express = require('..')7var request = require('supertest')89var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function'10 ? describe11 : describe.skip1213describe('express.text()', function () {14 before(function () {15 this.app = createApp()16 })
62 unmodified lines
79 })8081 describe('with defaultCharset option', function () {82 it('should change default charset', function (done) {78 var app = createApp({ defaultCharset: 'koi8-r' })79 var test = request(app).post('/')83 var server = createApp({ defaultCharset: 'koi8-r' })84 var test = request(server).post('/')85 test.set('Content-Type', 'text/plain')86 test.write(Buffer.from('6e616d6520697320cec5d4', 'hex'))87 test.expect(200, '"name is нет"', done)88 })8990 it('should honor content-type charset', function (done) {86 var app = createApp({ defaultCharset: 'koi8-r' })87 var test = request(app).post('/')91 var server = createApp({ defaultCharset: 'koi8-r' })92 var test = request(server).post('/')93 test.set('Content-Type', 'text/plain; charset=utf-8')94 test.write(Buffer.from('6e616d6520697320e8aeba', 'hex'))95 test.expect(200, '"name is 论"', done)96 })
10 unmodified lines
107 .expect(413, done)108 })109110 it('should 413 when over limit with chunked encoding', function (done) {106 var buf = Buffer.alloc(1028, '.')111 var app = createApp({ limit: '1kb' })112 var buf = Buffer.alloc(1028, '.')113 var test = request(app).post('/')114 test.set('Content-Type', 'text/plain')115 test.set('Transfer-Encoding', 'chunked')116 test.write(buf.toString())117 test.expect(413, done)118 })119120 it('should 413 when inflated body over limit', function (done) {121 var app = createApp({ limit: '1kb' })122 var test = request(app).post('/')123 test.set('Content-Encoding', 'gzip')124 test.set('Content-Type', 'text/plain')125 test.write(Buffer.from('1f8b080000000000000ad3d31b05a360148c64000087e5a14704040000', 'hex'))126 test.expect(413, done)127 })128129 it('should accept number of bytes', function (done) {130 var buf = Buffer.alloc(1028, '.')131 request(createApp({ limit: 1024 }))132 .post('/')
16 unmodified lines
149 .expect(413, done)150 })151152 it('should not hang response', function (done) {139 var buf = Buffer.alloc(10240, '.')153 var app = createApp({ limit: '8kb' })154 var buf = Buffer.alloc(10240, '.')155 var test = request(app).post('/')156 test.set('Content-Type', 'text/plain')157 test.write(buf)158 test.write(buf)159 test.write(buf)160 test.expect(413, done)161 })162163 it('should not error when inflating', function (done) {164 var app = createApp({ limit: '1kb' })165 var test = request(app).post('/')166 test.set('Content-Encoding', 'gzip')167 test.set('Content-Type', 'text/plain')168 test.write(Buffer.from('1f8b080000000000000ad3d31b05a360148c64000087e5a1470404', 'hex'))169 setTimeout(function () {170 test.expect(413, done)171 }, 100)172 })173 })174175 describe('with inflate option', function () {176 describe('when false', function () {
5 unmodified lines
182 var test = request(this.app).post('/')183 test.set('Content-Encoding', 'gzip')184 test.set('Content-Type', 'text/plain')185 test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex'))161 test.expect(415, 'content encoding unsupported', done)186 test.expect(415, '[encoding.unsupported] content encoding unsupported', done)187 })188 })189190 describe('when true', function () {
111 unmodified lines
302 /TypeError: option verify must be function/)303 })304305 it('should error from verify', function (done) {306 var app = createApp({281 var app = createApp({ verify: function (req, res, buf) {282 if (buf[0] === 0x20) throw new Error('no leading space')283 } })307 verify: function (req, res, buf) {308 if (buf[0] === 0x20) throw new Error('no leading space')309 }310 })311312 request(app)313 .post('/')314 .set('Content-Type', 'text/plain')315 .send(' user is tobi')289 .expect(403, 'no leading space', done)316 .expect(403, '[entity.verify.failed] no leading space', done)317 })318319 it('should allow custom codes', function (done) {320 var app = createApp({293 var app = createApp({ verify: function (req, res, buf) {294 if (buf[0] !== 0x20) return295 var err = new Error('no leading space')296 err.status = 400297 throw err298 } })321 verify: function (req, res, buf) {322 if (buf[0] !== 0x20) return323 var err = new Error('no leading space')324 err.status = 400325 throw err326 }327 })328329 request(app)330 .post('/')331 .set('Content-Type', 'text/plain')332 .send(' user is tobi')304 .expect(400, 'no leading space', done)333 .expect(400, '[entity.verify.failed] no leading space', done)334 })335336 it('should allow pass-through', function (done) {337 var app = createApp({308 var app = createApp({ verify: function (req, res, buf) {309 if (buf[0] === 0x20) throw new Error('no leading space')310 } })338 verify: function (req, res, buf) {339 if (buf[0] === 0x20) throw new Error('no leading space')340 }341 })342343 request(app)344 .post('/')345 .set('Content-Type', 'text/plain')
1 unmodified line
347 .expect(200, '"user is tobi"', done)348 })349350 it('should 415 on unknown charset prior to verify', function (done) {351 var app = createApp({320 var app = createApp({ verify: function (req, res, buf) {321 throw new Error('unexpected verify call')322 } })352 verify: function (req, res, buf) {353 throw new Error('unexpected verify call')354 }355 })356357 var test = request(app).post('/')358 test.set('Content-Type', 'text/plain; charset=x-bogus')359 test.write(Buffer.from('00000000', 'hex'))327 test.expect(415, 'unsupported charset "X-BOGUS"', done)360 test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done)361 })362 })363364 describeAsyncHooks('async local storage', function () {365 before(function () {366 var app = express()367 var store = { foo: 'bar' }368369 app.use(function (req, res, next) {370 req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()371 req.asyncLocalStorage.run(store, next)372 })373374 app.use(express.text())375376 app.use(function (req, res, next) {377 var local = req.asyncLocalStorage.getStore()378379 if (local) {380 res.setHeader('x-store-foo', String(local.foo))381 }382383 next()384 })385386 app.use(function (err, req, res, next) {387 var local = req.asyncLocalStorage.getStore()388389 if (local) {390 res.setHeader('x-store-foo', String(local.foo))391 }392393 res.status(err.status || 500)394 res.send('[' + err.type + '] ' + err.message)395 })396397 app.post('/', function (req, res) {398 res.json(req.body)399 })400401 this.app = app402 })403404 it('should presist store', function (done) {405 request(this.app)406 .post('/')407 .set('Content-Type', 'text/plain')408 .send('user is tobi')409 .expect(200)410 .expect('x-store-foo', 'bar')411 .expect('"user is tobi"')412 .end(done)413 })414415 it('should presist store when unmatched content-type', function (done) {416 request(this.app)417 .post('/')418 .set('Content-Type', 'application/fizzbuzz')419 .send('buzz')420 .expect(200)421 .expect('x-store-foo', 'bar')422 .end(done)423 })424425 it('should presist store when inflated', function (done) {426 var test = request(this.app).post('/')427 test.set('Content-Encoding', 'gzip')428 test.set('Content-Type', 'text/plain')429 test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex'))430 test.expect(200)431 test.expect('x-store-foo', 'bar')432 test.expect('"name is 论"')433 test.end(done)434 })435436 it('should presist store when inflate error', function (done) {437 var test = request(this.app).post('/')438 test.set('Content-Encoding', 'gzip')439 test.set('Content-Type', 'text/plain')440 test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b0000', 'hex'))441 test.expect(400)442 test.expect('x-store-foo', 'bar')443 test.end(done)444 })445446 it('should presist store when limit exceeded', function (done) {447 request(this.app)448 .post('/')449 .set('Content-Type', 'text/plain')450 .send('user is ' + Buffer.alloc(1024 * 100, '.').toString())451 .expect(413)452 .expect('x-store-foo', 'bar')453 .end(done)454 })455 })456457 describe('charset', function () {458 before(function () {459 this.app = createApp()460 })
30 unmodified lines
491 it('should 415 on unknown charset', function (done) {492 var test = request(this.app).post('/')493 test.set('Content-Type', 'text/plain; charset=x-bogus')494 test.write(Buffer.from('00000000', 'hex'))369 test.expect(415, 'unsupported charset "X-BOGUS"', done)495 test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done)496 })497 })498499 describe('encoding', function () {
39 unmodified lines
539 test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex'))540 test.expect(200, '"name is 论"', done)541 })542417 it('should fail on unknown encoding', function (done) {543 it('should 415 on unknown encoding', function (done) {544 var test = request(this.app).post('/')545 test.set('Content-Encoding', 'nulls')546 test.set('Content-Type', 'text/plain')547 test.write(Buffer.from('000000000000', 'hex'))422 test.expect(415, 'unsupported content encoding "nulls"', done)548 test.expect(415, '[encoding.unsupported] unsupported content encoding "nulls"', done)549 })550 })551})552
3 unmodified lines
556 app.use(express.text(options))557558 app.use(function (err, req, res, next) {559 res.status(err.status || 500)434 res.send(err.message)560 res.send(String(req.headers['x-error-property']561 ? err[req.headers['x-error-property']]562 : ('[' + err.type + '] ' + err.message)))563 })564565 app.post('/', function (req, res) {566 res.json(req.body)567 })568569 return app570}571572function tryRequire (name) {573 try {574 return require(name)575 } catch (e) {576 return {}577 }578}
modified:test/express.urlencoded.js+170 added-66 removed
1'use strict'23var assert = require('assert')4var asyncHooks = tryRequire('async_hooks')5var Buffer = require('safe-buffer').Buffer6var express = require('..')7var request = require('supertest')89var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function'10 ? describe11 : describe.skip1213describe('express.urlencoded()', function () {14 before(function () {15 this.app = createApp()16 })
204 unmodified lines
221 var test = request(this.app).post('/')222 test.set('Content-Encoding', 'gzip')223 test.set('Content-Type', 'application/x-www-form-urlencoded')224 test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))220 test.expect(415, 'content encoding unsupported', done)225 test.expect(415, '[encoding.unsupported] content encoding unsupported', done)226 })227 })228229 describe('when true', function () {
22 unmodified lines
252 .expect(413, done)253 })254255 it('should 413 when over limit with chunked encoding', function (done) {251 var buf = Buffer.alloc(1024, '.')256 var app = createApp({ limit: '1kb' })257 var buf = Buffer.alloc(1024, '.')258 var test = request(app).post('/')259 test.set('Content-Type', 'application/x-www-form-urlencoded')260 test.set('Transfer-Encoding', 'chunked')261 test.write('str=')262 test.write(buf.toString())263 test.expect(413, done)264 })265266 it('should 413 when inflated body over limit', function (done) {267 var app = createApp({ limit: '1kb' })268 var test = request(app).post('/')269 test.set('Content-Encoding', 'gzip')270 test.set('Content-Type', 'application/x-www-form-urlencoded')271 test.write(Buffer.from('1f8b080000000000000a2b2e29b2d51b05a360148c580000a0351f9204040000', 'hex'))272 test.expect(413, done)273 })274275 it('should accept number of bytes', function (done) {276 var buf = Buffer.alloc(1024, '.')277 request(createApp({ limit: 1024 }))278 .post('/')
16 unmodified lines
295 .expect(413, done)296 })297298 it('should not hang response', function (done) {285 var buf = Buffer.alloc(10240, '.')299 var app = createApp({ limit: '8kb' })300 var buf = Buffer.alloc(10240, '.')301 var test = request(app).post('/')302 test.set('Content-Type', 'application/x-www-form-urlencoded')303 test.write(buf)304 test.write(buf)305 test.write(buf)306 test.expect(413, done)307 })308309 it('should not error when inflating', function (done) {310 var app = createApp({ limit: '1kb' })311 var test = request(app).post('/')312 test.set('Content-Encoding', 'gzip')313 test.set('Content-Type', 'application/x-www-form-urlencoded')314 test.write(Buffer.from('1f8b080000000000000a2b2e29b2d51b05a360148c580000a0351f92040400', 'hex'))315 test.expect(413, done)316 })317 })318319 describe('with parameterLimit option', function () {320 describe('with extended: false', function () {
11 unmodified lines
332 request(createApp({ extended: false, parameterLimit: 10 }))333 .post('/')334 .set('Content-Type', 'application/x-www-form-urlencoded')335 .send(createManyParams(11))313 .expect(413, /too many parameters/, done)336 .expect(413, '[parameters.too.many] too many parameters', done)337 })338316 it('should error with type = "parameters.too.many"', function (done) {317 request(createApp({ extended: false, parameterLimit: 10 }))318 .post('/')319 .set('Content-Type', 'application/x-www-form-urlencoded')320 .set('X-Error-Property', 'type')321 .send(createManyParams(11))322 .expect(413, 'parameters.too.many', done)323 })324339 it('should work when at the limit', function (done) {340 request(createApp({ extended: false, parameterLimit: 10 }))341 .post('/')342 .set('Content-Type', 'application/x-www-form-urlencoded')
44 unmodified lines
387 request(createApp({ extended: true, parameterLimit: 10 }))388 .post('/')389 .set('Content-Type', 'application/x-www-form-urlencoded')390 .send(createManyParams(11))377 .expect(413, /too many parameters/, done)391 .expect(413, '[parameters.too.many] too many parameters', done)392 })393380 it('should error with type = "parameters.too.many"', function (done) {381 request(createApp({ extended: true, parameterLimit: 10 }))382 .post('/')383 .set('Content-Type', 'application/x-www-form-urlencoded')384 .set('X-Error-Property', 'type')385 .send(createManyParams(11))386 .expect(413, 'parameters.too.many', done)387 })388394 it('should work when at the limit', function (done) {395 request(createApp({ extended: true, parameterLimit: 10 }))396 .post('/')397 .set('Content-Type', 'application/x-www-form-urlencoded')
132 unmodified lines
530 /TypeError: option verify must be function/)531 })532533 it('should error from verify', function (done) {534 var app = createApp({529 var app = createApp({ verify: function (req, res, buf) {530 if (buf[0] === 0x20) throw new Error('no leading space')531 } })535 verify: function (req, res, buf) {536 if (buf[0] === 0x20) throw new Error('no leading space')537 }538 })539540 request(app)541 .post('/')542 .set('Content-Type', 'application/x-www-form-urlencoded')543 .send(' user=tobi')537 .expect(403, 'no leading space', done)544 .expect(403, '[entity.verify.failed] no leading space', done)545 })546540 it('should error with type = "entity.verify.failed"', function (done) {541 var app = createApp({ verify: function (req, res, buf) {542 if (buf[0] === 0x20) throw new Error('no leading space')543 } })544545 request(app)546 .post('/')547 .set('Content-Type', 'application/x-www-form-urlencoded')548 .set('X-Error-Property', 'type')549 .send(' user=tobi')550 .expect(403, 'entity.verify.failed', done)551 })552547 it('should allow custom codes', function (done) {548 var app = createApp({554 var app = createApp({ verify: function (req, res, buf) {555 if (buf[0] !== 0x20) return556 var err = new Error('no leading space')557 err.status = 400558 throw err559 } })549 verify: function (req, res, buf) {550 if (buf[0] !== 0x20) return551 var err = new Error('no leading space')552 err.status = 400553 throw err554 }555 })556557 request(app)558 .post('/')559 .set('Content-Type', 'application/x-www-form-urlencoded')560 .send(' user=tobi')565 .expect(400, 'no leading space', done)561 .expect(400, '[entity.verify.failed] no leading space', done)562 })563564 it('should allow custom type', function (done) {565 var app = createApp({569 var app = createApp({ verify: function (req, res, buf) {570 if (buf[0] !== 0x20) return571 var err = new Error('no leading space')572 err.type = 'foo.bar'573 throw err574 } })566 verify: function (req, res, buf) {567 if (buf[0] !== 0x20) return568 var err = new Error('no leading space')569 err.type = 'foo.bar'570 throw err571 }572 })573574 request(app)575 .post('/')576 .set('Content-Type', 'application/x-www-form-urlencoded')579 .set('X-Error-Property', 'type')577 .send(' user=tobi')581 .expect(403, 'foo.bar', done)578 .expect(403, '[foo.bar] no leading space', done)579 })580581 it('should allow pass-through', function (done) {582 var app = createApp({585 var app = createApp({ verify: function (req, res, buf) {586 if (buf[0] === 0x5b) throw new Error('no arrays')587 } })583 verify: function (req, res, buf) {584 if (buf[0] === 0x5b) throw new Error('no arrays')585 }586 })587588 request(app)589 .post('/')590 .set('Content-Type', 'application/x-www-form-urlencoded')
1 unmodified line
592 .expect(200, '{"user":"tobi"}', done)593 })594595 it('should 415 on unknown charset prior to verify', function (done) {596 var app = createApp({597 var app = createApp({ verify: function (req, res, buf) {598 throw new Error('unexpected verify call')599 } })597 verify: function (req, res, buf) {598 throw new Error('unexpected verify call')599 }600 })601602 var test = request(app).post('/')603 test.set('Content-Type', 'application/x-www-form-urlencoded; charset=x-bogus')604 test.write(Buffer.from('00000000', 'hex'))604 test.expect(415, 'unsupported charset "X-BOGUS"', done)605 test.expect(415, '[charset.unsupported] unsupported charset "X-BOGUS"', done)606 })607 })608609 describeAsyncHooks('async local storage', function () {610 before(function () {611 var app = express()612 var store = { foo: 'bar' }613614 app.use(function (req, res, next) {615 req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()616 req.asyncLocalStorage.run(store, next)617 })618619 app.use(express.urlencoded())620621 app.use(function (req, res, next) {622 var local = req.asyncLocalStorage.getStore()623624 if (local) {625 res.setHeader('x-store-foo', String(local.foo))626 }627628 next()629 })630631 app.use(function (err, req, res, next) {632 var local = req.asyncLocalStorage.getStore()633634 if (local) {635 res.setHeader('x-store-foo', String(local.foo))636 }637638 res.status(err.status || 500)639 res.send('[' + err.type + '] ' + err.message)640 })641642 app.post('/', function (req, res) {643 res.json(req.body)644 })645646 this.app = app647 })648649 it('should presist store', function (done) {650 request(this.app)651 .post('/')652 .set('Content-Type', 'application/x-www-form-urlencoded')653 .send('user=tobi')654 .expect(200)655 .expect('x-store-foo', 'bar')656 .expect('{"user":"tobi"}')657 .end(done)658 })659660 it('should presist store when unmatched content-type', function (done) {661 request(this.app)662 .post('/')663 .set('Content-Type', 'application/fizzbuzz')664 .send('buzz')665 .expect(200)666 .expect('x-store-foo', 'bar')667 .end(done)668 })669670 it('should presist store when inflated', function (done) {671 var test = request(this.app).post('/')672 test.set('Content-Encoding', 'gzip')673 test.set('Content-Type', 'application/x-www-form-urlencoded')674 test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))675 test.expect(200)676 test.expect('x-store-foo', 'bar')677 test.expect('{"name":"论"}')678 test.end(done)679 })680681 it('should presist store when inflate error', function (done) {682 var test = request(this.app).post('/')683 test.set('Content-Encoding', 'gzip')684 test.set('Content-Type', 'application/x-www-form-urlencoded')685 test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad6080000', 'hex'))686 test.expect(400)687 test.expect('x-store-foo', 'bar')688 test.end(done)689 })690691 it('should presist store when limit exceeded', function (done) {692 request(this.app)693 .post('/')694 .set('Content-Type', 'application/x-www-form-urlencoded')695 .send('user=' + Buffer.alloc(1024 * 100, '.').toString())696 .expect(413)697 .expect('x-store-foo', 'bar')698 .end(done)699 })700 })701702 describe('charset', function () {703 before(function () {704 this.app = createApp()705 })
23 unmodified lines
729 it('should fail on unknown charset', function (done) {730 var test = request(this.app).post('/')731 test.set('Content-Type', 'application/x-www-form-urlencoded; charset=koi8-r')732 test.write(Buffer.from('6e616d653dcec5d4', 'hex'))639 test.expect(415, 'unsupported charset "KOI8-R"', done)733 test.expect(415, '[charset.unsupported] unsupported charset "KOI8-R"', done)734 })735 })736737 describe('encoding', function () {
39 unmodified lines
777 test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))778 test.expect(200, '{"name":"论"}', done)779 })780687 it('should fail on unknown encoding', function (done) {781 it('should 415 on unknown encoding', function (done) {782 var test = request(this.app).post('/')783 test.set('Content-Encoding', 'nulls')784 test.set('Content-Type', 'application/x-www-form-urlencoded')785 test.write(Buffer.from('000000000000', 'hex'))692 test.expect(415, 'unsupported content encoding "nulls"', done)786 test.expect(415, '[encoding.unsupported] unsupported content encoding "nulls"', done)787 })788 })789})790
20 unmodified lines
811 app.use(express.urlencoded(options))812813 app.use(function (err, req, res, next) {814 res.status(err.status || 500)721 res.send(String(err[req.headers['x-error-property'] || 'message']))815 res.send(String(req.headers['x-error-property']816 ? err[req.headers['x-error-property']]817 : ('[' + err.type + '] ' + err.message)))818 })819820 app.post('/', function (req, res) {821 res.json(req.body)
6 unmodified lines
828 return function (res) {829 assert.strictEqual(Object.keys(JSON.parse(res.text)).length, count)830 }831}832833function tryRequire (name) {834 try {835 return require(name)836 } catch (e) {837 return {}838 }839}
deleted:test/mocha.opts-2 removed
1--require should2--slow 20
modified:test/res.append.js+41 added-30 removed
1'use strict'23var assert = require('assert')4var express = require('..')5var request = require('supertest')5var should = require('should')67describe('res', function () {8 // note about these tests: "Link" and "X-*" are chosen because9 // the common node.js versions white list which _incoming_10 // headers can appear multiple times; there is no such white list11 // for outgoing, though8 describe('.append(field, val)', function () {9 it('should append multiple headers', function (done) {10 var app = express()1112 app.use(function (req, res, next) {17 res.append('Link', '<http://localhost/>')13 res.append('Set-Cookie', 'foo=bar')14 next()15 })1617 app.use(function (req, res) {22 res.append('Link', '<http://localhost:80/>')18 res.append('Set-Cookie', 'fizz=buzz')19 res.end()20 })2122 request(app)27 .get('/')28 .expect('Link', '<http://localhost/>, <http://localhost:80/>', done)23 .get('/')24 .expect(200)25 .expect(shouldHaveHeaderValues('Set-Cookie', ['foo=bar', 'fizz=buzz']))26 .end(done)27 })2829 it('should accept array of values', function (done) {30 var app = express()
3 unmodified lines
34 res.end()35 })3637 request(app)40 .get('/')41 .expect(function (res) {42 should(res.headers['set-cookie']).eql(['foo=bar', 'fizz=buzz'])43 })44 .expect(200, done)38 .get('/')39 .expect(200)40 .expect(shouldHaveHeaderValues('Set-Cookie', ['foo=bar', 'fizz=buzz']))41 .end(done)42 })4344 it('should get reset by res.set(field, val)', function (done) {45 var app = express()4647 app.use(function (req, res, next) {51 res.append('Link', '<http://localhost/>')52 res.append('Link', '<http://localhost:80/>')48 res.append('Set-Cookie', 'foo=bar')49 res.append('Set-Cookie', 'fizz=buzz')50 next()51 })5253 app.use(function (req, res) {57 res.set('Link', '<http://127.0.0.1/>')54 res.set('Set-Cookie', 'pet=tobi')55 res.end()56 });5758 request(app)62 .get('/')63 .expect('Link', '<http://127.0.0.1/>', done)59 .get('/')60 .expect(200)61 .expect(shouldHaveHeaderValues('Set-Cookie', ['pet=tobi']))62 .end(done)63 })6465 it('should work with res.set(field, val) first', function (done) {66 var app = express()6768 app.use(function (req, res, next) {70 res.set('Link', '<http://localhost/>')69 res.set('Set-Cookie', 'foo=bar')70 next()71 })7273 app.use(function(req, res){75 res.append('Link', '<http://localhost:80/>')74 res.append('Set-Cookie', 'fizz=buzz')75 res.end()76 })7778 request(app)80 .get('/')81 .expect('Link', '<http://localhost/>, <http://localhost:80/>', done)79 .get('/')80 .expect(200)81 .expect(shouldHaveHeaderValues('Set-Cookie', ['foo=bar', 'fizz=buzz']))82 .end(done)83 })8484 it('should work with cookies', function (done) {85 it('should work together with res.cookie', function (done) {86 var app = express()8788 app.use(function (req, res, next) {89 res.cookie('foo', 'bar')90 next()91 })9293 app.use(function (req, res) {93 res.append('Set-Cookie', 'bar=baz')94 res.append('Set-Cookie', 'fizz=buzz')95 res.end()96 })9798 request(app)98 .get('/')99 .expect(function (res) {100 should(res.headers['set-cookie']).eql(['foo=bar; Path=/', 'bar=baz'])101 })102 .expect(200, done)99 .get('/')100 .expect(200)101 .expect(shouldHaveHeaderValues('Set-Cookie', ['foo=bar; Path=/', 'fizz=buzz']))102 .end(done)103 })104 })105})106107function shouldHaveHeaderValues (key, values) {108 return function (res) {109 var headers = res.headers[key.toLowerCase()]110 assert.ok(headers, 'should have header "' + key + '"')111 assert.strictEqual(headers.length, values.length, 'should have ' + values.length + ' occurances of "' + key + '"')112 for (var i = 0; i < values.length; i++) {113 assert.strictEqual(headers[i], values[i])114 }115 }116}
modified:test/res.cookie.js+118 added
65 unmodified lines
66 .expect('Set-Cookie', 'name=tobi; Path=/; HttpOnly; Secure')67 .expect(200, done)68 })6970 describe('expires', function () {71 it('should throw on invalid date', function (done) {72 var app = express()7374 app.use(function (req, res) {75 res.cookie('name', 'tobi', { expires: new Date(NaN) })76 res.end()77 })7879 request(app)80 .get('/')81 .expect(500, /option expires is invalid/, done)82 })83 })8485 describe('partitioned', function () {86 it('should set partitioned', function (done) {87 var app = express();8889 app.use(function (req, res) {90 res.cookie('name', 'tobi', { partitioned: true });91 res.end();92 });9394 request(app)95 .get('/')96 .expect('Set-Cookie', 'name=tobi; Path=/; Partitioned')97 .expect(200, done)98 })99 })100101 describe('maxAge', function(){102 it('should set relative expires', function(done){103 var app = express();104
36 unmodified lines
141 .get('/')142 .expect(200, optionsCopy, done)143 })144145 it('should not throw on null', function (done) {146 var app = express()147148 app.use(function (req, res) {149 res.cookie('name', 'tobi', { maxAge: null })150 res.end()151 })152153 request(app)154 .get('/')155 .expect(200)156 .expect('Set-Cookie', 'name=tobi; Path=/')157 .end(done)158 })159160 it('should not throw on undefined', function (done) {161 var app = express()162163 app.use(function (req, res) {164 res.cookie('name', 'tobi', { maxAge: undefined })165 res.end()166 })167168 request(app)169 .get('/')170 .expect(200)171 .expect('Set-Cookie', 'name=tobi; Path=/')172 .end(done)173 })174175 it('should throw an error with invalid maxAge', function (done) {176 var app = express()177178 app.use(function (req, res) {
6 unmodified lines
185 .expect(500, /option maxAge is invalid/, done)186 })187 })188189 describe('priority', function () {190 it('should set low priority', function (done) {191 var app = express()192193 app.use(function (req, res) {194 res.cookie('name', 'tobi', { priority: 'low' })195 res.end()196 })197198 request(app)199 .get('/')200 .expect('Set-Cookie', /Priority=Low/)201 .expect(200, done)202 })203204 it('should set medium priority', function (done) {205 var app = express()206207 app.use(function (req, res) {208 res.cookie('name', 'tobi', { priority: 'medium' })209 res.end()210 })211212 request(app)213 .get('/')214 .expect('Set-Cookie', /Priority=Medium/)215 .expect(200, done)216 })217218 it('should set high priority', function (done) {219 var app = express()220221 app.use(function (req, res) {222 res.cookie('name', 'tobi', { priority: 'high' })223 res.end()224 })225226 request(app)227 .get('/')228 .expect('Set-Cookie', /Priority=High/)229 .expect(200, done)230 })231232 it('should throw with invalid priority', function (done) {233 var app = express()234235 app.use(function (req, res) {236 res.cookie('name', 'tobi', { priority: 'foobar' })237 res.end()238 })239240 request(app)241 .get('/')242 .expect(500, /option priority is invalid/, done)243 })244 })245246 describe('signed', function(){247 it('should generate a signed JSON cookie', function(done){248 var app = express();249
47 unmodified lines
modified:test/res.download.js+291 added-24 removed
1'use strict'23var after = require('after');4var assert = require('assert');4var assert = require('assert')5var asyncHooks = tryRequire('async_hooks')6var Buffer = require('safe-buffer').Buffer7var express = require('..');8var path = require('path')9var request = require('supertest');10var utils = require('./support/utils')1112var FIXTURES_PATH = path.join(__dirname, 'fixtures')1314var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function'15 ? describe16 : describe.skip1718describe('res', function(){19 describe('.download(path)', function(){20 it('should transfer as an attachment', function(done){21 var app = express();
67 unmodified lines
89 .expect('Content-Type', 'text/html; charset=utf-8')90 .expect('Content-Disposition', 'attachment; filename="user.html"')91 .expect(200, cb);92 })9394 describeAsyncHooks('async local storage', function () {95 it('should presist store', function (done) {96 var app = express()97 var cb = after(2, done)98 var store = { foo: 'bar' }99100 app.use(function (req, res, next) {101 req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()102 req.asyncLocalStorage.run(store, next)103 })104105 app.use(function (req, res) {106 res.download('test/fixtures/name.txt', function (err) {107 if (err) return cb(err)108109 var local = req.asyncLocalStorage.getStore()110111 assert.strictEqual(local.foo, 'bar')112 cb()113 })114 })115116 request(app)117 .get('/')118 .expect('Content-Type', 'text/plain; charset=utf-8')119 .expect('Content-Disposition', 'attachment; filename="name.txt"')120 .expect(200, 'tobi', cb)121 })122123 it('should presist store on error', function (done) {124 var app = express()125 var store = { foo: 'bar' }126127 app.use(function (req, res, next) {128 req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()129 req.asyncLocalStorage.run(store, next)130 })131132 app.use(function (req, res) {133 res.download('test/fixtures/does-not-exist', function (err) {134 var local = req.asyncLocalStorage.getStore()135136 if (local) {137 res.setHeader('x-store-foo', String(local.foo))138 }139140 res.send(err ? 'got ' + err.status + ' error' : 'no error')141 })142 })143144 request(app)145 .get('/')146 .expect(200)147 .expect('x-store-foo', 'bar')148 .expect('got 404 error')149 .end(done)150 })151 })152 })153154 describe('.download(path, options)', function () {155 it('should allow options to res.sendFile()', function (done) {156 var app = express()157158 app.use(function (req, res) {159 res.download('test/fixtures/.name', {160 dotfiles: 'allow',161 maxAge: '4h'162 })163 })164165 request(app)166 .get('/')167 .expect(200)168 .expect('Content-Disposition', 'attachment; filename=".name"')169 .expect('Cache-Control', 'public, max-age=14400')170 .expect(utils.shouldHaveBody(Buffer.from('tobi')))171 .end(done)172 })173174 describe('with "headers" option', function () {175 it('should set headers on response', function (done) {176 var app = express()177178 app.use(function (req, res) {179 res.download('test/fixtures/user.html', {180 headers: {181 'X-Foo': 'Bar',182 'X-Bar': 'Foo'183 }184 })185 })186187 request(app)188 .get('/')189 .expect(200)190 .expect('X-Foo', 'Bar')191 .expect('X-Bar', 'Foo')192 .end(done)193 })194195 it('should use last header when duplicated', function (done) {196 var app = express()197198 app.use(function (req, res) {199 res.download('test/fixtures/user.html', {200 headers: {201 'X-Foo': 'Bar',202 'x-foo': 'bar'203 }204 })205 })206207 request(app)208 .get('/')209 .expect(200)210 .expect('X-Foo', 'bar')211 .end(done)212 })213214 it('should override Content-Type', function (done) {215 var app = express()216217 app.use(function (req, res) {218 res.download('test/fixtures/user.html', {219 headers: {220 'Content-Type': 'text/x-custom'221 }222 })223 })224225 request(app)226 .get('/')227 .expect(200)228 .expect('Content-Type', 'text/x-custom')229 .end(done)230 })231232 it('should not set headers on 404', function (done) {233 var app = express()234235 app.use(function (req, res) {236 res.download('test/fixtures/does-not-exist', {237 headers: {238 'X-Foo': 'Bar'239 }240 })241 })242243 request(app)244 .get('/')245 .expect(404)246 .expect(utils.shouldNotHaveHeader('X-Foo'))247 .end(done)248 })249250 describe('when headers contains Content-Disposition', function () {251 it('should be ignored', function (done) {252 var app = express()253254 app.use(function (req, res) {255 res.download('test/fixtures/user.html', {256 headers: {257 'Content-Disposition': 'inline'258 }259 })260 })261262 request(app)263 .get('/')264 .expect(200)265 .expect('Content-Disposition', 'attachment; filename="user.html"')266 .end(done)267 })268269 it('should be ignored case-insensitively', function (done) {270 var app = express()271272 app.use(function (req, res) {273 res.download('test/fixtures/user.html', {274 headers: {275 'content-disposition': 'inline'276 }277 })278 })279280 request(app)281 .get('/')282 .expect(200)283 .expect('Content-Disposition', 'attachment; filename="user.html"')284 .end(done)285 })286 })287 })288289 describe('with "root" option', function () {290 it('should allow relative path', function (done) {291 var app = express()292293 app.use(function (req, res) {294 res.download('name.txt', {295 root: FIXTURES_PATH296 })297 })298299 request(app)300 .get('/')301 .expect(200)302 .expect('Content-Disposition', 'attachment; filename="name.txt"')303 .expect(utils.shouldHaveBody(Buffer.from('tobi')))304 .end(done)305 })306307 it('should allow up within root', function (done) {308 var app = express()309310 app.use(function (req, res) {311 res.download('fake/../name.txt', {312 root: FIXTURES_PATH313 })314 })315316 request(app)317 .get('/')318 .expect(200)319 .expect('Content-Disposition', 'attachment; filename="name.txt"')320 .expect(utils.shouldHaveBody(Buffer.from('tobi')))321 .end(done)322 })323324 it('should reject up outside root', function (done) {325 var app = express()326327 app.use(function (req, res) {328 var p = '..' + path.sep +329 path.relative(path.dirname(FIXTURES_PATH), path.join(FIXTURES_PATH, 'name.txt'))330331 res.download(p, {332 root: FIXTURES_PATH333 })334 })335336 request(app)337 .get('/')338 .expect(403)339 .expect(utils.shouldNotHaveHeader('Content-Disposition'))340 .end(done)341 })342343 it('should reject reading outside root', function (done) {344 var app = express()345346 app.use(function (req, res) {347 res.download('../name.txt', {348 root: FIXTURES_PATH349 })350 })351352 request(app)353 .get('/')354 .expect(403)355 .expect(utils.shouldNotHaveHeader('Content-Disposition'))356 .end(done)357 })358 })359 })360361 describe('.download(path, filename, fn)', function(){362 it('should invoke the callback', function(done){363 var app = express();364 var cb = after(2, done);
16 unmodified lines
381 var cb = after(2, done)382 var options = {}383384 app.use(function (req, res) {110 res.download('test/fixtures/user.html', 'document', options, done)385 res.download('test/fixtures/user.html', 'document', options, cb)386 })387388 request(app)389 .get('/')
13 unmodified lines
403 })404 })405406 request(app)132 .get('/')133 .expect(200)134 .expect('Content-Disposition', 'attachment; filename="document"')135 .expect('Cache-Control', 'public, max-age=14400')136 .expect(shouldHaveBody(Buffer.from('tobi')))137 .end(done)407 .get('/')408 .expect(200)409 .expect('Content-Disposition', 'attachment; filename="document"')410 .expect('Cache-Control', 'public, max-age=14400')411 .expect(utils.shouldHaveBody(Buffer.from('tobi')))412 .end(done)413 })414415 describe('when options.headers contains Content-Disposition', function () {416 it('should be ignored', function (done) {
64 unmodified lines
481 });482 });483484 request(app)210 .get('/')211 .expect(shouldNotHaveHeader('Content-Disposition'))212 .expect(200, 'failed', done);485 .get('/')486 .expect(utils.shouldNotHaveHeader('Content-Disposition'))487 .expect(200, 'failed', done)488 })489 })490})491217function shouldHaveBody (buf) {218 return function (res) {219 var body = !Buffer.isBuffer(res.body)220 ? Buffer.from(res.text)221 : res.body222 assert.ok(body, 'response has body')223 assert.strictEqual(body.toString('hex'), buf.toString('hex'))492function tryRequire (name) {493 try {494 return require(name)495 } catch (e) {496 return {}497 }498}226227function shouldNotHaveHeader(header) {228 return function (res) {229 assert.ok(!(header.toLowerCase() in res.headers), 'should not have header ' + header);230 };231}
modified:test/res.format.js+30 added-3 removed
50 unmodified lines
5152app3.use(function(req, res, next){53 res.format({54 text: function(){ res.send('hey') },55 default: function(){ res.send('default') }55 default: function (a, b, c) {56 assert(req === a)57 assert(res === b)58 assert(next === c)59 res.send('default')60 }61 })62});6364var app4 = express();6561app4.get('/', function(req, res, next){66app4.get('/', function (req, res) {67 res.format({68 text: function(){ res.send('hey') },69 html: function(){ res.send('<p>hey</p>') },70 json: function(){ res.send({ message: 'hey' }) }
55 unmodified lines
126 .get('/')127 .set('Accept', '*/*')128 .expect('hey', done);129 })130131 it('should be able to invoke other formatter', function (done) {132 var app = express()133134 app.use(function (req, res, next) {135 res.format({136 json: function () { res.send('json') },137 default: function () {138 res.header('x-default', '1')139 this.json()140 }141 })142 })143144 request(app)145 .get('/')146 .set('Accept', 'text/plain')147 .expect(200)148 .expect('x-default', '1')149 .expect('json')150 .end(done)151 })152 })153154 describe('in router', function(){155 test(app4);
2 unmodified lines
158 describe('in router', function(){159 var app = express();160 var router = express.Router();161135 router.get('/', function(req, res, next){162 router.get('/', function (req, res) {163 res.format({164 text: function(){ res.send('hey') },165 html: function(){ res.send('<p>hey</p>') },166 json: function(){ res.send({ message: 'hey' }) }
82 unmodified lines
modified:test/res.location.js+45 added-1 removed
1'use strict'23var express = require('../')4 , request = require('supertest');4 , request = require('supertest')5 , url = require('url');67describe('res', function(){8 describe('.location(url)', function(){9 it('should set the header', function(done){10 var app = express();1112 app.use(function(req, res){13 res.location('http://google.com/').end();14 });1516 request(app)17 .get('/')18 .expect('Location', 'http://google.com/')19 .expect(200, done)20 })2122 it('should preserve trailing slashes when not present', function(done){23 var app = express();2425 app.use(function(req, res){26 res.location('http://google.com').end();27 });2829 request(app)
14 unmodified lines
44 .expect('Location', 'https://google.com?q=%E2%98%83%20%C2%A710')45 .expect(200, done)46 })4748 it('should not encode bad "url"', function (done) {49 var app = express()5051 app.use(function (req, res) {52 // This is here to show a basic check one might do which53 // would pass but then the location header would still be bad54 if (url.parse(req.query.q).host !== 'google.com') {55 res.status(400).end('Bad url');56 }57 res.location(req.query.q).end();58 });5960 request(app)61 .get('/?q=http://google.com\\@apple.com')62 .expect(200)63 .expect('Location', 'http://google.com\\@apple.com')64 .end(function (err) {65 if (err) {66 throw err;67 }6869 // This ensures that our protocol check is case insensitive70 request(app)71 .get('/?q=HTTP://google.com\\@apple.com')72 .expect(200)73 .expect('Location', 'HTTP://google.com\\@apple.com')74 .end(done)75 });76 });7778 it('should not touch already-encoded sequences in "url"', function (done) {79 var app = express()8081 app.use(function (req, res) {
68 unmodified lines
modified:test/res.redirect.js+13 added-20 removed
1'use strict'23var assert = require('assert')3var express = require('..');4var request = require('supertest');5var utils = require('./support/utils');6
62 unmodified lines
69 res.redirect('http://google.com');70 });7172 request(app)74 .head('/')75 .expect(302)76 .expect('Location', 'http://google.com')77 .expect(shouldNotHaveBody())78 .end(done)73 .head('/')74 .expect(302)75 .expect('Location', 'http://google.com')76 .expect(utils.shouldNotHaveBody())77 .end(done)78 })79 })8081 describe('when accepting html', function(){
100 unmodified lines
182 res.redirect('http://google.com');183 });184185 request(app)187 .get('/')188 .set('Accept', 'application/octet-stream')189 .expect(302)190 .expect('location', 'http://google.com')191 .expect('content-length', '0')192 .expect(utils.shouldNotHaveHeader('Content-Type'))193 .expect(shouldNotHaveBody())194 .end(done)186 .get('/')187 .set('Accept', 'application/octet-stream')188 .expect(302)189 .expect('location', 'http://google.com')190 .expect('content-length', '0')191 .expect(utils.shouldNotHaveHeader('Content-Type'))192 .expect(utils.shouldNotHaveBody())193 .end(done)194 })195 })196})198199function shouldNotHaveBody () {200 return function (res) {201 assert.ok(res.text === '' || res.text === undefined)202 }203}
modified:test/res.send.js+25 added-25 removed
141 unmodified lines
142 res.send(Buffer.from('hello'))143 });144145 request(app)146 .get('/')147 .expect(200)148 .expect('Content-Type', 'application/octet-stream')149 .expect(shouldHaveBody(Buffer.from('hello')))150 .end(done)146 .get('/')147 .expect(200)148 .expect('Content-Type', 'application/octet-stream')149 .expect(utils.shouldHaveBody(Buffer.from('hello')))150 .end(done)151 })152153 it('should set ETag', function (done) {154 var app = express();
58 unmodified lines
213 res.send('yay');214 });215216 request(app)217 .head('/')218 .expect(200)219 .expect(shouldNotHaveBody())220 .end(done)217 .head('/')218 .expect(200)219 .expect(utils.shouldNotHaveBody())220 .end(done)221 })222 })223224 describe('when .statusCode is 204', function(){
12 unmodified lines
237 .expect(204, '', done);238 })239 })240241 describe('when .statusCode is 205', function () {242 it('should strip Transfer-Encoding field and body, set Content-Length', function (done) {243 var app = express()244245 app.use(function (req, res) {246 res.status(205).set('Transfer-Encoding', 'chunked').send('foo')247 })248249 request(app)250 .get('/')251 .expect(utils.shouldNotHaveHeader('Transfer-Encoding'))252 .expect('Content-Length', '0')253 .expect(205, '', done)254 })255 })256257 describe('when .statusCode is 304', function(){258 it('should strip Content-* fields, Transfer-Encoding field, and body', function(done){259 var app = express();260
287 unmodified lines
548 })549 })550 })551})536537function shouldHaveBody (buf) {538 return function (res) {539 var body = !Buffer.isBuffer(res.body)540 ? Buffer.from(res.text)541 : res.body542 assert.ok(body, 'response has body')543 assert.strictEqual(body.toString('hex'), buf.toString('hex'))544 }545}546547function shouldNotHaveBody () {548 return function (res) {549 assert.ok(res.text === '' || res.text === undefined)550 }551}
modified:test/res.sendFile.js+653 added-143 removed
1'use strict'23var after = require('after');4var assert = require('assert')5var asyncHooks = tryRequire('async_hooks')6var Buffer = require('safe-buffer').Buffer7var express = require('../')8 , request = require('supertest')9var onFinished = require('on-finished');10var path = require('path');10var should = require('should');11var fixtures = path.join(__dirname, 'fixtures');12var utils = require('./support/utils');1314var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function'15 ? describe16 : describe.skip1718describe('res', function(){19 describe('.sendFile(path)', function () {20 it('should error missing path', function (done) {21 var app = createApp();
10 unmodified lines
32 .get('/')33 .expect(500, /TypeError: path must be a string to res.sendFile/, done)34 })3536 it('should error for non-absolute path', function (done) {37 var app = createApp('name.txt')3839 request(app)40 .get('/')41 .expect(500, /TypeError: path must be absolute/, done)42 })4344 it('should transfer a file', function (done) {45 var app = createApp(path.resolve(fixtures, 'name.txt'));4647 request(app)
54 unmodified lines
102 .get('/')103 .expect(404, done);104 });105106 it('should send cache-control by default', function (done) {107 var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'))108109 request(app)110 .get('/')111 .expect('Cache-Control', 'public, max-age=0')112 .expect(200, done)113 })114115 it('should not serve dotfiles by default', function (done) {116 var app = createApp(path.resolve(__dirname, 'fixtures/.name'))117118 request(app)119 .get('/')120 .expect(404, done)121 })122123 it('should not override manual content-types', function (done) {124 var app = express();125126 app.use(function (req, res) {
33 unmodified lines
160 assert.ok(err)161 server.close(cb)162 })163 })135136 describe('with "cacheControl" option', function () {137 it('should enable cacheControl by default', function (done) {138 var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'))139140 request(app)141 .get('/')142 .expect('Cache-Control', 'public, max-age=0')143 .expect(200, done)144 })145146 it('should accept cacheControl option', function (done) {147 var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'), { cacheControl: false })148149 request(app)150 .get('/')151 .expect(utils.shouldNotHaveHeader('Cache-Control'))152 .expect(200, done)153 })154 })155156 describe('with "dotfiles" option', function () {157 it('should not serve dotfiles by default', function (done) {158 var app = createApp(path.resolve(__dirname, 'fixtures/.name'));159160 request(app)161 .get('/')162 .expect(404, done);163 });164165 it('should accept dotfiles option', function(done){166 var app = createApp(path.resolve(__dirname, 'fixtures/.name'), { dotfiles: 'allow' });167168 request(app)169 .get('/')170 .expect(200)171 .expect(shouldHaveBody(Buffer.from('tobi')))172 .end(done)173 });174 });175176 describe('with "headers" option', function () {177 it('should accept headers option', function (done) {178 var headers = {179 'x-success': 'sent',180 'x-other': 'done'181 };182 var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'), { headers: headers });183184 request(app)185 .get('/')186 .expect('x-success', 'sent')187 .expect('x-other', 'done')188 .expect(200, done);189 });190191 it('should ignore headers option on 404', function (done) {192 var headers = { 'x-success': 'sent' };193 var app = createApp(path.resolve(__dirname, 'fixtures/does-not-exist'), { headers: headers });194195 request(app)196 .get('/')197 .expect(utils.shouldNotHaveHeader('X-Success'))198 .expect(404, done);199 });200 });201202 describe('with "immutable" option', function () {203 it('should add immutable cache-control directive', function (done) {204 var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'), {205 immutable: true,206 maxAge: '4h'207 })208209 request(app)210 .get('/')211 .expect('Cache-Control', 'public, max-age=14400, immutable')212 .expect(200, done)213 })214 })215216 describe('with "maxAge" option', function () {217 it('should set cache-control max-age from number', function (done) {218 var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'), {219 maxAge: 14400000220 })221222 request(app)223 .get('/')224 .expect('Cache-Control', 'public, max-age=14400')225 .expect(200, done)226 })227228 it('should set cache-control max-age from string', function (done) {229 var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'), {230 maxAge: '4h'231 })232233 request(app)234 .get('/')235 .expect('Cache-Control', 'public, max-age=14400')236 .expect(200, done)237 })238 })239240 describe('with "root" option', function () {241 it('should not transfer relative with without', function (done) {242 var app = createApp('test/fixtures/name.txt');243244 request(app)245 .get('/')246 .expect(500, /must be absolute/, done);247 })248249 it('should serve relative to "root"', function (done) {250 var app = createApp('name.txt', {root: fixtures});251252 request(app)253 .get('/')254 .expect(200, 'tobi', done);255 })256257 it('should disallow requesting out of "root"', function (done) {258 var app = createApp('foo/../../user.html', {root: fixtures});259260 request(app)261 .get('/')262 .expect(403, done);263 })264 })164 })165166 describe('.sendFile(path, fn)', function () {167 it('should invoke the callback when complete', function (done) {
89 unmodified lines
257 var app = express();258259 app.use(function (req, res) {260 res.sendFile(path.resolve(fixtures, 'does-not-exist'), function (err) {362 should(err).be.ok()363 err.status.should.equal(404);364 res.send('got it');261 res.send(err ? 'got ' + err.status + ' error' : 'no error')262 });263 });264265 request(app)369 .get('/')370 .expect(200, 'got it', done);266 .get('/')267 .expect(200, 'got 404 error', done)268 })269270 describeAsyncHooks('async local storage', function () {271 it('should presist store', function (done) {272 var app = express()273 var cb = after(2, done)274 var store = { foo: 'bar' }275276 app.use(function (req, res, next) {277 req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()278 req.asyncLocalStorage.run(store, next)279 })280281 app.use(function (req, res) {282 res.sendFile(path.resolve(fixtures, 'name.txt'), function (err) {283 if (err) return cb(err)284285 var local = req.asyncLocalStorage.getStore()286287 assert.strictEqual(local.foo, 'bar')288 cb()289 })290 })291292 request(app)293 .get('/')294 .expect('Content-Type', 'text/plain; charset=utf-8')295 .expect(200, 'tobi', cb)296 })297298 it('should presist store on error', function (done) {299 var app = express()300 var store = { foo: 'bar' }301302 app.use(function (req, res, next) {303 req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()304 req.asyncLocalStorage.run(store, next)305 })306307 app.use(function (req, res) {308 res.sendFile(path.resolve(fixtures, 'does-not-exist'), function (err) {309 var local = req.asyncLocalStorage.getStore()310311 if (local) {312 res.setHeader('x-store-foo', String(local.foo))313 }314315 res.send(err ? 'got ' + err.status + ' error' : 'no error')316 })317 })318319 request(app)320 .get('/')321 .expect(200)322 .expect('x-store-foo', 'bar')323 .expect('got 404 error')324 .end(done)325 })326 })327 })328329 describe('.sendFile(path, options)', function () {330 it('should pass options to send module', function (done) {331 request(createApp(path.resolve(fixtures, 'name.txt'), { start: 0, end: 1 }))332 .get('/')333 .expect(200, 'to', done)334 })335336 describe('with "acceptRanges" option', function () {337 describe('when true', function () {338 it('should advertise byte range accepted', function (done) {339 var app = express()340341 app.use(function (req, res) {342 res.sendFile(path.resolve(fixtures, 'nums.txt'), {343 acceptRanges: true344 })345 })346347 request(app)348 .get('/')349 .expect(200)350 .expect('Accept-Ranges', 'bytes')351 .expect('123456789')352 .end(done)353 })354355 it('should respond to range request', function (done) {356 var app = express()357358 app.use(function (req, res) {359 res.sendFile(path.resolve(fixtures, 'nums.txt'), {360 acceptRanges: true361 })362 })363364 request(app)365 .get('/')366 .set('Range', 'bytes=0-4')367 .expect(206, '12345', done)368 })369 })370371 describe('when false', function () {372 it('should not advertise accept-ranges', function (done) {373 var app = express()374375 app.use(function (req, res) {376 res.sendFile(path.resolve(fixtures, 'nums.txt'), {377 acceptRanges: false378 })379 })380381 request(app)382 .get('/')383 .expect(200)384 .expect(utils.shouldNotHaveHeader('Accept-Ranges'))385 .end(done)386 })387388 it('should not honor range requests', function (done) {389 var app = express()390391 app.use(function (req, res) {392 res.sendFile(path.resolve(fixtures, 'nums.txt'), {393 acceptRanges: false394 })395 })396397 request(app)398 .get('/')399 .set('Range', 'bytes=0-4')400 .expect(200, '123456789', done)401 })402 })403 })404405 describe('with "cacheControl" option', function () {406 describe('when true', function () {407 it('should send cache-control header', function (done) {408 var app = express()409410 app.use(function (req, res) {411 res.sendFile(path.resolve(fixtures, 'user.html'), {412 cacheControl: true413 })414 })415416 request(app)417 .get('/')418 .expect(200)419 .expect('Cache-Control', 'public, max-age=0')420 .end(done)421 })422 })423424 describe('when false', function () {425 it('should not send cache-control header', function (done) {426 var app = express()427428 app.use(function (req, res) {429 res.sendFile(path.resolve(fixtures, 'user.html'), {430 cacheControl: false431 })432 })433434 request(app)435 .get('/')436 .expect(200)437 .expect(utils.shouldNotHaveHeader('Cache-Control'))438 .end(done)439 })440 })441 })442443 describe('with "dotfiles" option', function () {444 describe('when "allow"', function () {445 it('should allow dotfiles', function (done) {446 var app = express()447448 app.use(function (req, res) {449 res.sendFile(path.resolve(fixtures, '.name'), {450 dotfiles: 'allow'451 })452 })453454 request(app)455 .get('/')456 .expect(200)457 .expect(utils.shouldHaveBody(Buffer.from('tobi')))458 .end(done)459 })460 })461462 describe('when "deny"', function () {463 it('should deny dotfiles', function (done) {464 var app = express()465466 app.use(function (req, res) {467 res.sendFile(path.resolve(fixtures, '.name'), {468 dotfiles: 'deny'469 })470 })471472 request(app)473 .get('/')474 .expect(403)475 .expect(/Forbidden/)476 .end(done)477 })478 })479480 describe('when "ignore"', function () {481 it('should ignore dotfiles', function (done) {482 var app = express()483484 app.use(function (req, res) {485 res.sendFile(path.resolve(fixtures, '.name'), {486 dotfiles: 'ignore'487 })488 })489490 request(app)491 .get('/')492 .expect(404)493 .expect(/Not Found/)494 .end(done)495 })496 })497 })498499 describe('with "headers" option', function () {500 it('should set headers on response', function (done) {501 var app = express()502503 app.use(function (req, res) {504 res.sendFile(path.resolve(fixtures, 'user.html'), {505 headers: {506 'X-Foo': 'Bar',507 'X-Bar': 'Foo'508 }509 })510 })511512 request(app)513 .get('/')514 .expect(200)515 .expect('X-Foo', 'Bar')516 .expect('X-Bar', 'Foo')517 .end(done)518 })519520 it('should use last header when duplicated', function (done) {521 var app = express()522523 app.use(function (req, res) {524 res.sendFile(path.resolve(fixtures, 'user.html'), {525 headers: {526 'X-Foo': 'Bar',527 'x-foo': 'bar'528 }529 })530 })531532 request(app)533 .get('/')534 .expect(200)535 .expect('X-Foo', 'bar')536 .end(done)537 })538539 it('should override Content-Type', function (done) {540 var app = express()541542 app.use(function (req, res) {543 res.sendFile(path.resolve(fixtures, 'user.html'), {544 headers: {545 'Content-Type': 'text/x-custom'546 }547 })548 })549550 request(app)551 .get('/')552 .expect(200)553 .expect('Content-Type', 'text/x-custom')554 .end(done)555 })556557 it('should not set headers on 404', function (done) {558 var app = express()559560 app.use(function (req, res) {561 res.sendFile(path.resolve(fixtures, 'does-not-exist'), {562 headers: {563 'X-Foo': 'Bar'564 }565 })566 })567568 request(app)569 .get('/')570 .expect(404)571 .expect(utils.shouldNotHaveHeader('X-Foo'))572 .end(done)573 })574 })575576 describe('with "immutable" option', function () {577 describe('when true', function () {578 it('should send cache-control header with immutable', function (done) {579 var app = express()580581 app.use(function (req, res) {582 res.sendFile(path.resolve(fixtures, 'user.html'), {583 immutable: true584 })585 })586587 request(app)588 .get('/')589 .expect(200)590 .expect('Cache-Control', 'public, max-age=0, immutable')591 .end(done)592 })593 })594595 describe('when false', function () {596 it('should not send cache-control header with immutable', function (done) {597 var app = express()598599 app.use(function (req, res) {600 res.sendFile(path.resolve(fixtures, 'user.html'), {601 immutable: false602 })603 })604605 request(app)606 .get('/')607 .expect(200)608 .expect('Cache-Control', 'public, max-age=0')609 .end(done)610 })611 })612 })613614 describe('with "lastModified" option', function () {615 describe('when true', function () {616 it('should send last-modified header', function (done) {617 var app = express()618619 app.use(function (req, res) {620 res.sendFile(path.resolve(fixtures, 'user.html'), {621 lastModified: true622 })623 })624625 request(app)626 .get('/')627 .expect(200)628 .expect(utils.shouldHaveHeader('Last-Modified'))629 .end(done)630 })631632 it('should conditionally respond with if-modified-since', function (done) {633 var app = express()634635 app.use(function (req, res) {636 res.sendFile(path.resolve(fixtures, 'user.html'), {637 lastModified: true638 })639 })640641 request(app)642 .get('/')643 .set('If-Modified-Since', (new Date(Date.now() + 99999).toUTCString()))644 .expect(304, done)645 })646 })647648 describe('when false', function () {649 it('should not have last-modified header', function (done) {650 var app = express()651652 app.use(function (req, res) {653 res.sendFile(path.resolve(fixtures, 'user.html'), {654 lastModified: false655 })656 })657658 request(app)659 .get('/')660 .expect(200)661 .expect(utils.shouldNotHaveHeader('Last-Modified'))662 .end(done)663 })664665 it('should not honor if-modified-since', function (done) {666 var app = express()667668 app.use(function (req, res) {669 res.sendFile(path.resolve(fixtures, 'user.html'), {670 lastModified: false671 })672 })673674 request(app)675 .get('/')676 .set('If-Modified-Since', (new Date(Date.now() + 99999).toUTCString()))677 .expect(200)678 .expect(utils.shouldNotHaveHeader('Last-Modified'))679 .end(done)680 })681 })682 })683684 describe('with "maxAge" option', function () {685 it('should set cache-control max-age to milliseconds', function (done) {686 var app = express()687688 app.use(function (req, res) {689 res.sendFile(path.resolve(fixtures, 'user.html'), {690 maxAge: 20000691 })692 })693694 request(app)695 .get('/')696 .expect(200)697 .expect('Cache-Control', 'public, max-age=20')698 .end(done)699 })700701 it('should cap cache-control max-age to 1 year', function (done) {702 var app = express()703704 app.use(function (req, res) {705 res.sendFile(path.resolve(fixtures, 'user.html'), {706 maxAge: 99999999999707 })708 })709710 request(app)711 .get('/')712 .expect(200)713 .expect('Cache-Control', 'public, max-age=31536000')714 .end(done)715 })716717 it('should min cache-control max-age to 0', function (done) {718 var app = express()719720 app.use(function (req, res) {721 res.sendFile(path.resolve(fixtures, 'user.html'), {722 maxAge: -20000723 })724 })725726 request(app)727 .get('/')728 .expect(200)729 .expect('Cache-Control', 'public, max-age=0')730 .end(done)731 })732733 it('should floor cache-control max-age', function (done) {734 var app = express()735736 app.use(function (req, res) {737 res.sendFile(path.resolve(fixtures, 'user.html'), {738 maxAge: 21911.23739 })740 })741742 request(app)743 .get('/')744 .expect(200)745 .expect('Cache-Control', 'public, max-age=21')746 .end(done)747 })748749 describe('when cacheControl: false', function () {750 it('should not send cache-control', function (done) {751 var app = express()752753 app.use(function (req, res) {754 res.sendFile(path.resolve(fixtures, 'user.html'), {755 cacheControl: false,756 maxAge: 20000757 })758 })759760 request(app)761 .get('/')762 .expect(200)763 .expect(utils.shouldNotHaveHeader('Cache-Control'))764 .end(done)765 })766 })767768 describe('when string', function () {769 it('should accept plain number as milliseconds', function (done) {770 var app = express()771772 app.use(function (req, res) {773 res.sendFile(path.resolve(fixtures, 'user.html'), {774 maxAge: '20000'775 })776 })777778 request(app)779 .get('/')780 .expect(200)781 .expect('Cache-Control', 'public, max-age=20')782 .end(done)783 })784785 it('should accept suffix "s" for seconds', function (done) {786 var app = express()787788 app.use(function (req, res) {789 res.sendFile(path.resolve(fixtures, 'user.html'), {790 maxAge: '20s'791 })792 })793794 request(app)795 .get('/')796 .expect(200)797 .expect('Cache-Control', 'public, max-age=20')798 .end(done)799 })800801 it('should accept suffix "m" for minutes', function (done) {802 var app = express()803804 app.use(function (req, res) {805 res.sendFile(path.resolve(fixtures, 'user.html'), {806 maxAge: '20m'807 })808 })809810 request(app)811 .get('/')812 .expect(200)813 .expect('Cache-Control', 'public, max-age=1200')814 .end(done)815 })816817 it('should accept suffix "d" for days', function (done) {818 var app = express()819820 app.use(function (req, res) {821 res.sendFile(path.resolve(fixtures, 'user.html'), {822 maxAge: '20d'823 })824 })825826 request(app)827 .get('/')828 .expect(200)829 .expect('Cache-Control', 'public, max-age=1728000')830 .end(done)831 })832 })833 })834835 describe('with "root" option', function () {836 it('should allow relative path', function (done) {837 var app = express()838839 app.use(function (req, res) {840 res.sendFile('name.txt', {841 root: fixtures842 })843 })844845 request(app)846 .get('/')847 .expect(200, 'tobi', done)848 })849850 it('should allow up within root', function (done) {851 var app = express()852853 app.use(function (req, res) {854 res.sendFile('fake/../name.txt', {855 root: fixtures856 })857 })858859 request(app)860 .get('/')861 .expect(200, 'tobi', done)862 })863864 it('should reject up outside root', function (done) {865 var app = express()866867 app.use(function (req, res) {868 res.sendFile('..' + path.sep + path.relative(path.dirname(fixtures), path.join(fixtures, 'name.txt')), {869 root: fixtures870 })871 })872873 request(app)874 .get('/')875 .expect(403, done)876 })877878 it('should reject reading outside root', function (done) {879 var app = express()880881 app.use(function (req, res) {882 res.sendFile('../name.txt', {883 root: fixtures884 })885 })886887 request(app)888 .get('/')889 .expect(403, done)890 })891 })892 })893})894895function createApp(path, options, fn) {
5 unmodified lines
901902 return app;903}904393function shouldHaveBody (buf) {394 return function (res) {395 var body = !Buffer.isBuffer(res.body)396 ? Buffer.from(res.text)397 : res.body398 assert.ok(body, 'response has body')399 assert.strictEqual(body.toString('hex'), buf.toString('hex'))905function tryRequire (name) {906 try {907 return require(name)908 } catch (e) {909 return {}910 }911}
modified:test/res.status.js+193 added-12 removed
1'use strict'23var express = require('../')4 , request = require('supertest');4var request = require('supertest')56describe('res', function(){7 describe('.status(code)', function(){8 it('should set the response .statusCode', function(done){9 var app = express();6var isIoJs = process.release7 ? process.release.name === 'io.js'8 : ['v1.', 'v2.', 'v3.'].indexOf(process.version.slice(0, 3)) !== -1911 app.use(function(req, res){12 res.status(201).end('Created');13 });10describe('res', function () {11 describe('.status(code)', function () {12 describe('when "code" is undefined', function () {13 it('should raise error for invalid status code', function (done) {14 var app = express()1516 app.use(function (req, res) {17 res.status(undefined).end()18 })1915 request(app)16 .get('/')17 .expect('Created')18 .expect(201, done);20 request(app)21 .get('/')22 .expect(500, /Invalid status code/, function (err) {23 if (isIoJs) {24 done(err ? null : new Error('expected error'))25 } else {26 done(err)27 }28 })29 })30 })3132 describe('when "code" is null', function () {33 it('should raise error for invalid status code', function (done) {34 var app = express()3536 app.use(function (req, res) {37 res.status(null).end()38 })3940 request(app)41 .get('/')42 .expect(500, /Invalid status code/, function (err) {43 if (isIoJs) {44 done(err ? null : new Error('expected error'))45 } else {46 done(err)47 }48 })49 })50 })5152 describe('when "code" is 201', function () {53 it('should set the response status code to 201', function (done) {54 var app = express()5556 app.use(function (req, res) {57 res.status(201).end()58 })5960 request(app)61 .get('/')62 .expect(201, done)63 })64 })6566 describe('when "code" is 302', function () {67 it('should set the response status code to 302', function (done) {68 var app = express()6970 app.use(function (req, res) {71 res.status(302).end()72 })7374 request(app)75 .get('/')76 .expect(302, done)77 })78 })7980 describe('when "code" is 403', function () {81 it('should set the response status code to 403', function (done) {82 var app = express()8384 app.use(function (req, res) {85 res.status(403).end()86 })8788 request(app)89 .get('/')90 .expect(403, done)91 })92 })9394 describe('when "code" is 501', function () {95 it('should set the response status code to 501', function (done) {96 var app = express()9798 app.use(function (req, res) {99 res.status(501).end()100 })101102 request(app)103 .get('/')104 .expect(501, done)105 })106 })107108 describe('when "code" is "410"', function () {109 it('should set the response status code to 410', function (done) {110 var app = express()111112 app.use(function (req, res) {113 res.status('410').end()114 })115116 request(app)117 .get('/')118 .expect(410, done)119 })120 })121122 describe('when "code" is 410.1', function () {123 it('should set the response status code to 410', function (done) {124 var app = express()125126 app.use(function (req, res) {127 res.status(410.1).end()128 })129130 request(app)131 .get('/')132 .expect(410, function (err) {133 if (isIoJs) {134 done(err ? null : new Error('expected error'))135 } else {136 done(err)137 }138 })139 })140 })141142 describe('when "code" is 1000', function () {143 it('should raise error for invalid status code', function (done) {144 var app = express()145146 app.use(function (req, res) {147 res.status(1000).end()148 })149150 request(app)151 .get('/')152 .expect(500, /Invalid status code/, function (err) {153 if (isIoJs) {154 done(err ? null : new Error('expected error'))155 } else {156 done(err)157 }158 })159 })160 })161162 describe('when "code" is 99', function () {163 it('should raise error for invalid status code', function (done) {164 var app = express()165166 app.use(function (req, res) {167 res.status(99).end()168 })169170 request(app)171 .get('/')172 .expect(500, /Invalid status code/, function (err) {173 if (isIoJs) {174 done(err ? null : new Error('expected error'))175 } else {176 done(err)177 }178 })179 })180 })181182 describe('when "code" is -401', function () {183 it('should raise error for invalid status code', function (done) {184 var app = express()185186 app.use(function (req, res) {187 res.status(-401).end()188 })189190 request(app)191 .get('/')192 .expect(500, /Invalid status code/, function (err) {193 if (isIoJs) {194 done(err ? null : new Error('expected error'))195 } else {196 done(err)197 }198 })199 })200 })201 })202})
modified:test/Route.js+51 added-20 removed
1'use strict'23var after = require('after');4var should = require('should');4var assert = require('assert')5var express = require('../')6 , Route = express.Route7 , methods = require('methods')8
3 unmodified lines
12 var route = new Route('/foo')13 route.dispatch(req, {}, done)14 })1516 it('should not stack overflow with a large sync stack', function (done) {17 this.timeout(5000) // long-running test1819 var req = { method: 'GET', url: '/' }20 var route = new Route('/foo')2122 route.get(function (req, res, next) {23 req.counter = 024 next()25 })2627 for (var i = 0; i < 6000; i++) {28 route.all(function (req, res, next) {29 req.counter++30 next()31 })32 }3334 route.get(function (req, res, next) {35 req.called = true36 next()37 })3839 route.dispatch(req, {}, function (err) {40 if (err) return done(err)41 assert.ok(req.called)42 assert.strictEqual(req.counter, 6000)43 done()44 })45 })4647 describe('.all', function(){48 it('should add handler', function(done){49 var req = { method: 'GET', url: '/' };50 var route = new Route('/foo');
4 unmodified lines
55 });5657 route.dispatch(req, {}, function (err) {58 if (err) return done(err);28 should(req.called).be.ok()59 assert.ok(req.called)60 done();61 });62 })63
1 unmodified line
65 var count = 0;66 var route = new Route('/foo');67 var cb = after(methods.length, function (err) {68 if (err) return done(err);38 count.should.equal(methods.length);69 assert.strictEqual(count, methods.length)70 done();71 });7273 route.all(function(req, res, next) {
22 unmodified lines
96 });9798 route.dispatch(req, {}, function (err) {99 if (err) return done(err);69 req.count.should.equal(2);100 assert.strictEqual(req.count, 2)101 done();102 });103 })104 })
9 unmodified lines
114 })115116 route.dispatch(req, {}, function (err) {117 if (err) return done(err);87 should(req.called).be.ok()118 assert.ok(req.called)119 done();120 });121 })122123 it('should limit to just .VERB', function(done){124 var req = { method: 'POST', url: '/' };125 var route = new Route('');12696 route.get(function(req, res, next) {127 route.get(function () {128 throw new Error('not me!');129 })130131 route.post(function(req, res, next) {
2 unmodified lines
134 })135136 route.dispatch(req, {}, function (err) {137 if (err) return done(err);107 should(req.called).be.true()138 assert.ok(req.called)139 done();140 });141 })142
17 unmodified lines
160 })161162 route.dispatch(req, {}, function (err) {163 if (err) return done(err);133 req.order.should.equal('abc');164 assert.strictEqual(req.order, 'abc')165 done();166 });167 })168 })
17 unmodified lines
186 next(err);187 });188189 route.dispatch(req, {}, function (err) {159 should(err).be.ok()160 should(err.message).equal('foobar');161 req.order.should.equal('a');190 assert.ok(err)191 assert.strictEqual(err.message, 'foobar')192 assert.strictEqual(req.order, 'a')193 done();194 });195 })196197 it('should handle throw', function(done) {198 var req = { order: '', method: 'GET', url: '/' };199 var route = new Route('');200170 route.all(function(req, res, next){201 route.all(function () {202 throw new Error('foobar');203 });204205 route.all(function(req, res, next){
6 unmodified lines
212 next(err);213 });214215 route.dispatch(req, {}, function (err) {185 should(err).be.ok()186 should(err.message).equal('foobar');187 req.order.should.equal('a');216 assert.ok(err)217 assert.strictEqual(err.message, 'foobar')218 assert.strictEqual(req.order, 'a')219 done();220 });221 });222223 it('should handle throwing inside error handlers', function(done) {224 var req = { method: 'GET', url: '/' };225 var route = new Route('');226196 route.get(function(req, res, next){227 route.get(function () {228 throw new Error('boom!');229 });230231 route.get(function(err, req, res, next){
6 unmodified lines
238 });239240 route.dispatch(req, {}, function (err) {241 if (err) return done(err);211 should(req.message).equal('oops');242 assert.strictEqual(req.message, 'oops')243 done();244 });245 });246
5 unmodified lines
252 throw new Error('boom!');253 });254255 route.dispatch(req, {}, function(err){225 should(err).be.ok()226 err.message.should.equal('boom!');256 assert.ok(err)257 assert.strictEqual(err.message, 'boom!')258 done();259 });260 });261
2 unmodified lines
264 var route = new Route('');265266 route.all(function(err, req, res, next){267 // this should not execute237 true.should.be.false()268 throw new Error('should not be called')269 });270271 route.dispatch(req, {}, done);272 });
2 unmodified lines
modified:test/Router.js+87 added-4 removed
59 unmodified lines
6061 router.handle({ method: 'GET' }, {}, done)62 })6364 it('handle missing method', function (done) {65 var all = false66 var router = new Router()67 var route = router.route('/foo')68 var use = false6970 route.post(function (req, res, next) { next(new Error('should not run')) })71 route.all(function (req, res, next) {72 all = true73 next()74 })75 route.get(function (req, res, next) { next(new Error('should not run')) })7677 router.get('/foo', function (req, res, next) { next(new Error('should not run')) })78 router.use(function (req, res, next) {79 use = true80 next()81 })8283 router.handle({ url: '/foo' }, {}, function (err) {84 if (err) return done(err)85 assert.ok(all)86 assert.ok(use)87 done()88 })89 })9091 it('should not stack overflow with many registered routes', function(done){92 this.timeout(5000) // long-running test9394 var handler = function(req, res){ res.end(new Error('wrong handler')) };95 var router = new Router();9697 for (var i = 0; i < 6000; i++) {
6 unmodified lines
104105 router.handle({ url: '/', method: 'GET' }, { end: done }, function(){});106 });107108 it('should not stack overflow with a large sync route stack', function (done) {109 this.timeout(5000) // long-running test110111 var router = new Router()112113 router.get('/foo', function (req, res, next) {114 req.counter = 0115 next()116 })117118 for (var i = 0; i < 6000; i++) {119 router.get('/foo', function (req, res, next) {120 req.counter++121 next()122 })123 }124125 router.get('/foo', function (req, res) {126 assert.strictEqual(req.counter, 6000)127 res.end()128 })129130 router.handle({ url: '/foo', method: 'GET' }, { end: done }, function (err) {131 assert(!err, err);132 });133 })134135 it('should not stack overflow with a large sync middleware stack', function (done) {136 this.timeout(5000) // long-running test137138 var router = new Router()139140 router.use(function (req, res, next) {141 req.counter = 0142 next()143 })144145 for (var i = 0; i < 6000; i++) {146 router.use(function (req, res, next) {147 req.counter++148 next()149 })150 }151152 router.use(function (req, res) {153 assert.strictEqual(req.counter, 6000)154 res.end()155 })156157 router.handle({ url: '/', method: 'GET' }, { end: done }, function (err) {158 assert(!err, err);159 })160 })161162 describe('.handle', function(){163 it('should dispatch', function(done){164 var router = new Router();165
65 unmodified lines
231232 it('should handle throwing inside routes with params', function(done) {233 var router = new Router();234152 router.get('/foo/:id', function(req, res, next){235 router.get('/foo/:id', function () {236 throw new Error('foo');237 });238239 router.use(function(req, res, next){
361 unmodified lines
601 var req1 = { url: '/foo/50/bar', method: 'get' };602 var req2 = { url: '/foo/10/bar', method: 'get' };603 var router = new Router();604 var sub = new Router();605 var cb = after(2, done)606523 done = after(2, done);607608 sub.get('/bar', function(req, res, next) {609 next();610 });
10 unmodified lines
621 router.handle(req1, {}, function(err) {622 assert.ifError(err);623 assert.equal(req1.ms, 50);624 assert.equal(req1.originalUrl, '/foo/50/bar');542 done();625 cb()626 });627628 router.handle(req2, {}, function(err) {629 assert.ifError(err);630 assert.equal(req2.ms, 10);631 assert.equal(req2.originalUrl, '/foo/10/bar');549 done();632 cb()633 });634 });635 });636})
modified:appveyor.yml+28 added-8 removed
8 unmodified lines
9 - nodejs_version: "10.24"10 - nodejs_version: "11.15"11 - nodejs_version: "12.22"12 - nodejs_version: "13.14"13 - nodejs_version: "14.19"13 - nodejs_version: "14.20"14 - nodejs_version: "15.14"15 - nodejs_version: "16.20"16 - nodejs_version: "17.9"17 - nodejs_version: "18.19"18 - nodejs_version: "19.9"19 - nodejs_version: "20.11"20 - nodejs_version: "21.6"21cache:22 - node_modules23install:24 # Install Node.js25 - ps: >-26 try { Install-Product node $env:nodejs_version -ErrorAction Stop }20 catch { Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version) }27 catch { Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version) x64 }28 # Configure npm29 - ps: |30 npm config set loglevel error31 if ((npm config get package-lock) -eq "true") {32 npm config set package-lock false33 } else {24 npm config set shrinkwrap false34 npm config set shrinkwrap false35 }36 # Remove all non-test dependencies37 - ps: |38 # Remove example dependencies39 npm rm --silent --save-dev connect-redis
7 unmodified lines
47 # - use 5.x for Node.js < 648 # - use 6.x for Node.js < 849 # - use 7.x for Node.js < 1050 # - use 8.x for Node.js < 1251 # - use 9.x for Node.js < 1440 if ([int]$env:nodejs_version.split(".")[0] -lt 6) {52 if ([int]$env:nodejs_version.split(".")[0] -lt 4) {53 npm install --silent --save-dev mocha@3.5.354 } elseif ([int]$env:nodejs_version.split(".")[0] -lt 6) {55 npm install --silent --save-dev mocha@5.2.056 } elseif ([int]$env:nodejs_version.split(".")[0] -lt 8) {57 npm install --silent --save-dev mocha@6.2.258 } elseif ([int]$env:nodejs_version.split(".")[0] -lt 10) {59 npm install --silent --save-dev mocha@7.2.060 } elseif ([int]$env:nodejs_version.split(".")[0] -lt 12) {61 npm install --silent --save-dev mocha@8.4.062 } elseif ([int]$env:nodejs_version.split(".")[0] -lt 14) {63 npm install --silent --save-dev mocha@9.2.264 }65 - ps: |66 # nyc for test coverage67 # - use 10.3.2 for Node.js < 468 # - use 11.9.0 for Node.js < 653 # - use 14.1.1 for Node.js < 869 # - use 14.1.1 for Node.js < 1070 if ([int]$env:nodejs_version.split(".")[0] -lt 4) {71 npm install --silent --save-dev nyc@10.3.272 } elseif ([int]$env:nodejs_version.split(".")[0] -lt 6) {73 npm install --silent --save-dev nyc@11.9.058 } elseif ([int]$env:nodejs_version.split(".")[0] -lt 8) {74 } elseif ([int]$env:nodejs_version.split(".")[0] -lt 10) {75 npm install --silent --save-dev nyc@14.1.176 }77 - ps: |78 # supertest for http calls63 # - use 3.4.2 for Node.js < 664 if ([int]$env:nodejs_version.split(".")[0] -lt 6) {79 # - use 2.0.0 for Node.js < 480 # - use 3.4.2 for Node.js < 781 # - use 6.1.6 for Node.js < 882 if ([int]$env:nodejs_version.split(".")[0] -lt 4) {83 npm install --silent --save-dev supertest@2.0.084 } elseif ([int]$env:nodejs_version.split(".")[0] -lt 7) {85 npm install --silent --save-dev supertest@3.4.286 } elseif ([int]$env:nodejs_version.split(".")[0] -lt 8) {87 npm install --silent --save-dev supertest@6.1.688 }
18 unmodified lines
modified:Charter.md+2 added-2 removed
7 unmodified lines
8also easily visible to outsiders.910## Section 1: Scope1112Express is a http web server framework with a simple and expressive API12Express is a HTTP web server framework with a simple and expressive API13which is highly aligned with Node.js core. We aim to be the best in14class for writing performant, spec compliant, and powerful web servers15in Node.js. As one of the oldest and most popular web frameworks in16the ecosystem, we have an important place for new users and experts
6 unmodified lines
23- [expressjs](http://github.com/expressjs/): Top level middleware and24 libraries25- [pillarjs](http://github.com/pillarjs/): Components which make up26 Express but can also be used for other web frameworks27- [jshttp](http://github.com/jshttp/): Low level http libraries27- [jshttp](http://github.com/jshttp/): Low level HTTP libraries2829### 1.2: Out-of-Scope3031Section Intentionally Left Blank
61 unmodified lines
modified:Contributing.md+69 added-6 removed
10 unmodified lines
11## Vocabulary1213* A **Contributor** is any individual creating or commenting on an issue or pull request.14* A **Committer** is a subset of contributors who have been given write access to the repository.15* A **Project Captain** is the lead maintainer of a repository.16* A **TC (Technical Committee)** is a group of committers representing the required technical17expertise to resolve rare disputes.18* A **Triager** is a subset of contributors who have been given triage access to the repository.19
82 unmodified lines
102If a consensus cannot be reached that has no objections then a majority wins vote103is called. It is also expected that the majority of decisions made by the TC are via104a consensus seeking process and that voting is only used as a last-resort.105105Resolution may involve returning the issue to committers with suggestions on how to106move forward towards a consensus. It is not expected that a meeting of the TC106Resolution may involve returning the issue to project captains with suggestions on107how to move forward towards a consensus. It is not expected that a meeting of the TC108will resolve all issues on its agenda during that meeting and may prefer to continue108the discussion happening among the committers.109the discussion happening among the project captains.110110Members can be added to the TC at any time. Any committer can nominate another committer111Members can be added to the TC at any time. Any TC member can nominate another committer112to the TC and the TC uses its standard consensus seeking process to evaluate whether or112not to add this new member. Members who do not participate consistently at the level of113a majority of the other members are expected to resign.113not to add this new member. The TC will consist of a minimum of 3 active members and a114maximum of 10. If the TC should drop below 5 members the active TC members should nominate115someone new. If a TC member is stepping down, they are encouraged (but not required) to116nominate someone to take their place.117118TC members will be added as admin's on the Github orgs, npm orgs, and other resources as119necessary to be effective in the role.120121To remain "active" a TC member should have participation within the last 12 months and miss122no more than six consecutive TC meetings. Our goal is to increase participation, not punish123people for any lack of participation, this guideline should be only be used as such124(replace an inactive member with a new active one, for example). Members who do not meet this125are expected to step down. If A TC member does not step down, an issue can be opened in the126discussions repo to move them to inactive status. TC members who step down or are removed due127to inactivity will be moved into inactive status.128129Inactive status members can become active members by self nomination if the TC is not already130larger than the maximum of 10. They will also be given preference if, while at max size, an131active member steps down.132133## Project Captains134135The Express TC can designate captains for individual projects/repos in the136organizations. These captains are responsible for being the primary137day-to-day maintainers of the repo on a technical and community front.138Repo captains are empowered with repo ownership and package publication rights.139When there are conflicts, especially on topics that effect the Express project140at large, captains are responsible to raise it up to the TC and drive141those conflicts to resolution. Captains are also responsible for making sure142community members follow the community guidelines, maintaining the repo143and the published package, as well as in providing user support.144145Like TC members, Repo captains are a subset of committers.146147To become a captain for a project the candidate is expected to participate in that148project for at least 6 months as a committer prior to the request. They should have149helped with code contributions as well as triaging issues. They are also required to150have 2FA enabled on both their GitHub and npm accounts. Any TC member or existing151captain on the repo can nominate another committer to the captain role, submit a PR to152this doc, under `Current Project Captains` section (maintaining the sort order) with153the project, their GitHub handle and npm username (if different). The PR will require154at least 2 approvals from TC members and 2 weeks hold time to allow for comment and/or155dissent. When the PR is merged, a TC member will add them to the proper GitHub/npm groups.156157### Current Project Captains158159- `expressjs/express`: @wesleytodd160- `expressjs/discussions`: @wesleytodd161- `expressjs/expressjs.com`: @crandmck162- `expressjs/body-parser`: @wesleytodd163- `expressjs/multer`: @LinusU164- `expressjs/cookie-parser`: @wesleytodd165- `expressjs/generator`: @wesleytodd166- `expressjs/statusboard`: @wesleytodd167- `pillarjs/path-to-regexp`: @blakeembrey168- `pillarjs/router`: @dougwilson, @wesleytodd169- `pillarjs/finalhandler`: @wesleytodd170- `pillarjs/request`: @wesleytodd171- `jshttp/http-errors`: @wesleytodd172- `jshttp/cookie`: @wesleytodd173- `jshttp/on-finished`: @wesleytodd174- `jshttp/forwarded`: @wesleytodd175- `jshttp/proxy-addr`: @wesleytodd176
modified:History.md+85 added-5 removed
160 unmodified lines
161 - `req.query` is now a getter instead of a plain property162 * add:163 - `app.router` is a reference to the base router1641654.18.3 / 2024-03-20166==========167168 * Prevent open redirect allow list bypass due to encodeurl169 * deps: cookie@0.6.01701714.18.3 / 2024-02-29172==========173174 * Fix routing requests without method175 * deps: body-parser@1.20.2176 - Fix strict json error message on Node.js 19+177 - deps: content-type@~1.0.5178 - deps: raw-body@2.5.2179 * deps: cookie@0.6.0180 - Add `partitioned` option1811824.18.2 / 2022-10-08183===================184185 * Fix regression routing a large stack in a single route186 * deps: body-parser@1.20.1187 - deps: qs@6.11.0188 - perf: remove unnecessary object clone189 * deps: qs@6.11.01901914.18.1 / 2022-04-29192===================193194 * Fix hanging on large stack of sync routes1951964.18.0 / 2022-04-25197===================198199 * Add "root" option to `res.download`200 * Allow `options` without `filename` in `res.download`201 * Deprecate string and non-integer arguments to `res.status`202 * Fix behavior of `null`/`undefined` as `maxAge` in `res.cookie`203 * Fix handling very large stacks of sync middleware204 * Ignore `Object.prototype` values in settings through `app.set`/`app.get`205 * Invoke `default` with same arguments as types in `res.format`206 * Support proper 205 responses using `res.send`207 * Use `http-errors` for `res.format` error208 * deps: body-parser@1.20.0209 - Fix error message for json parse whitespace in `strict`210 - Fix internal error when inflated body exceeds limit211 - Prevent loss of async hooks context212 - Prevent hanging when request already read213 - deps: depd@2.0.0214 - deps: http-errors@2.0.0215 - deps: on-finished@2.4.1216 - deps: qs@6.10.3217 - deps: raw-body@2.5.1218 * deps: cookie@0.5.0219 - Add `priority` option220 - Fix `expires` option to reject invalid dates221 * deps: depd@2.0.0222 - Replace internal `eval` usage with `Function` constructor223 - Use instance methods on `process` to check for listeners224 * deps: finalhandler@1.2.0225 - Remove set content headers that break response226 - deps: on-finished@2.4.1227 - deps: statuses@2.0.1228 * deps: on-finished@2.4.1229 - Prevent loss of async hooks context230 * deps: qs@6.10.3231 * deps: send@0.18.0232 - Fix emitted 416 error missing headers property233 - Limit the headers removed for 304 response234 - deps: depd@2.0.0235 - deps: destroy@1.2.0236 - deps: http-errors@2.0.0237 - deps: on-finished@2.4.1238 - deps: statuses@2.0.1239 * deps: serve-static@1.15.0240 - deps: send@0.18.0241 * deps: statuses@2.0.1242 - Remove code 306243 - Rename `425 Unordered Collection` to standard `425 Too Early`2442454.17.3 / 2022-02-16246===================247248 * deps: accepts@~1.3.8
2042 unmodified lines
2291 * use `media-typer` to alter content-type charset2292 * deps: connect@2.21.02293 - deprecate `connect(middleware)` -- use `app.use(middleware)` instead2294 - deprecate `connect.createServer()` -- use `connect()` instead2215 - fix `res.setHeader()` patch to work with with get -> append -> set pattern2295 - fix `res.setHeader()` patch to work with get -> append -> set pattern2296 - deps: compression@~1.0.82297 - deps: errorhandler@~1.1.12298 - deps: express-session@~1.5.02299 - deps: serve-index@~1.1.3
1202 unmodified lines
35023503 * Added node v0.1.97 compatibility3504 * Added support for deleting cookies via Request#cookie('key', null)3505 * Updated haml submodule3426 * Fixed not-found page, now using using charset utf-83427 * Fixed show-exceptions page, now using using charset utf-83506 * Fixed not-found page, now using charset utf-83507 * Fixed show-exceptions page, now using charset utf-83508 * Fixed view support due to fs.readFile Buffers3509 * Changed; mime.type() no longer accepts ".type" due to node extname() changes351035110.12.0 / 2010-05-22
26 unmodified lines
35380.10.0 / 2010-04-303539==================35403541 * Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s3462 encoding is set to 'utf8' or 'utf-8'.3542 encoding is set to 'utf8' or 'utf-8').3543 * Added "encoding" option to Request#render(). Closes #2993544 * Added "dump exceptions" setting, which is enabled by default.3545 * Added simple ejs template engine support3546 * Added error response support for text/plain, application/json. Closes #297
30 unmodified lines
3577 * Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #2543578 * Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js3579 * Added callback function support to Request#halt() as 3rd/4th arg3580 * Added preprocessing of route param wildcards using param(). Closes #2513501 * Added view partial support (with collections etc)3581 * Added view partial support (with collections etc.)3582 * Fixed bug preventing falsey params (such as ?page=0). Closes #2863583 * Fixed setting of multiple cookies. Closes #1993584 * Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml)3585 * Changed; session cookie is now httpOnly
184 unmodified lines
modified:package.json+16 added-18 removed
26 unmodified lines
27 "app",28 "api"29 ],30 "dependencies": {31 "accepts": "~1.3.7",31 "accepts": "~1.3.8",32 "array-flatten": "3.0.0",33 "body-parser": "2.0.0-beta.1",33 "body-parser": "2.0.0-beta.2",34 "content-disposition": "0.5.4",35 "content-type": "~1.0.4",36 "cookie": "0.4.2",36 "cookie": "0.6.0",37 "cookie-signature": "1.0.6",38 "debug": "3.1.0",39 "depd": "~1.1.2",39 "depd": "2.0.0",40 "encodeurl": "~1.0.2",41 "escape-html": "~1.0.3",42 "etag": "~1.8.1",43 "finalhandler": "~1.1.2",43 "finalhandler": "1.2.0",44 "fresh": "0.5.2",45 "http-errors": "2.0.0",46 "merge-descriptors": "1.0.1",47 "methods": "~1.1.2",48 "mime-types": "~2.1.34",48 "on-finished": "~2.3.0",49 "on-finished": "2.4.1",50 "parseurl": "~1.3.3",51 "path-is-absolute": "1.0.1",52 "proxy-addr": "~2.0.7",52 "qs": "6.9.7",53 "qs": "6.11.0",54 "range-parser": "~1.2.1",54 "router": "2.0.0-beta.1",55 "router": "2.0.0-beta.2",56 "safe-buffer": "5.2.1",56 "send": "1.0.0-beta.1",57 "serve-static": "2.0.0-beta.1",57 "send": "1.0.0-beta.2",58 "serve-static": "2.0.0-beta.2",59 "setprototypeof": "1.2.0",59 "statuses": "~1.5.0",60 "statuses": "2.0.1",61 "type-is": "~1.6.18",62 "utils-merge": "1.0.1",63 "vary": "~1.1.2"64 },
1 unmodified line
66 "after": "0.8.2",67 "connect-redis": "3.4.2",68 "cookie-parser": "1.4.6",69 "cookie-session": "2.0.0",69 "ejs": "3.1.6",70 "eslint": "7.32.0",70 "ejs": "3.1.9",71 "eslint": "8.47.0",72 "express-session": "1.17.2",73 "hbs": "4.2.0",74 "marked": "0.7.0",75 "method-override": "3.0.0",75 "mocha": "9.2.0",76 "mocha": "10.2.0",77 "morgan": "1.10.0",77 "multiparty": "4.2.3",78 "nyc": "15.1.0",79 "pbkdf2-password": "1.2.1",80 "resolve-path": "1.4.0",81 "should": "13.2.3",82 "supertest": "6.2.2",80 "supertest": "6.3.0",81 "vhost": "~3.0.2"82 },83 "engines": {84 "node": ">= 4"
16 unmodified lines
modified:Readme.md+42 added-34 removed
1[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/)23 Fast, unopinionated, minimalist web framework for [node](http://nodejs.org).3 Fast, unopinionated, minimalist web framework for [Node.js](http://nodejs.org).45 [![NPM Version][npm-image]][npm-url]6 [![NPM Downloads][downloads-image]][downloads-url]7 [![Linux Build][ci-image]][ci-url]8 [![Windows Build][appveyor-image]][appveyor-url]9 [![Test Coverage][coveralls-image]][coveralls-url]5 [![NPM Version][npm-version-image]][npm-url]6 [![NPM Install Size][npm-install-size-image]][npm-install-size-url]7 [![NPM Downloads][npm-downloads-image]][npm-downloads-url]89```js10const express = require('express')11const app = express()
18 unmodified lines
3031Installation is done using the32[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):3336```bash34```console35$ npm install express36```3738Follow [our installing guide](http://expressjs.com/en/starter/installing.html)
11 unmodified lines
5051## Docs & Community5253 * [Website and Documentation](http://expressjs.com/) - [[website repo](https://github.com/expressjs/expressjs.com)]56 * [#express](https://webchat.freenode.net/?channels=express) on freenode IRC54 * [#express](https://web.libera.chat/#express) on [Libera Chat](https://libera.chat) IRC55 * [GitHub Organization](https://github.com/expressjs) for Official Middleware & Modules56 * Visit the [Wiki](https://github.com/expressjs/express/wiki)57 * [Google Group](https://groups.google.com/group/express-js) for discussion58 * [Gitter](https://gitter.im/expressjs/express) for support and discussion5960**PROTIP** Be sure to read [Migrating from 3.x to 4.x](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x) as well as [New features in 4.x](https://github.com/expressjs/express/wiki/New-features-in-4.x).6164### Security Issues6566If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md).6762## Quick Start6364 The quickest way to get started with express is to utilize the executable [`express(1)`](https://github.com/expressjs/generator) to generate an application as shown below:6566 Install the executable. The executable's major version will match Express's:6774```bash68```console69$ npm install -g express-generator@470```7172 Create the app:7380```bash74```console75$ express /tmp/foo && cd /tmp/foo76```7778 Install dependencies:7986```bash80```console81$ npm install82```8384 Start the server:8592```bash86```console87$ npm start88```8990 View the website at: http://localhost:3000
11 unmodified lines
102## Examples103104 To view the examples, clone the Express repo and install the dependencies:105112```bash113$ git clone git://github.com/expressjs/express.git --depth 1106```console107$ git clone https://github.com/expressjs/express.git --depth 1108$ cd express109$ npm install110```111112 Then run whichever example you want:113120```bash114```console115$ node examples/content-negotiation116```117124## Tests118## Contributing119126 To run the test suite, first install the dependencies, then run `npm test`:120 [![Linux Build][github-actions-ci-image]][github-actions-ci-url]121 [![Windows Build][appveyor-image]][appveyor-url]122 [![Test Coverage][coveralls-image]][coveralls-url]123128```bash124The Express.js project welcomes all constructive contributions. Contributions take many forms,125from code for bug fixes and enhancements, to additions and fixes to documentation, additional126tests, triaging incoming pull requests and issues, and more!127128See the [Contributing Guide](Contributing.md) for more technical details on contributing.129130### Security Issues131132If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md).133134### Running Tests135136To run the test suite, first install the dependencies, then run `npm test`:137138```console139$ npm install140$ npm test141```142133## Contributing134135[Contributing Guide](Contributing.md)136143## People144145The original author of Express is [TJ Holowaychuk](https://github.com/tj)146
4 unmodified lines
151## License152153 [MIT](LICENSE)154149[ci-image]: https://img.shields.io/github/workflow/status/expressjs/express/ci/master.svg?label=linux150[ci-url]: https://github.com/expressjs/express/actions?query=workflow%3Aci151[npm-image]: https://img.shields.io/npm/v/express.svg152[npm-url]: https://npmjs.org/package/express153[downloads-image]: https://img.shields.io/npm/dm/express.svg154[downloads-url]: https://npmcharts.com/compare/express?minimal=true155[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/express/master.svg?label=windows155[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/express/master?label=windows156[appveyor-url]: https://ci.appveyor.com/project/dougwilson/express157[coveralls-image]: https://img.shields.io/coveralls/expressjs/express/master.svg157[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/express/master158[coveralls-url]: https://coveralls.io/r/expressjs/express?branch=master159[github-actions-ci-image]: https://badgen.net/github/checks/expressjs/express/master?label=linux160[github-actions-ci-url]: https://github.com/expressjs/express/actions/workflows/ci.yml161[npm-downloads-image]: https://badgen.net/npm/dm/express162[npm-downloads-url]: https://npmcharts.com/compare/express?minimal=true163[npm-install-size-image]: https://badgen.net/packagephobia/install/express164[npm-install-size-url]: https://packagephobia.com/result?p=express165[npm-url]: https://npmjs.org/package/express166[npm-version-image]: https://badgen.net/npm/v/express
modified:Release-Process.md+6 added
182 unmodified lines
183```184185**NOTE:** The version number to publish will be picked up automatically from186 package.json.187 188### Step 7. Update documentation website189190The documentation website https://expressjs.com/ documents the current release version in various places. For a new release:1911. Change the value of `current_version` in https://github.com/expressjs/expressjs.com/blob/gh-pages/_data/express.yml to match the latest version number.1922. Add a new section to the change log. For example, for a 4.x release, https://github.com/expressjs/expressjs.com/blob/gh-pages/en/changelog/4x.md,
modified:Security.md+1 added-2 removed
25 unmodified lines
26endeavor to keep you informed of the progress towards a fix and full27announcement, and may ask for additional information or guidance.2829Report security bugs in third-party modules to the person or team maintaining30the module. You can also report a vulnerability through the31[Node Security Project](https://nodesecurity.io/report).30the module.3132## Disclosure Policy3334When the security team receives a security bug report, they will assign it to a
12 unmodified lines