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
Provenance
- Commit
e9f9aae- Tree
fd7de8a- Author
Wes Todd <wes@wesleytodd.com>- Committer
Wes Todd <wes@wesleytodd.com>- Parent 1
318fd4b- Parent 2
084e365
53 files changed+2818 added−769 removed
modified:.github/workflows/ci.yml+74 added-17 removed
21 unmodified lines2223242526272829303132333435368 unmodified lines4546474842495051525354555650575859605461626364653 unmodified lines6970717273747576777879718081828384858687888990919293949596979899100101102103741041051061071082 unmodified lines111112113114115116117851181191201211221234 unmodified lines12812913013198991321331341351361378 unmodified lines14614714814911615015115215315412015515615715815916016116212716316416516616716816917012913013117117217317417517617717813717918018118218318418518618718818919019119219319419519619714014119821 unmodified lines - Node.js 11.x - Node.js 12.x - Node.js 13.x - Node.js 14.x - Node.js 15.x - Node.js 16.x - Node.js 17.x - Node.js 18.x - Node.js 19.x - Node.js 20.x - Node.js 21.x
include: - name: Node.js 4.0 node-version: "4.0"8 unmodified lines npm-i: mocha@5.2.0 nyc@11.9.0 supertest@3.4.2
- name: Node.js 6.x node-version: "6.17" npm-i: mocha@6.2.2 nyc@14.1.1 supertest@6.1.6 npm-i: mocha@6.2.2 nyc@14.1.1 supertest@3.4.2
- name: Node.js 7.x node-version: "7.10" npm-i: mocha@6.2.2 nyc@14.1.1 supertest@6.1.6
- name: Node.js 8.x node-version: "8.17" npm-i: mocha@7.2.0 npm-i: mocha@7.2.0 nyc@14.1.1
- name: Node.js 9.x node-version: "9.11" npm-i: mocha@7.2.0 npm-i: mocha@7.2.0 nyc@14.1.1
- name: Node.js 10.x node-version: "10.24" npm-i: mocha@8.4.03 unmodified lines npm-i: mocha@8.4.0
- name: Node.js 12.x node-version: "12.22" npm-i: mocha@9.2.2
- name: Node.js 13.x node-version: "13.14" npm-i: mocha@9.2.2
- name: Node.js 14.x node-version: "14.19" node-version: "14.20"
- name: Node.js 15.x node-version: "15.14"
- name: Node.js 16.x node-version: "16.20"
- name: Node.js 17.x node-version: "17.9"
- name: Node.js 18.x node-version: "18.19"
- name: Node.js 19.x node-version: "19.9"
- name: Node.js 20.x node-version: "20.11"
- name: Node.js 21.x node-version: "21.6"
steps: - uses: actions/checkout@v2 - uses: actions/checkout@v4
- name: Install Node.js ${{ matrix.node-version }} shell: bash -eo pipefail -l {0} run: |2 unmodified lines
- name: Configure npm run: | npm config set loglevel error if [[ "$(npm config get package-lock)" == "true" ]]; then npm config set package-lock false else npm config set shrinkwrap false npm config set shrinkwrap false fi
- name: Install npm module(s) ${{ matrix.npm-i }} run: npm install --save-dev ${{ matrix.npm-i }} if: matrix.npm-i != ''4 unmodified lines - name: Setup Node.js version-specific dependencies shell: bash run: | # eslint for linting # - remove on Node.js < 10 if [[ "$(cut -d. -f1 <<< "${{ matrix.node-version }}")" -lt 10 ]]; then # - remove on Node.js < 12 if [[ "$(cut -d. -f1 <<< "${{ matrix.node-version }}")" -lt 12 ]]; then node -pe 'Object.keys(require("./package").devDependencies).join("\n")' | \ grep -E '^eslint(-|$)' | \ sort -r | \ xargs -n1 npm rm --silent --save-dev8 unmodified lines run: | echo "node@$(node -v)" echo "npm@$(npm -v)" npm -s ls ||: (npm -s ls --depth=0 ||:) | awk -F'[ @]' 'NR>1 && $2 { print "::set-output name=" $2 "::" $3 }' (npm -s ls --depth=0 ||:) | awk -F'[ @]' 'NR>1 && $2 { print $2 "=" $3 }' >> "$GITHUB_OUTPUT"
- name: Run tests shell: bash run: | run: npm run test-ci npm run test-ci cp coverage/lcov.info "coverage/${{ matrix.name }}.lcov"
- name: Lint code if: steps.list_env.outputs.eslint != '' run: npm run lint
- name: Collect code coverage uses: coverallsapp/github-action@master run: | mv ./coverage "./${{ matrix.name }}" mkdir ./coverage mv "./${{ matrix.name }}" "./coverage/${{ matrix.name }}"
- name: Upload code coverage uses: actions/upload-artifact@v3 with: github-token: ${{ secrets.GITHUB_TOKEN }} flag-name: run-${{ matrix.test_number }} parallel: true name: coverage path: ./coverage retention-days: 1
coverage: needs: test runs-on: ubuntu-latest steps: - name: Upload code coverage - uses: actions/checkout@v4
- name: Install lcov shell: bash run: sudo apt-get -y install lcov
- name: Collect coverage reports uses: actions/download-artifact@v3 with: name: coverage path: ./coverage
- name: Merge coverage reports shell: bash run: find ./coverage -name lcov.info -exec printf '-a %q\n' {} \; | xargs lcov -o ./coverage/lcov.info
- name: Upload coverage report uses: coverallsapp/github-action@master with: github-token: ${{ secrets.github_token }} parallel-finished: true github-token: ${{ secrets.GITHUB_TOKEN }}modified:benchmarks/Makefile+12 added-8 removed
1 2 all: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 @echo16 17 .PHONY: allmodified:benchmarks/middleware.js+1 added-1 removed
11 unmodified lines1213141516161718192011 unmodified lines next(); });}
app.use(function(req, res, next){app.use(function(req, res){ res.send('Hello World')});
app.listen(3333);added:benchmarks/README.md+34 added
1+# Express Benchmarks2+3+## Installation4+5+You will need to install [wrk](https://github.com/wg/wrk/blob/master/INSTALL) in order to run the benchmarks.6+7+## Running8+9+To run the benchmarks, first install the dependencies `npm i`, then run `make`10+11+The output will look something like this:12+13+```14+ 50 connections15+ 1 middleware16+ 7.15ms17+ 6784.0118+19+ [...redacted...]20+21+ 1000 connections22+ 10 middleware23+ 139.21ms24+ 6155.1925+26+```27+28+### Tip: Include Node.js version in output29+30+You can use `make && node -v` to include the node.js version in the output.31+32+### Tip: Save the results to a file33+34+You can use `make > results.log` to save the results to a file `results.log`.modified:benchmarks/run+5 added-3 removed
2 unmodified lines3 echo4 MW=$1 node $2 &5 pid=$!6 7+echo " $3 connections"8+9 sleep 210 11 wrk '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 }'17 18 kill $pidmodified:examples/auth/views/login.ejs+4 added-4 removed
4 unmodified lines5 <%- message %>6 Try 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 linesmodified:examples/cookie-sessions/index.js+2 added-5 removed
11 unmodified lines12 // add req.session cookie support13 app.use(cookieSession({ secret: 'manny is cool' }));14 15 // do something with the session16-app.use(count);17-18-// custom middleware19-function count(req, res) {16+app.get('/', function (req, res) {17 req.session.count = (req.session.count || 0) + 118 res.send('viewed ' + req.session.count + ' times\n')22-}19+})20 21 /* istanbul ignore next */22 if (!module.parent) {23 app.listen(3000);2 unmodified linesmodified:examples/downloads/index.js+1 added-4 removed
4 unmodified lines5 */6 7 var express = require('../../');8 var path = require('path');9-var resolvePath = require('resolve-path')9 10 var app = module.exports = express();11 12 // path to where the files are stored on disk10 unmodified lines23 24 // /files/* is accessed via req.params[0]25 // but here we name it :file26 app.get('/files/:file+', function (req, res, next) {28- var filePath = resolvePath(FILES_DIR, req.params.file)29-30- 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 linesmodified:examples/error/index.js+1 added-1 removed
24 unmodified lines25 res.status(500);26 res.send('Internal Server Error');27 }28 29-app.get('/', function(req, res){29+app.get('/', function () {30 // Caught and passed down to the errorHandler middleware31 throw new Error('something broke!');32 });33 20 unmodified linesmodified:examples/markdown/index.js+1 added-1 removed
24 unmodified lines25 });26 27 app.set('views', path.join(__dirname, 'views'));28 29-// make it the default so we dont need .md29+// make it the default, so we don't need .md30 app.set('view engine', 'md');31 32 app.get('/', function(req, res){33 res.render('index', { title: 'Markdown Example' });11 unmodified linesdeleted:examples/multipart/index.js-62 removed
1-'use strict'2-3-/**4- * Module dependencies.5- */6-7-var express = require('../..');8-var multiparty = require('multiparty');9-var format = require('util').format;10-11-var app = module.exports = express();12-13-app.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-});20-21-app.post('/', function(req, res, next){22- // create a form to begin parsing23- var form = new multiparty.Form();24- var image;25- var title;26-27- 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- });34-35- // listen on field event for title36- form.on('field', function(name, val){37- if (name !== 'title') return;38- title = val;39- });40-41- // 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- });52-53-54- // parse the form55- form.parse(req);56-});57-58-/* istanbul ignore next */59-if (!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 lines3 /**4 * Module dependencies.5 */6 7+var createError = require('http-errors')8 var express = require('../../');9 var app = module.exports = express();10 11 // Faux database5 unmodified lines17 , { name: 'jane' }18 , { name: 'bandit' }19 ];20 20-// Create HTTP error21-22-function createError(status, message) {23- var err = new Error(message);24- err.status = status;25- return err;26-}27-21 // Convert :to and :from to integers22 23 app.param(['to', 'from'], function(req, res, next, num, name){24 req.params[name] = parseInt(num, 10);25 unmodified lines50 /**51 * GET :user.52 */53 61-app.get('/user/:user', function(req, res, next){54+app.get('/user/:user', function (req, res) {55 res.send('user ' + req.user.name);56 });57 58 /**59 * GET users :from - :to.60 */61 69-app.get('/users/:from-:to', function(req, res, next){62+app.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 linesmodified:examples/route-separation/views/users/edit.ejs+1 added-1 removed
1 unmodified line2 3 <h1>Editing <%= user.name %></h1>4 5 <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 linesmodified:examples/search/public/index.html+2 added-2 removed
2 unmodified lines3 <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 lines14 <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 lines60 next();61 })62 }63 64-app.get('/middleware', count, users, function(req, res, next){64+app.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 lines98 next();99 })100 }101 102-app.get('/middleware-locals', count2, users2, function(req, res, next){102+app.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 booster49 unmodified linesmodified:examples/web-service/index.js+2 added-2 removed
70 unmodified lines71 // we now can assume the api key is valid,72 // and simply expose the data73 74 // example: http://localhost:3000/api/users/?api-key=foo75-app.get('/api/users', function(req, res, next){75+app.get('/api/users', function (req, res) {76 res.send(users);77 });78 79 // example: http://localhost:3000/api/repos/?api-key=foo80-app.get('/api/repos', function(req, res, next){80+app.get('/api/repos', function (req, res) {81 res.send(repos);82 });83 84 // example: http://localhost:3000/api/user/tobi/repos/?api-key=foo33 unmodified linesmodified:examples/README.md-1 removed
11 unmodified lines12 - [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 resource10 unmodified linesmodified:lib/application.js+18 added-1 removed
24 unmodified lines25 var merge = require('utils-merge');26 var resolve = require('path').resolve;27 var Router = require('router');28 var setPrototypeOf = require('setprototypeof')29+30+/**31+ * Module variables.32+ * @private33+ */34+35+var hasOwnProperty = Object.prototype.hasOwnProperty36 var slice = Array.prototype.slice;37 38 /**39 * Application prototype.312 unmodified lines352 353 app.set = function set(setting, val) {354 if (arguments.length === 1) {355 // app.get(setting)349- return this.settings[setting];356+ var settings = this.settings357+358+ while (settings && settings !== Object.prototype) {359+ if (hasOwnProperty.call(settings, setting)) {360+ return settings[setting]361+ }362+363+ settings = Object.getPrototypeOf(settings)364+ }365+366+ return undefined367 }368 369 debug('set "%s" to %o', setting, val);370 277 unmodified linesmodified:lib/response.js+59 added-18 removed
12 unmodified lines13 */14 15 var Buffer = require('safe-buffer').Buffer16 var contentDisposition = require('content-disposition');17+var createError = require('http-errors')18+var deprecate = require('depd')('express');19 var encodeUrl = require('encodeurl');20 var escapeHtml = require('escape-html');21 var http = require('http');22 var onFinished = require('on-finished');10 unmodified lines33 var send = require('send');34 var extname = path.extname;35 var resolve = path.resolve;36 var vary = require('vary');37+var urlParse = require('url').parse;38 39 /**40 * Response prototype.41 * @public16 unmodified lines58 * @public59 */60 61 res.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 lines185 this.removeHeader('Transfer-Encoding');186 chunk = '';187 }188 189+ // alter headers for 205190+ if (this.statusCode === 205) {191+ this.set('Content-Length', '0')192+ this.removeHeader('Transfer-Encoding')193+ chunk = ''194+ }195+196 if (req.method === 'HEAD') {197 // skip body for HEAD198 this.end();199 } else {105 unmodified lines305 * @public306 */307 308 res.sendStatus = function sendStatus(statusCode) {296- var body = statuses[statusCode] || String(statusCode)309+ var body = statuses.message[statusCode] || String(statusCode)310 311 this.statusCode = statusCode;312 this.type('txt');313 114 unmodified lines428 done = options429 opts = null430 }431 432+ // 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+ }438+439 // set Content-Disposition when file is sent440 var headers = {441 'Content-Disposition': contentDisposition(name || path)442 };13 unmodified lines456 opts = Object.create(opts)457 opts.headers = headers458 459 // Resolve the full path for sendFile440- var fullPath = resolve(path);460+ var fullPath = !opts.root461+ ? resolve(path)462+ : path463 464 // send file465 return this.sendFile(fullPath, opts, done)466 };86 unmodified lines553 res.format = function(obj){554 var req = this.req;555 var next = req.next;556 535- 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' })559 560 var key = keys.length > 0561 ? req.accepts(keys)562 : false;2 unmodified lines565 566 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 }576 577 return this;578 };157 unmodified lines736 if (signed) {737 val = 's:' + sign(val, secret);738 }739 720- 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 - 0742+743+ if (!isNaN(maxAge)) {744+ opts.expires = new Date(Date.now() + maxAge)745+ opts.maxAge = Math.floor(maxAge / 1000)746+ }747 }748 749 if (opts.path == null) {750 opts.path = '/';28 unmodified lines779 if (url === 'back') {780 loc = this.req.get('Referrer') || '/';781 }782 783+ 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+ }799+800 // set location760- return this.set('Location', encodeUrl(loc));801+ return this.set('Location', encodedUrl);802 };803 804 /**805 * Redirect to the given `url` with optional response `status`29 unmodified lines835 836 // 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 },841 842 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 },846 847 default: function(){848 body = '';160 unmodified lines1009 * 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 * @private27 unmodified linesmodified:lib/utils.js+3 added-3 removed
75 unmodified lines76 77 /**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 */85 87-function acceptParams(str, index) {86+function 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: {} }89 90 for (var i = 1; i < parts.length; ++i) {91 var pms = parts[i].split(/ *= */);92 if ('q' === pms[0]) {145 unmodified lines238 239 /**240 * Parse an extended query string with qs.241 *242+ * @param {String} str243 * @return {Object}244 * @private245 */246 5 unmodified linesmodified:lib/view.js+1 added-1 removed
72 unmodified lines73 }74 75 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)79 80 // default engine export81 var fn = require(mod).__express124 unmodified linesmodified:test/support/utils.js+14 added
11 unmodified lines12 * @public13 */14 15 exports.shouldHaveBody = shouldHaveBody16+exports.shouldHaveHeader = shouldHaveHeader17 exports.shouldNotHaveBody = shouldNotHaveBody18 exports.shouldNotHaveHeader = shouldNotHaveHeader;19 20 /**13 unmodified lines34 }35 }36 37 /**38+ * Assert that a supertest response does have a header.39+ *40+ * @param {string} header Header name to check41+ * @returns {function}42+ */43+44+function shouldHaveHeader (header) {45+ return function (res) {46+ assert.ok((header.toLowerCase() in res.headers), 'should have header ' + header)47+ }48+}49+50+/**51 * Assert that a supertest response does not have a body.52 *53 * @returns {function}54 */18 unmodified linesmodified:test/app.listen.js+2 added-3 removed
4 unmodified lines5 describe('app.listen()', function(){6 it('should wrap with an HTTP server', function(done){7 var app = express();8 9- 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'2 3 var assert = require('assert')4 var express = require('../')5-var should = require('should')5 6 describe('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- })13 20- 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 lines123 124 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 });130 131 request(app)12 unmodified lines144 app.param('user', function(req, res, next, user) {145 next(new Error('invalid invocation'))146 });147 148- app.post('/:user', function(req, res, next) {148+ app.post('/:user', function (req, res) {149 res.send(req.params.user);150 });151 152- app.get('/:thing', function(req, res, next) {152+ app.get('/:thing', function (req, res) {153 res.send(req.thing);154 });155 156 request(app)167 unmodified linesmodified:test/app.router.js+12 added-12 removed
90 unmodified lines91 describe('decode params', function () {92 it('should decode correct params', function(done){93 var app = express();94 95- app.get('/:name', function(req, res, next){95+ app.get('/:name', function (req, res) {96 res.send(req.params.name);97 });98 99 request(app)3 unmodified lines103 104 it('should not accept params in malformed paths', function(done) {105 var app = express();106 107- app.get('/:name', function(req, res, next){107+ app.get('/:name', function (req, res) {108 res.send(req.params.name);109 });110 111 request(app)3 unmodified lines115 116 it('should not decode spaces', function(done) {117 var app = express();118 119- app.get('/:name', function(req, res, next){119+ app.get('/:name', function (req, res) {120 res.send(req.params.name);121 });122 123 request(app)3 unmodified lines127 128 it('should work with unicode', function(done) {129 var app = express();130 131- app.get('/:name', function(req, res, next){131+ app.get('/:name', function (req, res) {132 res.send(req.params.name);133 });134 135 request(app)654 unmodified lines790 .expect(200, 'foo as html', cb)791 792 request(app)793 .get('/foo.json')794- .expect(200, 'foo as json', done)794+ .expect(200, 'foo as json', cb)795 })796 })797 798 describe('when next() is called', function(){5 unmodified lines804 calls.push('/foo/:bar?');805 next();806 });807 808- app.get('/bar', function(req, res){808+ app.get('/bar', function () {809 assert(0);810 });811 812 app.get('/foo', function(req, res, next){813 calls.push('/foo');814 next();815 });816 817- 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 lines833 res.set('X-Hit', '1')834 next('route')835 }836 837- app.get('/foo', fn, function(req, res, next){837+ app.get('/foo', fn, function (req, res) {838 res.end('failure')839 });840 841 app.get('/foo', function(req, res){16 unmodified lines858 res.set('X-Hit', '1')859 next('router')860 }861 862- router.get('/foo', fn, function (req, res, next) {862+ router.get('/foo', fn, function (req, res) {863 res.end('failure')864 })865 866- router.get('/foo', function (req, res, next) {866+ router.get('/foo', function (req, res) {867 res.end('failure')868 })869 870 app.use(router)18 unmodified lines889 calls.push('/foo/:bar?');890 next();891 });892 893- app.get('/bar', function(req, res){893+ app.get('/bar', function () {894 assert(0);895 });896 897 app.get('/foo', function(req, res, next){898 calls.push('/foo');899 next(new Error('fail'));900 });901 902- app.get('/foo', function(req, res, next){902+ app.get('/foo', function () {903 assert(0);904 });905 906 app.use(function(err, req, res, next){232 unmodified linesmodified:test/app.use.js+1 added-1 removed
55 unmodified lines56 .expect(200, 'blog', cb)57 58 request(app)59 .get('/forum')60- .expect(200, 'forum', done)60+ .expect(200, 'forum', cb)61 })62 63 it('should set the child\'s .parent', function(){64 var blog = express()478 unmodified linesmodified:test/config.js+44 added
9 unmodified lines10 app.set('foo', 'bar');11 assert.equal(app.get('foo'), 'bar');12 })13 14+ it('should set prototype values', function () {15+ var app = express()16+ app.set('hasOwnProperty', 42)17+ assert.strictEqual(app.get('hasOwnProperty'), 42)18+ })19+20 it('should return the app', function () {21 var app = express();22 assert.equal(app.set('foo', 'bar'), app);23 })2 unmodified lines26 var app = express();27 assert.equal(app.set('foo', undefined), app);28 })29 30+ it('should return set value', function () {31+ var app = express()32+ app.set('foo', 'bar')33+ assert.strictEqual(app.set('foo'), 'bar')34+ })35+36+ it('should return undefined for prototype values', function () {37+ var app = express()38+ assert.strictEqual(app.set('hasOwnProperty'), undefined)39+ })40+41 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 lines67 var app = express();68 assert.strictEqual(app.get('foo'), undefined);69 })70 71+ it('should return undefined for prototype values', function () {72+ var app = express()73+ assert.strictEqual(app.get('hasOwnProperty'), undefined)74+ })75+76 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 lines146 var app = express();147 assert.equal(app.enable('tobi'), app);148 assert.strictEqual(app.get('tobi'), true);149 })150+151+ it('should set prototype values', function () {152+ var app = express()153+ app.enable('hasOwnProperty')154+ assert.strictEqual(app.get('hasOwnProperty'), true)155+ })156 })157 158 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 })164+165+ it('should set prototype values', function () {166+ var app = express()167+ app.disable('hasOwnProperty')168+ assert.strictEqual(app.get('hasOwnProperty'), false)169+ })170 })171 172 describe('.enabled()', function(){173 it('should default to false', function(){5 unmodified lines179 var app = express();180 app.set('foo', 'bar');181 assert.strictEqual(app.enabled('foo'), true);182 })183+184+ it('should default to false for prototype values', function () {185+ var app = express()186+ assert.strictEqual(app.enabled('hasOwnProperty'), false)187+ })188 })189 190 describe('.disabled()', function(){191 it('should default to true', function(){5 unmodified lines197 var app = express();198 app.set('foo', 'bar');199 assert.strictEqual(app.disabled('foo'), false);200 })201+202+ 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 lines5 var request = require('supertest');6 7 describe('exports', function(){8 it('should expose Router', function(){9- express.Router.should.be.a.Function()9+ assert.strictEqual(typeof express.Router, 'function')10 })11 12 it('should expose json middleware', function () {13 assert.equal(typeof express.json, 'function')20 unmodified lines34 assert.equal(express.urlencoded.length, 1)35 })36 37 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 })41 42 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 })46 47 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 })51 52 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 })56 57 it('should permit modifying the .request prototype', function(done){58 express.request.foo = function(){ return 'bar'; };24 unmodified linesmodified:test/express.json.js+209 added-108 removed
1 'use strict'2 3 var assert = require('assert')4+var asyncHooks = tryRequire('async_hooks')5 var Buffer = require('safe-buffer').Buffer6 var express = require('..')7 var request = require('supertest')8 9+var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function'10+ ? describe11+ : describe.skip12+13 describe('express.json()', function () {14 it('should parse JSON', function (done) {15 request(createApp())16 .post('/')25 unmodified lines42 .unset('Transfer-Encoding')43 .expect(200, '{}', done)44 })45 46+ // 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+ })54+55 it('should 400 when invalid content-length', function (done) {56 var app = express()57 58 app.use(function (req, res, next) {40 unmodified lines99 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 })105 106 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 })113 100- 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- })108-114 it('should include original body on error object', function (done) {115 request(this.app)116 .post('/')117 .set('Content-Type', 'application/json')10 unmodified lines128 .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 })134 130- 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- })140-135 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 })145 146+ 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+ })154+155 it('should accept number of bytes', function (done) {156 var buf = Buffer.alloc(1024, '.')157 request(createApp({ limit: 1024 }))158 .post('/')4 unmodified lines163 164 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)168 169 options.limit = '100kb'170 168- 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 })177 178 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 })188+189+ 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 })198 199 describe('with inflate option', function () {200 describe('when false', function () {5 unmodified lines206 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 })213 214 describe('when true', function () {21 unmodified lines236 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 })243 244 describe('when false', function () {19 unmodified lines264 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 })270 271 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 })278 279 it('should allow leading whitespaces in JSON', function (done) {280 request(this.app)2 unmodified lines283 .send(' { "user": "tobi" }')284 .expect(200, '{"user":"tobi"}', done)285 })286 275- 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- })283-287 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 lines399 /TypeError: option verify must be function/)400 })401 402 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+ })408 409 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 })415 411- 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- } })415-416- 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- })423-416 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+ })425 426 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 })432 433 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+ })442 443 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 })449 450 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+ })456 457 request(app)458 .post('/')459 .set('Content-Type', 'application/json')2 unmodified lines462 .expect(403, '["tobi"]', done)463 })464 465 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+ })471 472 request(app)473 .post('/')474 .set('Content-Type', 'application/json')1 unmodified line476 .expect(200, '{"user":"tobi"}', done)477 })478 479 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+ })485 486 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 })491 492 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+ })498 499 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 })505 506+ describeAsyncHooks('async local storage', function () {507+ before(function () {508+ var app = express()509+ var store = { foo: 'bar' }510+511+ app.use(function (req, res, next) {512+ req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()513+ req.asyncLocalStorage.run(store, next)514+ })515+516+ app.use(express.json())517+518+ app.use(function (req, res, next) {519+ var local = req.asyncLocalStorage.getStore()520+521+ if (local) {522+ res.setHeader('x-store-foo', String(local.foo))523+ }524+525+ next()526+ })527+528+ app.use(function (err, req, res, next) {529+ var local = req.asyncLocalStorage.getStore()530+531+ if (local) {532+ res.setHeader('x-store-foo', String(local.foo))533+ }534+535+ res.status(err.status || 500)536+ res.send('[' + err.type + '] ' + err.message)537+ })538+539+ app.post('/', function (req, res) {540+ res.json(req.body)541+ })542+543+ this.app = app544+ })545+546+ 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+ })556+557+ 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+ })567+568+ 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+ })578+579+ 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+ })588+589+ 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+ })598+599+ 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+ })609+610 describe('charset', function () {611 before(function () {612 this.app = createApp()613 })30 unmodified lines644 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 })543-544- 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 })651 652 describe('encoding', function () {653 before(function () {43 unmodified lines697 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 })703 605- 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- })613-704 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 lines727 728 app.use(express.json(options))729 730 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 })737 738 app.post('/', function (req, res) {739 res.json(req.body)15 unmodified lines755 assert.ok(res.text.indexOf(str) !== -1,756 'expected \'' + res.text + '\' to contain \'' + str + '\'')757 }758 }759+760+function 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'2 3 var assert = require('assert')4+var asyncHooks = tryRequire('async_hooks')5 var Buffer = require('safe-buffer').Buffer6 var express = require('..')7 var request = require('supertest')8 9+var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function'10+ ? describe11+ : describe.skip12+13 describe('express.raw()', function () {14 before(function () {15 this.app = createApp()16 })89 unmodified lines106 test.write(buf)107 test.expect(413, done)108 })109 110+ 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+ })118+119 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 lines147 test.write(buf)148 test.write(buf)149 test.expect(413, done)150 })151+152+ 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 })161 162 describe('with inflate option', function () {163 describe('when false', function () {5 unmodified lines169 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 })176 177 describe('when true', function () {107 unmodified lines285 /TypeError: option verify must be function/)286 })287 288 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+ })294 295 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 })300 301 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+ })310 311 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 })316 317 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+ })323 324 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 })330 331+ describeAsyncHooks('async local storage', function () {332+ before(function () {333+ var app = express()334+ var store = { foo: 'bar' }335+336+ app.use(function (req, res, next) {337+ req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()338+ req.asyncLocalStorage.run(store, next)339+ })340+341+ app.use(express.raw())342+343+ app.use(function (req, res, next) {344+ var local = req.asyncLocalStorage.getStore()345+346+ if (local) {347+ res.setHeader('x-store-foo', String(local.foo))348+ }349+350+ next()351+ })352+353+ app.use(function (err, req, res, next) {354+ var local = req.asyncLocalStorage.getStore()355+356+ if (local) {357+ res.setHeader('x-store-foo', String(local.foo))358+ }359+360+ res.status(err.status || 500)361+ res.send('[' + err.type + '] ' + err.message)362+ })363+364+ 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+ })371+372+ this.app = app373+ })374+375+ 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+ })385+386+ 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+ })395+396+ 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+ })406+407+ 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+ })416+417+ 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+ })427+428 describe('charset', function () {429 before(function () {430 this.app = createApp()431 })49 unmodified lines481 test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))482 test.expect(200, { buf: '6e616d653de8aeba' }, done)483 })484 359- 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 lines498 app.use(express.raw(options))499 500 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 })506 507 app.post('/', function (req, res) {508 if (Buffer.isBuffer(req.body)) {4 unmodified lines513 })514 515 return app516 }517+518+function 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'2 3 var assert = require('assert')4+var asyncHooks = tryRequire('async_hooks')5 var Buffer = require('safe-buffer').Buffer6 var express = require('..')7 var request = require('supertest')8 9+var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function'10+ ? describe11+ : describe.skip12+13 describe('express.text()', function () {14 before(function () {15 this.app = createApp()16 })62 unmodified lines79 })80 81 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 })89 90 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 lines107 .expect(413, done)108 })109 110 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 })119 120+ 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+ })128+129 it('should accept number of bytes', function (done) {130 var buf = Buffer.alloc(1028, '.')131 request(createApp({ limit: 1024 }))132 .post('/')16 unmodified lines149 .expect(413, done)150 })151 152 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 })162+163+ 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 })174 175 describe('with inflate option', function () {176 describe('when false', function () {5 unmodified lines182 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 })189 190 describe('when true', function () {111 unmodified lines302 /TypeError: option verify must be function/)303 })304 305 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+ })311 312 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 })318 319 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+ })328 329 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 })335 336 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+ })342 343 request(app)344 .post('/')345 .set('Content-Type', 'text/plain')1 unmodified line347 .expect(200, '"user is tobi"', done)348 })349 350 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+ })356 357 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 })363 364+ describeAsyncHooks('async local storage', function () {365+ before(function () {366+ var app = express()367+ var store = { foo: 'bar' }368+369+ app.use(function (req, res, next) {370+ req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()371+ req.asyncLocalStorage.run(store, next)372+ })373+374+ app.use(express.text())375+376+ app.use(function (req, res, next) {377+ var local = req.asyncLocalStorage.getStore()378+379+ if (local) {380+ res.setHeader('x-store-foo', String(local.foo))381+ }382+383+ next()384+ })385+386+ app.use(function (err, req, res, next) {387+ var local = req.asyncLocalStorage.getStore()388+389+ if (local) {390+ res.setHeader('x-store-foo', String(local.foo))391+ }392+393+ res.status(err.status || 500)394+ res.send('[' + err.type + '] ' + err.message)395+ })396+397+ app.post('/', function (req, res) {398+ res.json(req.body)399+ })400+401+ this.app = app402+ })403+404+ 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+ })414+415+ 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+ })424+425+ 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+ })435+436+ 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+ })445+446+ 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+ })456+457 describe('charset', function () {458 before(function () {459 this.app = createApp()460 })30 unmodified lines491 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 })498 499 describe('encoding', function () {39 unmodified lines539 test.write(Buffer.from('1f8b080000000000000bcb4bcc4d55c82c5678b16e170072b3e0200b000000', 'hex'))540 test.expect(200, '"name is 论"', done)541 })542 417- 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 lines556 app.use(express.text(options))557 558 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 })564 565 app.post('/', function (req, res) {566 res.json(req.body)567 })568 569 return app570 }571+572+function 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'2 3 var assert = require('assert')4+var asyncHooks = tryRequire('async_hooks')5 var Buffer = require('safe-buffer').Buffer6 var express = require('..')7 var request = require('supertest')8 9+var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function'10+ ? describe11+ : describe.skip12+13 describe('express.urlencoded()', function () {14 before(function () {15 this.app = createApp()16 })204 unmodified lines221 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 })228 229 describe('when true', function () {22 unmodified lines252 .expect(413, done)253 })254 255 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 })265 266+ 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+ })274+275 it('should accept number of bytes', function (done) {276 var buf = Buffer.alloc(1024, '.')277 request(createApp({ limit: 1024 }))278 .post('/')16 unmodified lines295 .expect(413, done)296 })297 298 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 })308+309+ 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 })318 319 describe('with parameterLimit option', function () {320 describe('with extended: false', function () {11 unmodified lines332 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 })338 316- 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- })324-339 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 lines387 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 })393 380- 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- })388-394 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 lines530 /TypeError: option verify must be function/)531 })532 533 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+ })539 540 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 })546 540- 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- } })544-545- 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- })552-547 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+ })556 557 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 })563 564 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+ })573 574 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 })580 581 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+ })587 588 request(app)589 .post('/')590 .set('Content-Type', 'application/x-www-form-urlencoded')1 unmodified line592 .expect(200, '{"user":"tobi"}', done)593 })594 595 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+ })601 602 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 })608 609+ describeAsyncHooks('async local storage', function () {610+ before(function () {611+ var app = express()612+ var store = { foo: 'bar' }613+614+ app.use(function (req, res, next) {615+ req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()616+ req.asyncLocalStorage.run(store, next)617+ })618+619+ app.use(express.urlencoded())620+621+ app.use(function (req, res, next) {622+ var local = req.asyncLocalStorage.getStore()623+624+ if (local) {625+ res.setHeader('x-store-foo', String(local.foo))626+ }627+628+ next()629+ })630+631+ app.use(function (err, req, res, next) {632+ var local = req.asyncLocalStorage.getStore()633+634+ if (local) {635+ res.setHeader('x-store-foo', String(local.foo))636+ }637+638+ res.status(err.status || 500)639+ res.send('[' + err.type + '] ' + err.message)640+ })641+642+ app.post('/', function (req, res) {643+ res.json(req.body)644+ })645+646+ this.app = app647+ })648+649+ 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+ })659+660+ 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+ })669+670+ 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+ })680+681+ 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+ })690+691+ 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+ })701+702 describe('charset', function () {703 before(function () {704 this.app = createApp()705 })23 unmodified lines729 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 })736 737 describe('encoding', function () {39 unmodified lines777 test.write(Buffer.from('1f8b080000000000000bcb4bcc4db57db16e170099a4bad608000000', 'hex'))778 test.expect(200, '{"name":"论"}', done)779 })780 687- 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 lines811 app.use(express.urlencoded(options))812 813 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 })819 820 app.post('/', function (req, res) {821 res.json(req.body)6 unmodified lines828 return function (res) {829 assert.strictEqual(Object.keys(JSON.parse(res.text)).length, count)830 }831 }832+833+function 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 20modified:test/res.append.js+41 added-30 removed
1 'use strict'2 3+var assert = require('assert')4 var express = require('..')5 var request = require('supertest')5-var should = require('should')6 7 describe('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()11 12 app.use(function (req, res, next) {17- res.append('Link', '<http://localhost/>')13+ res.append('Set-Cookie', 'foo=bar')14 next()15 })16 17 app.use(function (req, res) {22- res.append('Link', '<http://localhost:80/>')18+ res.append('Set-Cookie', 'fizz=buzz')19 res.end()20 })21 22 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 })28 29 it('should accept array of values', function (done) {30 var app = express()3 unmodified lines34 res.end()35 })36 37 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 })43 44 it('should get reset by res.set(field, val)', function (done) {45 var app = express()46 47 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 })52 53 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 });57 58 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 })64 65 it('should work with res.set(field, val) first', function (done) {66 var app = express()67 68 app.use(function (req, res, next) {70- res.set('Link', '<http://localhost/>')69+ res.set('Set-Cookie', 'foo=bar')70 next()71 })72 73 app.use(function(req, res){75- res.append('Link', '<http://localhost:80/>')74+ res.append('Set-Cookie', 'fizz=buzz')75 res.end()76 })77 78 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 })84 84- it('should work with cookies', function (done) {85+ it('should work together with res.cookie', function (done) {86 var app = express()87 88 app.use(function (req, res, next) {89 res.cookie('foo', 'bar')90 next()91 })92 93 app.use(function (req, res) {93- res.append('Set-Cookie', 'bar=baz')94+ res.append('Set-Cookie', 'fizz=buzz')95 res.end()96 })97 98 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 })106+107+function 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 lines66 .expect('Set-Cookie', 'name=tobi; Path=/; HttpOnly; Secure')67 .expect(200, done)68 })69 70+ describe('expires', function () {71+ it('should throw on invalid date', function (done) {72+ var app = express()73+74+ app.use(function (req, res) {75+ res.cookie('name', 'tobi', { expires: new Date(NaN) })76+ res.end()77+ })78+79+ request(app)80+ .get('/')81+ .expect(500, /option expires is invalid/, done)82+ })83+ })84+85+ describe('partitioned', function () {86+ it('should set partitioned', function (done) {87+ var app = express();88+89+ app.use(function (req, res) {90+ res.cookie('name', 'tobi', { partitioned: true });91+ res.end();92+ });93+94+ request(app)95+ .get('/')96+ .expect('Set-Cookie', 'name=tobi; Path=/; Partitioned')97+ .expect(200, done)98+ })99+ })100+101 describe('maxAge', function(){102 it('should set relative expires', function(done){103 var app = express();104 36 unmodified lines141 .get('/')142 .expect(200, optionsCopy, done)143 })144 145+ it('should not throw on null', function (done) {146+ var app = express()147+148+ app.use(function (req, res) {149+ res.cookie('name', 'tobi', { maxAge: null })150+ res.end()151+ })152+153+ request(app)154+ .get('/')155+ .expect(200)156+ .expect('Set-Cookie', 'name=tobi; Path=/')157+ .end(done)158+ })159+160+ it('should not throw on undefined', function (done) {161+ var app = express()162+163+ app.use(function (req, res) {164+ res.cookie('name', 'tobi', { maxAge: undefined })165+ res.end()166+ })167+168+ request(app)169+ .get('/')170+ .expect(200)171+ .expect('Set-Cookie', 'name=tobi; Path=/')172+ .end(done)173+ })174+175 it('should throw an error with invalid maxAge', function (done) {176 var app = express()177 178 app.use(function (req, res) {6 unmodified lines185 .expect(500, /option maxAge is invalid/, done)186 })187 })188 189+ describe('priority', function () {190+ it('should set low priority', function (done) {191+ var app = express()192+193+ app.use(function (req, res) {194+ res.cookie('name', 'tobi', { priority: 'low' })195+ res.end()196+ })197+198+ request(app)199+ .get('/')200+ .expect('Set-Cookie', /Priority=Low/)201+ .expect(200, done)202+ })203+204+ it('should set medium priority', function (done) {205+ var app = express()206+207+ app.use(function (req, res) {208+ res.cookie('name', 'tobi', { priority: 'medium' })209+ res.end()210+ })211+212+ request(app)213+ .get('/')214+ .expect('Set-Cookie', /Priority=Medium/)215+ .expect(200, done)216+ })217+218+ it('should set high priority', function (done) {219+ var app = express()220+221+ app.use(function (req, res) {222+ res.cookie('name', 'tobi', { priority: 'high' })223+ res.end()224+ })225+226+ request(app)227+ .get('/')228+ .expect('Set-Cookie', /Priority=High/)229+ .expect(200, done)230+ })231+232+ it('should throw with invalid priority', function (done) {233+ var app = express()234+235+ app.use(function (req, res) {236+ res.cookie('name', 'tobi', { priority: 'foobar' })237+ res.end()238+ })239+240+ request(app)241+ .get('/')242+ .expect(500, /option priority is invalid/, done)243+ })244+ })245+246 describe('signed', function(){247 it('should generate a signed JSON cookie', function(done){248 var app = express();249 47 unmodified linesmodified:test/res.download.js+291 added-24 removed
1 'use strict'2 3 var after = require('after');4-var assert = require('assert');4+var assert = require('assert')5+var asyncHooks = tryRequire('async_hooks')6 var Buffer = require('safe-buffer').Buffer7 var express = require('..');8+var path = require('path')9 var request = require('supertest');10+var utils = require('./support/utils')11 12+var FIXTURES_PATH = path.join(__dirname, 'fixtures')13+14+var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function'15+ ? describe16+ : describe.skip17+18 describe('res', function(){19 describe('.download(path)', function(){20 it('should transfer as an attachment', function(done){21 var app = express();67 unmodified lines89 .expect('Content-Type', 'text/html; charset=utf-8')90 .expect('Content-Disposition', 'attachment; filename="user.html"')91 .expect(200, cb);92 })93+94+ 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' }99+100+ app.use(function (req, res, next) {101+ req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()102+ req.asyncLocalStorage.run(store, next)103+ })104+105+ app.use(function (req, res) {106+ res.download('test/fixtures/name.txt', function (err) {107+ if (err) return cb(err)108+109+ var local = req.asyncLocalStorage.getStore()110+111+ assert.strictEqual(local.foo, 'bar')112+ cb()113+ })114+ })115+116+ 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+ })122+123+ it('should presist store on error', function (done) {124+ var app = express()125+ var store = { foo: 'bar' }126+127+ app.use(function (req, res, next) {128+ req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()129+ req.asyncLocalStorage.run(store, next)130+ })131+132+ app.use(function (req, res) {133+ res.download('test/fixtures/does-not-exist', function (err) {134+ var local = req.asyncLocalStorage.getStore()135+136+ if (local) {137+ res.setHeader('x-store-foo', String(local.foo))138+ }139+140+ res.send(err ? 'got ' + err.status + ' error' : 'no error')141+ })142+ })143+144+ request(app)145+ .get('/')146+ .expect(200)147+ .expect('x-store-foo', 'bar')148+ .expect('got 404 error')149+ .end(done)150+ })151+ })152 })153 154+ describe('.download(path, options)', function () {155+ it('should allow options to res.sendFile()', function (done) {156+ var app = express()157+158+ app.use(function (req, res) {159+ res.download('test/fixtures/.name', {160+ dotfiles: 'allow',161+ maxAge: '4h'162+ })163+ })164+165+ 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+ })173+174+ describe('with "headers" option', function () {175+ it('should set headers on response', function (done) {176+ var app = express()177+178+ 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+ })186+187+ request(app)188+ .get('/')189+ .expect(200)190+ .expect('X-Foo', 'Bar')191+ .expect('X-Bar', 'Foo')192+ .end(done)193+ })194+195+ it('should use last header when duplicated', function (done) {196+ var app = express()197+198+ 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+ })206+207+ request(app)208+ .get('/')209+ .expect(200)210+ .expect('X-Foo', 'bar')211+ .end(done)212+ })213+214+ it('should override Content-Type', function (done) {215+ var app = express()216+217+ app.use(function (req, res) {218+ res.download('test/fixtures/user.html', {219+ headers: {220+ 'Content-Type': 'text/x-custom'221+ }222+ })223+ })224+225+ request(app)226+ .get('/')227+ .expect(200)228+ .expect('Content-Type', 'text/x-custom')229+ .end(done)230+ })231+232+ it('should not set headers on 404', function (done) {233+ var app = express()234+235+ app.use(function (req, res) {236+ res.download('test/fixtures/does-not-exist', {237+ headers: {238+ 'X-Foo': 'Bar'239+ }240+ })241+ })242+243+ request(app)244+ .get('/')245+ .expect(404)246+ .expect(utils.shouldNotHaveHeader('X-Foo'))247+ .end(done)248+ })249+250+ describe('when headers contains Content-Disposition', function () {251+ it('should be ignored', function (done) {252+ var app = express()253+254+ app.use(function (req, res) {255+ res.download('test/fixtures/user.html', {256+ headers: {257+ 'Content-Disposition': 'inline'258+ }259+ })260+ })261+262+ request(app)263+ .get('/')264+ .expect(200)265+ .expect('Content-Disposition', 'attachment; filename="user.html"')266+ .end(done)267+ })268+269+ it('should be ignored case-insensitively', function (done) {270+ var app = express()271+272+ app.use(function (req, res) {273+ res.download('test/fixtures/user.html', {274+ headers: {275+ 'content-disposition': 'inline'276+ }277+ })278+ })279+280+ request(app)281+ .get('/')282+ .expect(200)283+ .expect('Content-Disposition', 'attachment; filename="user.html"')284+ .end(done)285+ })286+ })287+ })288+289+ describe('with "root" option', function () {290+ it('should allow relative path', function (done) {291+ var app = express()292+293+ app.use(function (req, res) {294+ res.download('name.txt', {295+ root: FIXTURES_PATH296+ })297+ })298+299+ 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+ })306+307+ it('should allow up within root', function (done) {308+ var app = express()309+310+ app.use(function (req, res) {311+ res.download('fake/../name.txt', {312+ root: FIXTURES_PATH313+ })314+ })315+316+ 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+ })323+324+ it('should reject up outside root', function (done) {325+ var app = express()326+327+ app.use(function (req, res) {328+ var p = '..' + path.sep +329+ path.relative(path.dirname(FIXTURES_PATH), path.join(FIXTURES_PATH, 'name.txt'))330+331+ res.download(p, {332+ root: FIXTURES_PATH333+ })334+ })335+336+ request(app)337+ .get('/')338+ .expect(403)339+ .expect(utils.shouldNotHaveHeader('Content-Disposition'))340+ .end(done)341+ })342+343+ it('should reject reading outside root', function (done) {344+ var app = express()345+346+ app.use(function (req, res) {347+ res.download('../name.txt', {348+ root: FIXTURES_PATH349+ })350+ })351+352+ request(app)353+ .get('/')354+ .expect(403)355+ .expect(utils.shouldNotHaveHeader('Content-Disposition'))356+ .end(done)357+ })358+ })359+ })360+361 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 lines381 var cb = after(2, done)382 var options = {}383 384 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 })387 388 request(app)389 .get('/')13 unmodified lines403 })404 })405 406 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 })414 415 describe('when options.headers contains Content-Disposition', function () {416 it('should be ignored', function (done) {64 unmodified lines481 });482 });483 484 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 })491 217-function 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'))492+function tryRequire (name) {493+ try {494+ return require(name)495+ } catch (e) {496+ return {}497 }498 }226-227-function 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 lines51 52 app3.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 });63 64 var app4 = express();65 61-app4.get('/', function(req, res, next){66+app4.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 lines126 .get('/')127 .set('Accept', '*/*')128 .expect('hey', done);129 })130+131+ it('should be able to invoke other formatter', function (done) {132+ var app = express()133+134+ 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+ })143+144+ 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 })153 154 describe('in router', function(){155 test(app4);2 unmodified lines158 describe('in router', function(){159 var app = express();160 var router = express.Router();161 135- 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 linesmodified:test/res.location.js+45 added-1 removed
1 'use strict'2 3 var express = require('../')4- , request = require('supertest');4+ , request = require('supertest')5+ , url = require('url');6 7 describe('res', function(){8 describe('.location(url)', function(){9 it('should set the header', function(done){10 var app = express();11 12 app.use(function(req, res){13+ res.location('http://google.com/').end();14+ });15+16+ request(app)17+ .get('/')18+ .expect('Location', 'http://google.com/')19+ .expect(200, done)20+ })21+22+ it('should preserve trailing slashes when not present', function(done){23+ var app = express();24+25+ app.use(function(req, res){26 res.location('http://google.com').end();27 });28 29 request(app)14 unmodified lines44 .expect('Location', 'https://google.com?q=%E2%98%83%20%C2%A710')45 .expect(200, done)46 })47 48+ it('should not encode bad "url"', function (done) {49+ var app = express()50+51+ 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+ });59+60+ 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+ }68+69+ // 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+ });77+78 it('should not touch already-encoded sequences in "url"', function (done) {79 var app = express()80 81 app.use(function (req, res) {68 unmodified linesmodified:test/res.redirect.js+13 added-20 removed
1 'use strict'2 3-var assert = require('assert')3 var express = require('..');4 var request = require('supertest');5 var utils = require('./support/utils');6 62 unmodified lines69 res.redirect('http://google.com');70 });71 72 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 })80 81 describe('when accepting html', function(){100 unmodified lines182 res.redirect('http://google.com');183 });184 185 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 })198-199-function 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 lines142 res.send(Buffer.from('hello'))143 });144 145 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 })152 153 it('should set ETag', function (done) {154 var app = express();58 unmodified lines213 res.send('yay');214 });215 216 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 })223 224 describe('when .statusCode is 204', function(){12 unmodified lines237 .expect(204, '', done);238 })239 })240 241+ describe('when .statusCode is 205', function () {242+ it('should strip Transfer-Encoding field and body, set Content-Length', function (done) {243+ var app = express()244+245+ app.use(function (req, res) {246+ res.status(205).set('Transfer-Encoding', 'chunked').send('foo')247+ })248+249+ request(app)250+ .get('/')251+ .expect(utils.shouldNotHaveHeader('Transfer-Encoding'))252+ .expect('Content-Length', '0')253+ .expect(205, '', done)254+ })255+ })256+257 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 lines548 })549 })550 })551 })536-537-function 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-}546-547-function 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'2 3 var after = require('after');4 var assert = require('assert')5+var asyncHooks = tryRequire('async_hooks')6 var Buffer = require('safe-buffer').Buffer7 var express = require('../')8 , request = require('supertest')9 var onFinished = require('on-finished');10 var path = require('path');10-var should = require('should');11 var fixtures = path.join(__dirname, 'fixtures');12 var utils = require('./support/utils');13 14+var describeAsyncHooks = typeof asyncHooks.AsyncLocalStorage === 'function'15+ ? describe16+ : describe.skip17+18 describe('res', function(){19 describe('.sendFile(path)', function () {20 it('should error missing path', function (done) {21 var app = createApp();10 unmodified lines32 .get('/')33 .expect(500, /TypeError: path must be a string to res.sendFile/, done)34 })35 36+ it('should error for non-absolute path', function (done) {37+ var app = createApp('name.txt')38+39+ request(app)40+ .get('/')41+ .expect(500, /TypeError: path must be absolute/, done)42+ })43+44 it('should transfer a file', function (done) {45 var app = createApp(path.resolve(fixtures, 'name.txt'));46 47 request(app)54 unmodified lines102 .get('/')103 .expect(404, done);104 });105 106+ it('should send cache-control by default', function (done) {107+ var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'))108+109+ request(app)110+ .get('/')111+ .expect('Cache-Control', 'public, max-age=0')112+ .expect(200, done)113+ })114+115+ it('should not serve dotfiles by default', function (done) {116+ var app = createApp(path.resolve(__dirname, 'fixtures/.name'))117+118+ request(app)119+ .get('/')120+ .expect(404, done)121+ })122+123 it('should not override manual content-types', function (done) {124 var app = express();125 126 app.use(function (req, res) {33 unmodified lines160 assert.ok(err)161 server.close(cb)162 })163 })135-136- describe('with "cacheControl" option', function () {137- it('should enable cacheControl by default', function (done) {138- var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'))139-140- request(app)141- .get('/')142- .expect('Cache-Control', 'public, max-age=0')143- .expect(200, done)144- })145-146- it('should accept cacheControl option', function (done) {147- var app = createApp(path.resolve(__dirname, 'fixtures/name.txt'), { cacheControl: false })148-149- request(app)150- .get('/')151- .expect(utils.shouldNotHaveHeader('Cache-Control'))152- .expect(200, done)153- })154- })155-156- describe('with "dotfiles" option', function () {157- it('should not serve dotfiles by default', function (done) {158- var app = createApp(path.resolve(__dirname, 'fixtures/.name'));159-160- request(app)161- .get('/')162- .expect(404, done);163- });164-165- it('should accept dotfiles option', function(done){166- var app = createApp(path.resolve(__dirname, 'fixtures/.name'), { dotfiles: 'allow' });167-168- request(app)169- .get('/')170- .expect(200)171- .expect(shouldHaveBody(Buffer.from('tobi')))172- .end(done)173- });174- });175-176- 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 });183-184- request(app)185- .get('/')186- .expect('x-success', 'sent')187- .expect('x-other', 'done')188- .expect(200, done);189- });190-191- 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 });194-195- request(app)196- .get('/')197- .expect(utils.shouldNotHaveHeader('X-Success'))198- .expect(404, done);199- });200- });201-202- 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- })208-209- request(app)210- .get('/')211- .expect('Cache-Control', 'public, max-age=14400, immutable')212- .expect(200, done)213- })214- })215-216- 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- })221-222- request(app)223- .get('/')224- .expect('Cache-Control', 'public, max-age=14400')225- .expect(200, done)226- })227-228- 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- })232-233- request(app)234- .get('/')235- .expect('Cache-Control', 'public, max-age=14400')236- .expect(200, done)237- })238- })239-240- describe('with "root" option', function () {241- it('should not transfer relative with without', function (done) {242- var app = createApp('test/fixtures/name.txt');243-244- request(app)245- .get('/')246- .expect(500, /must be absolute/, done);247- })248-249- it('should serve relative to "root"', function (done) {250- var app = createApp('name.txt', {root: fixtures});251-252- request(app)253- .get('/')254- .expect(200, 'tobi', done);255- })256-257- it('should disallow requesting out of "root"', function (done) {258- var app = createApp('foo/../../user.html', {root: fixtures});259-260- request(app)261- .get('/')262- .expect(403, done);263- })264- })164 })165 166 describe('.sendFile(path, fn)', function () {167 it('should invoke the callback when complete', function (done) {89 unmodified lines257 var app = express();258 259 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 });264 265 request(app)369- .get('/')370- .expect(200, 'got it', done);266+ .get('/')267+ .expect(200, 'got 404 error', done)268 })269+270+ 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' }275+276+ app.use(function (req, res, next) {277+ req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()278+ req.asyncLocalStorage.run(store, next)279+ })280+281+ app.use(function (req, res) {282+ res.sendFile(path.resolve(fixtures, 'name.txt'), function (err) {283+ if (err) return cb(err)284+285+ var local = req.asyncLocalStorage.getStore()286+287+ assert.strictEqual(local.foo, 'bar')288+ cb()289+ })290+ })291+292+ request(app)293+ .get('/')294+ .expect('Content-Type', 'text/plain; charset=utf-8')295+ .expect(200, 'tobi', cb)296+ })297+298+ it('should presist store on error', function (done) {299+ var app = express()300+ var store = { foo: 'bar' }301+302+ app.use(function (req, res, next) {303+ req.asyncLocalStorage = new asyncHooks.AsyncLocalStorage()304+ req.asyncLocalStorage.run(store, next)305+ })306+307+ app.use(function (req, res) {308+ res.sendFile(path.resolve(fixtures, 'does-not-exist'), function (err) {309+ var local = req.asyncLocalStorage.getStore()310+311+ if (local) {312+ res.setHeader('x-store-foo', String(local.foo))313+ }314+315+ res.send(err ? 'got ' + err.status + ' error' : 'no error')316+ })317+ })318+319+ request(app)320+ .get('/')321+ .expect(200)322+ .expect('x-store-foo', 'bar')323+ .expect('got 404 error')324+ .end(done)325+ })326+ })327 })328 329 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 })335+336+ describe('with "acceptRanges" option', function () {337+ describe('when true', function () {338+ it('should advertise byte range accepted', function (done) {339+ var app = express()340+341+ app.use(function (req, res) {342+ res.sendFile(path.resolve(fixtures, 'nums.txt'), {343+ acceptRanges: true344+ })345+ })346+347+ request(app)348+ .get('/')349+ .expect(200)350+ .expect('Accept-Ranges', 'bytes')351+ .expect('123456789')352+ .end(done)353+ })354+355+ it('should respond to range request', function (done) {356+ var app = express()357+358+ app.use(function (req, res) {359+ res.sendFile(path.resolve(fixtures, 'nums.txt'), {360+ acceptRanges: true361+ })362+ })363+364+ request(app)365+ .get('/')366+ .set('Range', 'bytes=0-4')367+ .expect(206, '12345', done)368+ })369+ })370+371+ describe('when false', function () {372+ it('should not advertise accept-ranges', function (done) {373+ var app = express()374+375+ app.use(function (req, res) {376+ res.sendFile(path.resolve(fixtures, 'nums.txt'), {377+ acceptRanges: false378+ })379+ })380+381+ request(app)382+ .get('/')383+ .expect(200)384+ .expect(utils.shouldNotHaveHeader('Accept-Ranges'))385+ .end(done)386+ })387+388+ it('should not honor range requests', function (done) {389+ var app = express()390+391+ app.use(function (req, res) {392+ res.sendFile(path.resolve(fixtures, 'nums.txt'), {393+ acceptRanges: false394+ })395+ })396+397+ request(app)398+ .get('/')399+ .set('Range', 'bytes=0-4')400+ .expect(200, '123456789', done)401+ })402+ })403+ })404+405+ describe('with "cacheControl" option', function () {406+ describe('when true', function () {407+ it('should send cache-control header', function (done) {408+ var app = express()409+410+ app.use(function (req, res) {411+ res.sendFile(path.resolve(fixtures, 'user.html'), {412+ cacheControl: true413+ })414+ })415+416+ request(app)417+ .get('/')418+ .expect(200)419+ .expect('Cache-Control', 'public, max-age=0')420+ .end(done)421+ })422+ })423+424+ describe('when false', function () {425+ it('should not send cache-control header', function (done) {426+ var app = express()427+428+ app.use(function (req, res) {429+ res.sendFile(path.resolve(fixtures, 'user.html'), {430+ cacheControl: false431+ })432+ })433+434+ request(app)435+ .get('/')436+ .expect(200)437+ .expect(utils.shouldNotHaveHeader('Cache-Control'))438+ .end(done)439+ })440+ })441+ })442+443+ describe('with "dotfiles" option', function () {444+ describe('when "allow"', function () {445+ it('should allow dotfiles', function (done) {446+ var app = express()447+448+ app.use(function (req, res) {449+ res.sendFile(path.resolve(fixtures, '.name'), {450+ dotfiles: 'allow'451+ })452+ })453+454+ request(app)455+ .get('/')456+ .expect(200)457+ .expect(utils.shouldHaveBody(Buffer.from('tobi')))458+ .end(done)459+ })460+ })461+462+ describe('when "deny"', function () {463+ it('should deny dotfiles', function (done) {464+ var app = express()465+466+ app.use(function (req, res) {467+ res.sendFile(path.resolve(fixtures, '.name'), {468+ dotfiles: 'deny'469+ })470+ })471+472+ request(app)473+ .get('/')474+ .expect(403)475+ .expect(/Forbidden/)476+ .end(done)477+ })478+ })479+480+ describe('when "ignore"', function () {481+ it('should ignore dotfiles', function (done) {482+ var app = express()483+484+ app.use(function (req, res) {485+ res.sendFile(path.resolve(fixtures, '.name'), {486+ dotfiles: 'ignore'487+ })488+ })489+490+ request(app)491+ .get('/')492+ .expect(404)493+ .expect(/Not Found/)494+ .end(done)495+ })496+ })497+ })498+499+ describe('with "headers" option', function () {500+ it('should set headers on response', function (done) {501+ var app = express()502+503+ 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+ })511+512+ request(app)513+ .get('/')514+ .expect(200)515+ .expect('X-Foo', 'Bar')516+ .expect('X-Bar', 'Foo')517+ .end(done)518+ })519+520+ it('should use last header when duplicated', function (done) {521+ var app = express()522+523+ 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+ })531+532+ request(app)533+ .get('/')534+ .expect(200)535+ .expect('X-Foo', 'bar')536+ .end(done)537+ })538+539+ it('should override Content-Type', function (done) {540+ var app = express()541+542+ app.use(function (req, res) {543+ res.sendFile(path.resolve(fixtures, 'user.html'), {544+ headers: {545+ 'Content-Type': 'text/x-custom'546+ }547+ })548+ })549+550+ request(app)551+ .get('/')552+ .expect(200)553+ .expect('Content-Type', 'text/x-custom')554+ .end(done)555+ })556+557+ it('should not set headers on 404', function (done) {558+ var app = express()559+560+ app.use(function (req, res) {561+ res.sendFile(path.resolve(fixtures, 'does-not-exist'), {562+ headers: {563+ 'X-Foo': 'Bar'564+ }565+ })566+ })567+568+ request(app)569+ .get('/')570+ .expect(404)571+ .expect(utils.shouldNotHaveHeader('X-Foo'))572+ .end(done)573+ })574+ })575+576+ 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()580+581+ app.use(function (req, res) {582+ res.sendFile(path.resolve(fixtures, 'user.html'), {583+ immutable: true584+ })585+ })586+587+ request(app)588+ .get('/')589+ .expect(200)590+ .expect('Cache-Control', 'public, max-age=0, immutable')591+ .end(done)592+ })593+ })594+595+ describe('when false', function () {596+ it('should not send cache-control header with immutable', function (done) {597+ var app = express()598+599+ app.use(function (req, res) {600+ res.sendFile(path.resolve(fixtures, 'user.html'), {601+ immutable: false602+ })603+ })604+605+ request(app)606+ .get('/')607+ .expect(200)608+ .expect('Cache-Control', 'public, max-age=0')609+ .end(done)610+ })611+ })612+ })613+614+ describe('with "lastModified" option', function () {615+ describe('when true', function () {616+ it('should send last-modified header', function (done) {617+ var app = express()618+619+ app.use(function (req, res) {620+ res.sendFile(path.resolve(fixtures, 'user.html'), {621+ lastModified: true622+ })623+ })624+625+ request(app)626+ .get('/')627+ .expect(200)628+ .expect(utils.shouldHaveHeader('Last-Modified'))629+ .end(done)630+ })631+632+ it('should conditionally respond with if-modified-since', function (done) {633+ var app = express()634+635+ app.use(function (req, res) {636+ res.sendFile(path.resolve(fixtures, 'user.html'), {637+ lastModified: true638+ })639+ })640+641+ request(app)642+ .get('/')643+ .set('If-Modified-Since', (new Date(Date.now() + 99999).toUTCString()))644+ .expect(304, done)645+ })646+ })647+648+ describe('when false', function () {649+ it('should not have last-modified header', function (done) {650+ var app = express()651+652+ app.use(function (req, res) {653+ res.sendFile(path.resolve(fixtures, 'user.html'), {654+ lastModified: false655+ })656+ })657+658+ request(app)659+ .get('/')660+ .expect(200)661+ .expect(utils.shouldNotHaveHeader('Last-Modified'))662+ .end(done)663+ })664+665+ it('should not honor if-modified-since', function (done) {666+ var app = express()667+668+ app.use(function (req, res) {669+ res.sendFile(path.resolve(fixtures, 'user.html'), {670+ lastModified: false671+ })672+ })673+674+ 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+ })683+684+ describe('with "maxAge" option', function () {685+ it('should set cache-control max-age to milliseconds', function (done) {686+ var app = express()687+688+ app.use(function (req, res) {689+ res.sendFile(path.resolve(fixtures, 'user.html'), {690+ maxAge: 20000691+ })692+ })693+694+ request(app)695+ .get('/')696+ .expect(200)697+ .expect('Cache-Control', 'public, max-age=20')698+ .end(done)699+ })700+701+ it('should cap cache-control max-age to 1 year', function (done) {702+ var app = express()703+704+ app.use(function (req, res) {705+ res.sendFile(path.resolve(fixtures, 'user.html'), {706+ maxAge: 99999999999707+ })708+ })709+710+ request(app)711+ .get('/')712+ .expect(200)713+ .expect('Cache-Control', 'public, max-age=31536000')714+ .end(done)715+ })716+717+ it('should min cache-control max-age to 0', function (done) {718+ var app = express()719+720+ app.use(function (req, res) {721+ res.sendFile(path.resolve(fixtures, 'user.html'), {722+ maxAge: -20000723+ })724+ })725+726+ request(app)727+ .get('/')728+ .expect(200)729+ .expect('Cache-Control', 'public, max-age=0')730+ .end(done)731+ })732+733+ it('should floor cache-control max-age', function (done) {734+ var app = express()735+736+ app.use(function (req, res) {737+ res.sendFile(path.resolve(fixtures, 'user.html'), {738+ maxAge: 21911.23739+ })740+ })741+742+ request(app)743+ .get('/')744+ .expect(200)745+ .expect('Cache-Control', 'public, max-age=21')746+ .end(done)747+ })748+749+ describe('when cacheControl: false', function () {750+ it('should not send cache-control', function (done) {751+ var app = express()752+753+ app.use(function (req, res) {754+ res.sendFile(path.resolve(fixtures, 'user.html'), {755+ cacheControl: false,756+ maxAge: 20000757+ })758+ })759+760+ request(app)761+ .get('/')762+ .expect(200)763+ .expect(utils.shouldNotHaveHeader('Cache-Control'))764+ .end(done)765+ })766+ })767+768+ describe('when string', function () {769+ it('should accept plain number as milliseconds', function (done) {770+ var app = express()771+772+ app.use(function (req, res) {773+ res.sendFile(path.resolve(fixtures, 'user.html'), {774+ maxAge: '20000'775+ })776+ })777+778+ request(app)779+ .get('/')780+ .expect(200)781+ .expect('Cache-Control', 'public, max-age=20')782+ .end(done)783+ })784+785+ it('should accept suffix "s" for seconds', function (done) {786+ var app = express()787+788+ app.use(function (req, res) {789+ res.sendFile(path.resolve(fixtures, 'user.html'), {790+ maxAge: '20s'791+ })792+ })793+794+ request(app)795+ .get('/')796+ .expect(200)797+ .expect('Cache-Control', 'public, max-age=20')798+ .end(done)799+ })800+801+ it('should accept suffix "m" for minutes', function (done) {802+ var app = express()803+804+ app.use(function (req, res) {805+ res.sendFile(path.resolve(fixtures, 'user.html'), {806+ maxAge: '20m'807+ })808+ })809+810+ request(app)811+ .get('/')812+ .expect(200)813+ .expect('Cache-Control', 'public, max-age=1200')814+ .end(done)815+ })816+817+ it('should accept suffix "d" for days', function (done) {818+ var app = express()819+820+ app.use(function (req, res) {821+ res.sendFile(path.resolve(fixtures, 'user.html'), {822+ maxAge: '20d'823+ })824+ })825+826+ request(app)827+ .get('/')828+ .expect(200)829+ .expect('Cache-Control', 'public, max-age=1728000')830+ .end(done)831+ })832+ })833+ })834+835+ describe('with "root" option', function () {836+ it('should allow relative path', function (done) {837+ var app = express()838+839+ app.use(function (req, res) {840+ res.sendFile('name.txt', {841+ root: fixtures842+ })843+ })844+845+ request(app)846+ .get('/')847+ .expect(200, 'tobi', done)848+ })849+850+ it('should allow up within root', function (done) {851+ var app = express()852+853+ app.use(function (req, res) {854+ res.sendFile('fake/../name.txt', {855+ root: fixtures856+ })857+ })858+859+ request(app)860+ .get('/')861+ .expect(200, 'tobi', done)862+ })863+864+ it('should reject up outside root', function (done) {865+ var app = express()866+867+ app.use(function (req, res) {868+ res.sendFile('..' + path.sep + path.relative(path.dirname(fixtures), path.join(fixtures, 'name.txt')), {869+ root: fixtures870+ })871+ })872+873+ request(app)874+ .get('/')875+ .expect(403, done)876+ })877+878+ it('should reject reading outside root', function (done) {879+ var app = express()880+881+ app.use(function (req, res) {882+ res.sendFile('../name.txt', {883+ root: fixtures884+ })885+ })886+887+ request(app)888+ .get('/')889+ .expect(403, done)890+ })891+ })892 })893 })894 895 function createApp(path, options, fn) {5 unmodified lines901 902 return app;903 }904 393-function 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'))905+function 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'2 3 var express = require('../')4- , request = require('supertest');4+var request = require('supertest')5 6-describe('res', function(){7- describe('.status(code)', function(){8- it('should set the response .statusCode', function(done){9- var app = express();6+var isIoJs = process.release7+ ? process.release.name === 'io.js'8+ : ['v1.', 'v2.', 'v3.'].indexOf(process.version.slice(0, 3)) !== -19 11- app.use(function(req, res){12- res.status(201).end('Created');13- });10+describe('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()15 16+ app.use(function (req, res) {17+ res.status(undefined).end()18+ })19+15- 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 })31+32+ describe('when "code" is null', function () {33+ it('should raise error for invalid status code', function (done) {34+ var app = express()35+36+ app.use(function (req, res) {37+ res.status(null).end()38+ })39+40+ 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+ })51+52+ describe('when "code" is 201', function () {53+ it('should set the response status code to 201', function (done) {54+ var app = express()55+56+ app.use(function (req, res) {57+ res.status(201).end()58+ })59+60+ request(app)61+ .get('/')62+ .expect(201, done)63+ })64+ })65+66+ describe('when "code" is 302', function () {67+ it('should set the response status code to 302', function (done) {68+ var app = express()69+70+ app.use(function (req, res) {71+ res.status(302).end()72+ })73+74+ request(app)75+ .get('/')76+ .expect(302, done)77+ })78+ })79+80+ describe('when "code" is 403', function () {81+ it('should set the response status code to 403', function (done) {82+ var app = express()83+84+ app.use(function (req, res) {85+ res.status(403).end()86+ })87+88+ request(app)89+ .get('/')90+ .expect(403, done)91+ })92+ })93+94+ describe('when "code" is 501', function () {95+ it('should set the response status code to 501', function (done) {96+ var app = express()97+98+ app.use(function (req, res) {99+ res.status(501).end()100+ })101+102+ request(app)103+ .get('/')104+ .expect(501, done)105+ })106+ })107+108+ describe('when "code" is "410"', function () {109+ it('should set the response status code to 410', function (done) {110+ var app = express()111+112+ app.use(function (req, res) {113+ res.status('410').end()114+ })115+116+ request(app)117+ .get('/')118+ .expect(410, done)119+ })120+ })121+122+ describe('when "code" is 410.1', function () {123+ it('should set the response status code to 410', function (done) {124+ var app = express()125+126+ app.use(function (req, res) {127+ res.status(410.1).end()128+ })129+130+ 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+ })141+142+ describe('when "code" is 1000', function () {143+ it('should raise error for invalid status code', function (done) {144+ var app = express()145+146+ app.use(function (req, res) {147+ res.status(1000).end()148+ })149+150+ 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+ })161+162+ describe('when "code" is 99', function () {163+ it('should raise error for invalid status code', function (done) {164+ var app = express()165+166+ app.use(function (req, res) {167+ res.status(99).end()168+ })169+170+ 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+ })181+182+ describe('when "code" is -401', function () {183+ it('should raise error for invalid status code', function (done) {184+ var app = express()185+186+ app.use(function (req, res) {187+ res.status(-401).end()188+ })189+190+ 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'2 3 var after = require('after');4-var should = require('should');4+var assert = require('assert')5 var express = require('../')6 , Route = express.Route7 , methods = require('methods')8 3 unmodified lines12 var route = new Route('/foo')13 route.dispatch(req, {}, done)14 })15 16+ it('should not stack overflow with a large sync stack', function (done) {17+ this.timeout(5000) // long-running test18+19+ var req = { method: 'GET', url: '/' }20+ var route = new Route('/foo')21+22+ route.get(function (req, res, next) {23+ req.counter = 024+ next()25+ })26+27+ for (var i = 0; i < 6000; i++) {28+ route.all(function (req, res, next) {29+ req.counter++30+ next()31+ })32+ }33+34+ route.get(function (req, res, next) {35+ req.called = true36+ next()37+ })38+39+ 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+ })46+47 describe('.all', function(){48 it('should add handler', function(done){49 var req = { method: 'GET', url: '/' };50 var route = new Route('/foo');4 unmodified lines55 });56 57 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 line65 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 });72 73 route.all(function(req, res, next) {22 unmodified lines96 });97 98 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 lines114 })115 116 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 })122 123 it('should limit to just .VERB', function(done){124 var req = { method: 'POST', url: '/' };125 var route = new Route('');126 96- route.get(function(req, res, next) {127+ route.get(function () {128 throw new Error('not me!');129 })130 131 route.post(function(req, res, next) {2 unmodified lines134 })135 136 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 lines160 })161 162 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 lines186 next(err);187 });188 189 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 })196 197 it('should handle throw', function(done) {198 var req = { order: '', method: 'GET', url: '/' };199 var route = new Route('');200 170- route.all(function(req, res, next){201+ route.all(function () {202 throw new Error('foobar');203 });204 205 route.all(function(req, res, next){6 unmodified lines212 next(err);213 });214 215 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 });222 223 it('should handle throwing inside error handlers', function(done) {224 var req = { method: 'GET', url: '/' };225 var route = new Route('');226 196- route.get(function(req, res, next){227+ route.get(function () {228 throw new Error('boom!');229 });230 231 route.get(function(err, req, res, next){6 unmodified lines238 });239 240 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 lines252 throw new Error('boom!');253 });254 255 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 lines264 var route = new Route('');265 266 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 });270 271 route.dispatch(req, {}, done);272 });2 unmodified linesmodified:test/Router.js+87 added-4 removed
59 unmodified lines60 61 router.handle({ method: 'GET' }, {}, done)62 })63 64+ it('handle missing method', function (done) {65+ var all = false66+ var router = new Router()67+ var route = router.route('/foo')68+ var use = false69+70+ 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')) })76+77+ 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+ })82+83+ router.handle({ url: '/foo' }, {}, function (err) {84+ if (err) return done(err)85+ assert.ok(all)86+ assert.ok(use)87+ done()88+ })89+ })90+91 it('should not stack overflow with many registered routes', function(done){92+ this.timeout(5000) // long-running test93+94 var handler = function(req, res){ res.end(new Error('wrong handler')) };95 var router = new Router();96 97 for (var i = 0; i < 6000; i++) {6 unmodified lines104 105 router.handle({ url: '/', method: 'GET' }, { end: done }, function(){});106 });107 108+ it('should not stack overflow with a large sync route stack', function (done) {109+ this.timeout(5000) // long-running test110+111+ var router = new Router()112+113+ router.get('/foo', function (req, res, next) {114+ req.counter = 0115+ next()116+ })117+118+ for (var i = 0; i < 6000; i++) {119+ router.get('/foo', function (req, res, next) {120+ req.counter++121+ next()122+ })123+ }124+125+ router.get('/foo', function (req, res) {126+ assert.strictEqual(req.counter, 6000)127+ res.end()128+ })129+130+ router.handle({ url: '/foo', method: 'GET' }, { end: done }, function (err) {131+ assert(!err, err);132+ });133+ })134+135+ it('should not stack overflow with a large sync middleware stack', function (done) {136+ this.timeout(5000) // long-running test137+138+ var router = new Router()139+140+ router.use(function (req, res, next) {141+ req.counter = 0142+ next()143+ })144+145+ for (var i = 0; i < 6000; i++) {146+ router.use(function (req, res, next) {147+ req.counter++148+ next()149+ })150+ }151+152+ router.use(function (req, res) {153+ assert.strictEqual(req.counter, 6000)154+ res.end()155+ })156+157+ router.handle({ url: '/', method: 'GET' }, { end: done }, function (err) {158+ assert(!err, err);159+ })160+ })161+162 describe('.handle', function(){163 it('should dispatch', function(done){164 var router = new Router();165 65 unmodified lines231 232 it('should handle throwing inside routes with params', function(done) {233 var router = new Router();234 152- router.get('/foo/:id', function(req, res, next){235+ router.get('/foo/:id', function () {236 throw new Error('foo');237 });238 239 router.use(function(req, res, next){361 unmodified lines601 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)606 523- done = after(2, done);607 608 sub.get('/bar', function(req, res, next) {609 next();610 });10 unmodified lines621 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 });627 628 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 lines9 - 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"21 cache:22 - node_modules23 install: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-redis7 unmodified lines47 # - 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 linesmodified:Charter.md+2 added-2 removed
7 unmodified lines8 also easily visible to outsiders.9 10 ## Section 1: Scope11 12-Express is a http web server framework with a simple and expressive API12+Express is a HTTP web server framework with a simple and expressive API13 which is highly aligned with Node.js core. We aim to be the best in14 class for writing performant, spec compliant, and powerful web servers15 in Node.js. As one of the oldest and most popular web frameworks in16 the ecosystem, we have an important place for new users and experts6 unmodified lines23 - [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 libraries28 29 ### 1.2: Out-of-Scope30 31 Section Intentionally Left Blank61 unmodified linesmodified:Contributing.md+69 added-6 removed
10 unmodified lines11 ## Vocabulary12 13 * 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 technical17 expertise to resolve rare disputes.18 * A **Triager** is a subset of contributors who have been given triage access to the repository.19 82 unmodified lines102 If a consensus cannot be reached that has no objections then a majority wins vote103 is called. It is also expected that the majority of decisions made by the TC are via104 a consensus seeking process and that voting is only used as a last-resort.105 105-Resolution may involve returning the issue to committers with suggestions on how to106-move forward towards a consensus. It is not expected that a meeting of the TC106+Resolution may involve returning the issue to project captains with suggestions on107+how to move forward towards a consensus. It is not expected that a meeting of the TC108 will resolve all issues on its agenda during that meeting and may prefer to continue108-the discussion happening among the committers.109+the discussion happening among the project captains.110 110-Members can be added to the TC at any time. Any committer can nominate another committer111+Members can be added to the TC at any time. Any TC member can nominate another committer112 to the TC and the TC uses its standard consensus seeking process to evaluate whether or112-not to add this new member. Members who do not participate consistently at the level of113-a majority of the other members are expected to resign.113+not to add this new member. The TC will consist of a minimum of 3 active members and a114+maximum of 10. If the TC should drop below 5 members the active TC members should nominate115+someone new. If a TC member is stepping down, they are encouraged (but not required) to116+nominate someone to take their place.117+118+TC members will be added as admin's on the Github orgs, npm orgs, and other resources as119+necessary to be effective in the role.120+121+To remain "active" a TC member should have participation within the last 12 months and miss122+no more than six consecutive TC meetings. Our goal is to increase participation, not punish123+people 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 this125+are expected to step down. If A TC member does not step down, an issue can be opened in the126+discussions repo to move them to inactive status. TC members who step down or are removed due127+to inactivity will be moved into inactive status.128+129+Inactive status members can become active members by self nomination if the TC is not already130+larger than the maximum of 10. They will also be given preference if, while at max size, an131+active member steps down.132+133+## Project Captains134+135+The Express TC can designate captains for individual projects/repos in the136+organizations. These captains are responsible for being the primary137+day-to-day maintainers of the repo on a technical and community front.138+Repo captains are empowered with repo ownership and package publication rights.139+When there are conflicts, especially on topics that effect the Express project140+at large, captains are responsible to raise it up to the TC and drive141+those conflicts to resolution. Captains are also responsible for making sure142+community members follow the community guidelines, maintaining the repo143+and the published package, as well as in providing user support.144+145+Like TC members, Repo captains are a subset of committers.146+147+To become a captain for a project the candidate is expected to participate in that148+project for at least 6 months as a committer prior to the request. They should have149+helped with code contributions as well as triaging issues. They are also required to150+have 2FA enabled on both their GitHub and npm accounts. Any TC member or existing151+captain on the repo can nominate another committer to the captain role, submit a PR to152+this doc, under `Current Project Captains` section (maintaining the sort order) with153+the project, their GitHub handle and npm username (if different). The PR will require154+at least 2 approvals from TC members and 2 weeks hold time to allow for comment and/or155+dissent. When the PR is merged, a TC member will add them to the proper GitHub/npm groups.156+157+### Current Project Captains158+159+- `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 lines161 - `req.query` is now a getter instead of a plain property162 * add:163 - `app.router` is a reference to the base router164 165+4.18.3 / 2024-03-20166+==========167+168+ * Prevent open redirect allow list bypass due to encodeurl169+ * deps: cookie@0.6.0170+171+4.18.3 / 2024-02-29172+==========173+174+ * 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` option181+182+4.18.2 / 2022-10-08183+===================184+185+ * 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.0190+191+4.18.1 / 2022-04-29192+===================193+194+ * Fix hanging on large stack of sync routes195+196+4.18.0 / 2022-04-25197+===================198+199+ * 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`244+245 4.17.3 / 2022-02-16246 ===================247 248 * deps: accepts@~1.3.82042 unmodified lines2291 * 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.31202 unmodified lines3502 3503 * 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() changes3510 3511 0.12.0 / 2010-05-2226 unmodified lines3538 0.10.0 / 2010-04-303539 ==================3540 3541 * 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 #29730 unmodified lines3577 * 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 httpOnly184 unmodified linesmodified:package.json+16 added-18 removed
26 unmodified lines27 "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 line66 "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 linesmodified:Readme.md+42 added-34 removed
1 [](http://expressjs.com/)2 3- Fast, unopinionated, minimalist web framework for [node](http://nodejs.org).3+ Fast, unopinionated, minimalist web framework for [Node.js](http://nodejs.org).4 5- [![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]8 9 ```js10 const express = require('express')11 const app = express()18 unmodified lines30 31 Installation is done using the32 [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):33 36-```bash34+```console35 $ npm install express36 ```37 38 Follow [our installing guide](http://expressjs.com/en/starter/installing.html)11 unmodified lines50 51 ## Docs & Community52 53 * [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 discussion59 60 **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).61 64-### Security Issues65-66-If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md).67-62 ## Quick Start63 64 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:65 66 Install the executable. The executable's major version will match Express's:67 74-```bash68+```console69 $ npm install -g express-generator@470 ```71 72 Create the app:73 80-```bash74+```console75 $ express /tmp/foo && cd /tmp/foo76 ```77 78 Install dependencies:79 86-```bash80+```console81 $ npm install82 ```83 84 Start the server:85 92-```bash86+```console87 $ npm start88 ```89 90 View the website at: http://localhost:300011 unmodified lines102 ## Examples103 104 To view the examples, clone the Express repo and install the dependencies:105 112-```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 ```111 112 Then run whichever example you want:113 120-```bash114+```console115 $ node examples/content-negotiation116 ```117 124-## Tests118+## Contributing119 126- 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]123 128-```bash124+The Express.js project welcomes all constructive contributions. Contributions take many forms,125+from code for bug fixes and enhancements, to additions and fixes to documentation, additional126+tests, triaging incoming pull requests and issues, and more!127+128+See the [Contributing Guide](Contributing.md) for more technical details on contributing.129+130+### Security Issues131+132+If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md).133+134+### Running Tests135+136+To run the test suite, first install the dependencies, then run `npm test`:137+138+```console139 $ npm install140 $ npm test141 ```142 133-## Contributing134-135-[Contributing Guide](Contributing.md)136-143 ## People144 145 The original author of Express is [TJ Holowaychuk](https://github.com/tj)146 4 unmodified lines151 ## License152 153 [MIT](LICENSE)154 149-[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/expressmodified:Release-Process.md+6 added
182 unmodified lines183 ```184 185 **NOTE:** The version number to publish will be picked up automatically from186 package.json.187+ 188+### Step 7. Update documentation website189+190+The documentation website https://expressjs.com/ documents the current release version in various places. For a new release:191+1. 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.192+2. 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 lines26 endeavor to keep you informed of the progress towards a fix and full27 announcement, and may ask for additional information or guidance.28 29 Report security bugs in third-party modules to the person or team maintaining30-the module. You can also report a vulnerability through the31-[Node Security Project](https://nodesecurity.io/report).30+the module.31 32 ## Disclosure Policy33 34 When the security team receives a security bug report, they will assign it to a12 unmodified lines