Compare commits

..

394 Commits

Author SHA1 Message Date
Sebastian Beltran
3981e29545 fix(tests): correct spelling of 'throw' in error messages 2025-03-18 09:26:05 -05:00
Sebastian Beltran
f636741bf8 feat(res.redirect): add validation for url and status arguments 2025-03-18 09:21:25 -05:00
Sebastian Beltran
4a2175dfc9 fix dependabot config (#6392) 2025-03-16 17:44:57 -05:00
Ulises Gascón
0bb00e1906 ci: add dependabot (#5435)
Co-authored-by: Shivam Sharma <meshivam81@gmail.com>
Co-authored-by: Sebastian Beltran <bjohansebas@gmail.com>
2025-03-11 22:50:59 +01:00
Wes Todd
1e359f57fc fix(deps): qs@^6.14.0 (#6374) 2025-03-11 22:49:58 +01:00
Ulises Gascón
9cbe2c2cbb docs: add @dpopp07 to the triage team (#6352) 2025-03-11 22:49:08 +01:00
Sebastian Beltran
35e15362ab fix(docs): clarify guidelines for becoming a committer (#6364)
* docs: clarify guidelines for becoming a committer

* Update Contributing.md

Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>

---------

Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>
2025-03-05 09:11:29 -06:00
Sebastian Beltran
90e522ac90 fix(docs): update guidance for triager nominations (#6349)
* docs: update guidance for triager nominations

* Update Contributing.md

Co-authored-by: Wes Todd <wes@wesleytodd.com>

* Update Contributing.md

---------

Co-authored-by: Wes Todd <wes@wesleytodd.com>
2025-03-04 08:09:18 -06:00
Ulises Gascón
59703c2321 docs: update emeritus triagers (#6345) 2025-02-27 22:47:13 +01:00
Andrea Polverino
caa4f68ee8 feat: Extend res.links() to allow adding multiple links with the same rel (closes #2729) (#4885) 2025-02-14 10:20:53 -06:00
Phillip Barta
6ed3439584 fix(docs): Update multiple links to use https instead of http (#6338) 2025-02-14 09:51:27 -06:00
Juan José
327af123a1 feat: add support for ETag option in res.sendFile (#6073)
This patch introduces the ability to control the ETag generation
through the `res.sendFile` function. Specifically, the ETag option
is wired to the application's configuration, allowing it to be
enabled or disabled based on the app's settings.

Fixes: https://github.com/expressjs/express/issues/2294

Signed-off-by: Juan José Arboleda <soyjuanarbol@gmail.com>
2025-02-13 13:39:31 -06:00
Wes Todd
d2de128a32 fix (deps): update deps (#6337)
fix(deps): mocha@^10.7.3 (closes #6121)

fix(deps): marked@^15.0.3 (closes #6120)

fix(deps): express-session@^1.18.1 (closes #6119)

fix(deps): ejs@^3.1.10 (closes #6117)

fix(deps): content-type@^1.0.5 (closes #6115)

fix(deps): connect-redis@^8.0.1 (closes #6114)

fix(deps): supertest@^6.3.4 (closes #6112)

Co-authored-by: agungjati <agungjati94@gmail.com>
2025-02-13 10:44:50 -06:00
Agung Jati
2a53336e5d fix(deps): nyc@^17.1.0 (#6122) 2025-02-12 10:47:19 -06:00
Ulises Gascón
a42413d4e3 fix(docs): Update repo captains (#6234)
* docs: update repo captains

* docs: update repo captain nomination policies

Ref: https://github.com/expressjs/express/pull/6234#issuecomment-2578555232
2025-02-12 10:22:11 -06:00
Wes Todd
c2f576cbe9 feat(deps): router@^2.1.0 (#6331) 2025-02-12 10:09:50 -06:00
Wes Todd
99473c593a feat(deps): body-parser@^2.1.0 (#6332) 2025-02-12 09:44:53 -06:00
Dustin Popp
2d589b644a fix(docs): retroactively note 5.0.0-beta.1 api change in history file (#6333)
Signed-off-by: Dustin Popp <dustinpopp@ibm.com>
2025-02-12 09:38:10 -06:00
Phillip Barta
85e48bb8c1 fix(deps): update debug to ^4.4.0 (#6313) 2025-02-10 13:41:39 -06:00
Alexander Cerutti
55869f49a6 feat: Added check to support Uint8Array in response sending (#6285)
Unified usage of ArrayBuffer.isView to comprehend Buffer and removed isView function check

Co-authored-by: Wes Todd <wes@wesleytodd.com>

Added Uint8Array test with encoding

fix: added history.md entry
2025-02-10 11:23:02 -06:00
Dustin Popp
af7cd90893 feat(deps): use carat notation for dependency versions (#6317)
Signed-off-by: Dustin Popp <dustinpopp@ibm.com>
Co-authored-by: Ulises Gascón <ulisesgascongonzalez@gmail.com>
2025-02-05 12:05:39 -06:00
Phillip Barta
ae6a4621bc fix(ci): updated scorecard actions (#6322) 2025-02-05 11:40:08 -06:00
Phillip Barta
8d39345902 fix(ci): fix npm install --include typo (#6324) 2025-02-05 11:25:48 -06:00
Phillip Barta
a5cb681eb8 ci: updated github actions ci workflow (#6314) 2025-02-05 13:27:59 +01:00
Ayoub Mabrouk
511d9dfca8 refactor: simplify normalizeTypes function (#6097) 2025-02-04 11:59:48 +01:00
Ulises Gascón
7f13d572c1 docs: include team email in the security policy (#6278) 2025-02-04 11:28:18 +01:00
prajesh
62336717bf fix: added a missing semicolon in css styles in examples/auth (#6297) 2025-01-26 11:54:07 +01:00
Sebastian Beltran
3bbffdc41c docs: add @Phillip9587 to the triage team 2025-01-23 09:51:45 -06:00
Ulises Gascón
ff86319ed5 ci: add support for OSSF scorecard reporting (#5431) 2025-01-15 07:39:30 +01:00
Hamir Mahal
1c5cf0fead refactor: remove Invalid action input 2025-01-14 13:01:39 -06:00
Jon Koops
256a3d1527 Remove unused depd dependency
Signed-off-by: Jon Koops <jonkoops@gmail.com>
2025-01-12 11:08:51 -06:00
Wes Todd
4f952a953b fix: remove download size badges 2025-01-11 11:12:04 -06:00
Szymon Łągiewka
41113599af fix(refactor): prefix built-in node module imports
Since v5 relies on node >= 18, this is now possible (since v16, v14.18.0
[^1][^2]).

It's functionally irrelevant:
1. It's not required for CJS nor ESM (with a few exceptions [^3])
2. It has no performance promises

However, there are upsides to this approach:
1. It brings clear boundaries to what's a built-in and what's an
external dependency
2. It reduces the risk of importing unwanted deps where a built-in is
expected
3. It's slightly more interoperable with other JS runtimes that provide
node compatibility[^4], albeit only during development. Once imported
from npm, built-ins are assumed.

[^1]:https://nodejs.org/docs/latest-v22.x/api/modules.html#built-in-modules
[^2]:https://github.com/nodejs/node/pull/37246
[^3]:https://nodejs.org/api/modules.html#built-in-modules-with-mandatory-node-prefix
[^4]:https://docs.deno.com/runtime/fundamentals/node/#using-node's-built-in-modules
2025-01-10 11:53:44 -06:00
AbdelMonaam Aouini
6a40af8293 fix(devdeps): update dev deps (#6211)
Co-authored-by: Monaam Aouini <abdelmonaem.aouini@mispay.co>
2025-01-08 14:45:36 -06:00
Phillip Barta
246f6f5aee fix: Remove utils-merge dependency - use spread syntax instead (#6091) 2025-01-08 09:56:16 -06:00
Jon Koops
b11122be85 chore: replace methods dependency with standard library (#6196) 2025-01-02 08:00:30 +01:00
Sebastian Beltran
43020ff275 docs: clarify the security process in the triage role (#6217) 2024-12-20 18:18:55 +01:00
Shahan Arshad
e4a61bd88e refactor: improve readability (#6173) 2024-11-27 21:22:22 +01:00
Ulises Gascón
39f5d633b5 docs: add @rxmarbles to the triage team (#6151) 2024-11-27 19:59:36 +01:00
Jon Church
52ed64606f update history.md for acceptParams change (#6177) 2024-11-20 14:40:39 -05:00
Phillip Barta
4e92ac9031 cleanup: remove AsyncLocalStorage check from tests (#6147)
Co-authored-by: Wes Todd <wes@wesleytodd.com>
2024-11-15 10:23:42 -06:00
Phillip9587
9f8589e31c cleanup: remove unnecessary require for global Buffer
The Buffer object is globally available in Node.js, so there is no need to explicitly require it.
2024-11-15 10:16:29 -06:00
Sebastian Beltran
cc751cff8f improve step update documentation 2024-11-15 08:53:37 -06:00
Blake Embrey
805ef52ae6 Use loop for acceptParams (#6066) 2024-11-14 16:01:25 -05:00
Phillip Barta
9e3dbb4374 chore(test): remove promise support check from tests (#6148)
Promises are supported in all supported Node.js version so the check is unnecessary
2024-11-12 09:30:34 -06:00
Ulises Gascón
b31910c542 docs: Add DCO (#6048)
Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>
2024-10-29 13:35:44 +01:00
Bhavya Dhiman
c70197ad33 fix(buffer): use node:buffer instead of safe-buffer (#6071)
Main Changes:
- Removed dependency `safe-buffer@5.2.1`
- Use `node:buffer` core library instead of safe-buffer
2024-10-27 11:10:33 +01:00
Phillip Barta
8cb53ea5c3 refactor: Remove Object.setPrototypeOf polyfill (#6081) 2024-10-22 20:22:26 +02:00
Rand McKinney
e162764f0f docs: add bjohansebas as repo captain for expressjs.com (#6058) 2024-10-20 20:10:23 +02:00
Sebastian Beltran
508c74091f docs: update readme (#5994) 2024-10-20 20:09:00 +02:00
Sebastian Beltran
b274047a5d docs: update homepage link http to https (#5920)
Co-authored-by: Ulises Gascón <ulisesgascongonzalez@gmail.com>
2024-10-20 20:07:22 +02:00
Chris de Almeida
082d6d1253 test: add discarded middleware test (#5819) 2024-10-20 20:06:49 +02:00
Sebastian Beltran
94546a3cc5 docs: add funding (#6064) 2024-10-20 19:58:49 +02:00
Sebastian Beltran
ab02240336 build: Node.js 23.0 (#6075) 2024-10-20 19:25:56 +02:00
Ulises Gascón
a46cfdc37f docs: update captains
PR-URL: https://github.com/expressjs/express/pull/6027
2024-10-09 21:40:05 +02:00
Ulises Gascón
d14b2de782 5.0.1
PR-URL: https://github.com/expressjs/express/pull/6032
2024-10-08 21:31:10 +02:00
Josh Buker
2027b87a27 fix(deps): cookie@0.7.0
Co-authored-by: Ulises Gascón <ulisesgascongonzalez@gmail.com>
2024-10-08 12:10:56 +02:00
Blake Embrey
2cbf22721d Link and update captains (#6013) 2024-10-06 14:06:57 -07:00
Ulises Gascón
3e1a1cedb2 Add @bjohansebas to the triage team (#6009)
Co-authored-by: Sebastian Beltran <bjohansebas@gmail.com>
2024-10-06 17:34:26 +02:00
Jon Church
6340d1509f remove --bail from test script (#5962) 2024-09-30 16:49:26 -04:00
Wes Todd
344b022fc7 5.0.0
closes #2237
closes https://github.com/expressjs/discussions/issues/233
2024-09-09 23:37:22 -05:00
Wes Todd
0c49926a9b fix(deps): send@^1.1.0 2024-09-09 23:34:03 -05:00
Wes Todd
b3906cbdde fix(deps): serve-static@^2.1.0 2024-09-09 23:32:19 -05:00
Wes Todd
fed8c2a885 fix(deps): body-parser@^2.0.1 2024-09-09 23:27:40 -05:00
Blake Embrey
bdd81f8670 Delete back as a magic string (#5933) 2024-09-09 20:28:55 -07:00
ctcpip
6c98f80b6a 🔧 update CI, remove unsupported versions, clean up 2024-09-09 21:49:35 -05:00
Wes Todd
f9256ef36f Merge branch '5.0' into 5-merge 2024-09-09 21:11:23 -05:00
Wes Todd
e5feb9fcc9 Merge tag '4.20.0' into 5.0 2024-09-09 21:07:57 -05:00
Ulises Gascón
21df421ebc 4.20.0 2024-09-10 04:01:43 +02:00
Ulises Gascón
4c9ddc1c47 feat: upgrade to serve-static@0.16.0 2024-09-10 04:01:43 +02:00
Ulises Gascón
9ebe5d500d feat: upgrade to send@0.19.0 (#5928) 2024-09-10 04:01:43 +02:00
Ulises Gascón
ec4a01b6b8 feat: upgrade to body-parser@1.20.3 (#5926)
PR-URL: https://github.com/expressjs/express/pull/5926
2024-09-10 04:01:43 +02:00
Chris de Almeida
54271f69b5 fix: don't render redirect values in anchor href
Co-authored-by: Ulises Gascón <ulisesgascongonzalez@gmail.com>
2024-09-10 04:00:58 +02:00
Wes Todd
0264908903 feat(deps)!: router@^2.0.0 (#5885) 2024-09-09 17:50:11 -05:00
Jon Church
4d713d2b76 update to fresh@2.0.0 (#5916)
fixes handling of If-Modified-Since in combination with If-None-Match
2024-09-09 17:03:32 -05:00
Blake Embrey
125bb742a3 path-to-regexp@0.1.10 (#5902)
* path-to-regexp@0.1.10

* Update History.md
2024-09-09 16:02:06 -05:00
Wes Todd
accafc652e fix(deps): finalhandler@^2.0.0 (#5899) 2024-09-02 13:36:21 -05:00
Wes Todd
05f40f4321 fix(deps)!: content-disposition@^1.0.0 (#5884) 2024-08-31 13:09:21 -05:00
Wes Todd
402e7f653f fix(deps): type-is@^2.0.0 (#5883) 2024-08-31 12:31:31 -05:00
Wes Todd
4e61d0100d fix(deps)!: mime-types@^3.0.0 (#5882) 2024-08-31 11:06:25 -05:00
Wes Todd
7748475747 fix(deps): accepts@^2.0.0 (#5881) 2024-08-31 10:55:04 -05:00
S M Mahmudul Hasan
91a58b5b03 cookie-signature@^1.2.1 (#5833)
* upgraded `cookie-signature` to 1.2.1

* declared cookie-signature deps in history

* add caret in version
2024-08-23 18:17:12 -05:00
Carlos Serrano
13e6894393 chore: qs@6.13.0 (#5847)
Co-authored-by: Wes Todd <wtodd@netflix.com>
2024-08-23 14:10:16 -07:00
Wes Todd
65b62065d2 fix(deps) serve-staic@2.0.0 (#5790) 2024-08-23 14:07:45 -07:00
Anna Bocharova
2a980ad160 merge-descriptors@1.0.3 (#5781)
* Allow patches for `merge-descriptors` dependency

* Set fixed latest of v1 (1.0.3)
2024-08-23 13:39:13 -07:00
Anna Bocharova
0b243b1aee 5.x: Upgrading merge-descriptors with allowing minors (#5782)
* Upgrading `merge-descriptors` with allowing minors in v5

* Using ^2.0.0 as per request

* Reflecting in History.md.

* Update History.md
2024-08-23 13:37:27 -07:00
S M Mahmudul Hasan
a3e7e05e0a docs: specify new instructions for question and discuss
PR-URL: https://github.com/expressjs/express/pull/5835
2024-08-22 18:25:14 +02:00
Blake Embrey
c5addb9a17 deps: path-to-regexp@0.1.8 (#5603) 2024-08-21 20:15:02 -07:00
Ulises Gascón
e35380a39d docs: add @IamLizu to the triage team (#5836)
PR-URL: https://github.com/expressjs/express/pull/5836
2024-08-19 22:12:24 +02:00
Sebastian Beltran
f5b6e67aed docs: update scorecard link (#5814)
Co-authored-by: Ulises Gascón <ulisesgascongonzalez@gmail.com>
2024-08-18 20:37:51 +02:00
Carlos Serrano
09831580ec refactor: replace 'path-is-absolute' dep with node:path isAbsolute method (#5830)
* refactor: replace 'path-is-absolute' dep with node:path isAbsolute method

* docs: add path-is-absolute dep removal to History.md
2024-08-17 10:21:29 -05:00
Carlos Serrano
41c054cff1 chore: upgrade debug dep from 3.10 to 4.3.6 (#5829)
* chore: upgrade debug dep from 3.10 to 4.3.6

* docs: add debug dep upgrade to History.md
2024-08-17 10:20:25 -05:00
Wes Todd
ecf762ff38 fix(deps)!: send@^1.0.0 (#5786) 2024-08-09 09:59:53 -07:00
ctcpip
63992bb1d7 Merge branch 'ci/v5-node-lts' into 5-merge 2024-08-02 16:24:55 -05:00
ctcpip
ea49706052 Merge branch 'master' into 5-merge 2024-08-02 15:57:43 -05:00
ctcpip
dde1f7d6e8 Merge branch '5.0' into 5-merge 2024-08-02 15:38:18 -05:00
Jon Church
82fc12a40b Ignore expires and maxAge in res.clearCookie() (#5792)
* add test for removing user provided expires

* rework impl and tests to ignore maxAge, do not set it

this is to take into account the built-in relative expires when passing
a maxAge to res.cookie

I realized that using maxAge to invalidate cookies inherrently hit this
relativee expires behavior, and the goal of this PR is not to rework
that relative expires behavior w/ maxAge, but to prevent users from
overwriting these values by accident when clearing cookies

* update history.md

* explicitly delete maxAge instead of setting as undefined

* drop the spread, use object.assign

* wording, review comment on history.md

Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>

* ♻️ use spread, update supported ecmascript version

---------

Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>
2024-08-02 15:26:45 -05:00
ctcpip
9c756b0105 💚 remove node <11, all failing permanently now 2024-08-02 13:15:51 -05:00
Ulises Gascón
160b91cbf7 feat: adopt Node@18 as the minimum supported version (#5803)
- PR-URL: https://github.com/expressjs/express/pull/5803
- This is a BREAKING CHANGE
2024-08-02 16:07:36 +02:00
Mick A.
d106bf5324 Use Array.flat instead of array-flatten (#5677) 2024-08-01 19:42:07 -04:00
Jon Church
723b5451bb Throw on invalid status codes (#4212)
* check status code is integer, or string integer, in range

* fix tests, update jsdoc comment for res.status

* throw if number is string

* narrow valid range to between 1xx and 5xx

* disambiguate the error message

* update skipped tests, remove invalid string test

* remove invalid float test

* fixup! remove invalid float test

* fix invalid range tests error assertions

* remove unused deprecate function

* add test to assert on 200.00 coming through as 200

this is the behavior of node's underlying HTTP module

* revert back to throwing only on > 999 and < 100

* update implementation for > 999

* add test for 700 status code

* update history with change

* update jsdoc

* clarify jsdoc comment

* one more round of jsdoc

* update 501 test

* add invalid status code test for res.sendStatus

* add test describe block for valid range

* fixup! add test describe block for valid range

* reduce the describe nesting

* switch to testing status 100, to avoid 100-continue behavior

* fix 900 test

* stringify code in thrown RangeError message

* remove accidentally duplicated res.status method

* fix error range message

Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>

* update sendStatus invalid code test to use sendStatus

---------

Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>
2024-07-30 14:49:13 -07:00
Ulises Gascón
2177f67f54 docs: add OSSF Scorecard badge (#5436)
PR-URL: https://github.com/expressjs/express/pull/5436
2024-07-28 12:55:10 +02:00
Jon Church
f4bd86ed36 Replace Appveyor windows testing with GHA (#5599)
This PR moves us off of Appveyor for windows testing.

We are now doing windows/linux testing on GHA. With the exception of iojs, which we are only testing on Linux and have split out to it's own workflow.

We have also added npm-shrinkwrap.json to our gitignore, in order to not have to configure npm in CI to ignore it. If it's never checked in, it shouldn't exist in CI as you need to go out of your way to create it w/ npm.
2024-07-27 14:15:55 -04:00
ctcpip
c96c690dc0 Merge branch 'master' into 5.0 2024-07-25 16:55:48 -05:00
ctcpip
088856c3f8 💚 add legacy CI, clean up 2024-07-25 12:39:38 -05:00
S M Mahmudul Hasan
2ec589c113 Fix Contributor Covenant link definition reference in attribution section (#5762) 2024-07-17 13:44:03 -07:00
Jon Church
4cf7eed927 remove minor version pinning from ci (#5722) 2024-06-26 18:23:19 -04:00
Chris de Almeida
6d084715ba 📝 update people, add ctcpip to TC (#5683) 2024-06-10 17:19:11 -04:00
Jon Church
61421a8c0c skip QUERY tests for Node 21 only, still not supported (#5695)
* skip QUERY tests for Node 21 only, still not supported

QUERY support has now landed in Node 22.2.0, but is still not supported
in 21.7.3

QUERY showed up in http.METHODS in 21.7.2. Only Node versions after that
will attempt to run tests for it, based on the way we dynamically test
members of the http.METHODS array from Node

* update CI to run on 21.7 and 22.2
2024-06-08 23:25:42 -04:00
Jon Church
f42b160bbc [v4] Deprecate res.clearCookie accepting options.maxAge and options.expires (#5672)
* add deprecation notice for res.clearCookie maxAge/expires

* update History.md for clearCookie deprecation change

* add tests to codify deprecated behavior

Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>

---------

Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>
2024-06-07 19:48:48 -04:00
Chris de Almeida
689073d657 bring back query tests for node 21 (#5690) 2024-06-05 17:25:58 -04:00
Ulises Gascón
2803a2b35a docs: add @UlisesGascon as captain for cookie-parser (#5666) 2024-05-22 18:29:16 -04:00
Wes
ee40a881f5 call callback once on listen error 2024-05-17 13:47:56 -07:00
Blake Embrey
a7d6d29ed3 Add @UlisesGascon to mime repos
Co-authored-by: Ulises Gascón <ulisesgascongonzalez@gmail.com>
2024-05-13 21:31:23 -05:00
Blake Embrey
897290b685 List and sort all projects, add captains 2024-05-13 21:31:23 -05:00
Mert Can Altin
700349ffaf doc: add table of contents, tc/triager lists to readme (#5619)
* doc: updated readme file

* doc: updated readme file for doc lint

* Update Readme.md

Co-authored-by: krzysdz <krzysdz@users.noreply.github.com>

* Update Readme.md

Co-authored-by: Ulises Gascón <ulisesgascongonzalez@gmail.com>

* Update Readme.md

Co-authored-by: Ulises Gascón <ulisesgascongonzalez@gmail.com>

* Update Readme.md

Co-authored-by: Christine Belzie <105683440+CBID2@users.noreply.github.com>

* repair readme

* added Emeritus area

* Add @carpasse to the triager team

* removed old collaborators

* add missing triagers

* lint

* Update Readme.md

Co-authored-by: Jon Church <me@jonchurch.com>

* Update Readme.md

Co-authored-by: Jon Church <me@jonchurch.com>

* dedent to fix ToC spacing

* fixup! dedent to fix ToC spacing

* us @ for jonchurch

* format names to use github handles first, single line

* added emeritus triagers

* edited title

* added emeritus team members

* added menu head

* edited emeritus

* Update Readme.md

Co-authored-by: Jon Church <me@jonchurch.com>

* Update Readme.md

Co-authored-by: Jon Church <me@jonchurch.com>

* edits to TC and anchors

* Update Readme.md

Co-authored-by: Jon Church <me@jonchurch.com>

* Update Readme.md

Co-authored-by: Jon Church <me@jonchurch.com>

* Update Readme.md

Co-authored-by: Jon Church <me@jonchurch.com>

* Update Readme.md

Co-authored-by: Jon Church <me@jonchurch.com>

* Update Readme.md

Co-authored-by: Jon Church <me@jonchurch.com>

* Update Readme.md

Co-authored-by: Ulises Gascón <ulisesgascongonzalez@gmail.com>

* Update Readme.md

Co-authored-by: Ulises Gascón <ulisesgascongonzalez@gmail.com>

* Update Readme.md

Co-authored-by: Ulises Gascón <ulisesgascongonzalez@gmail.com>

* Update Readme.md

Co-authored-by: Ulises Gascón <ulisesgascongonzalez@gmail.com>

* Update Readme.md

Co-authored-by: Ulises Gascón <ulisesgascongonzalez@gmail.com>

---------

Co-authored-by: Mert Can Altin <mert.altin@trendyol.com>
Co-authored-by: krzysdz <krzysdz@users.noreply.github.com>
Co-authored-by: Ulises Gascón <ulisesgascongonzalez@gmail.com>
Co-authored-by: Christine Belzie <105683440+CBID2@users.noreply.github.com>
Co-authored-by: Jon Church <me@jonchurch.com>
2024-05-08 17:02:11 -04:00
Mert Can Altin
4b9cd2fd0e add support Node.js@22 in the CI (#5627)
Co-authored-by: Mert Can Altin <mert.altin@trendyol.com>
2024-05-04 18:15:53 -04:00
Jon Church
b44191eb3d ignore ETAG query test as well, reuse skip util (#5639) 2024-05-04 18:01:42 -04:00
Jon Church
8417c60fcf skip QUERY method test (#5628) 2024-05-04 17:09:52 -04:00
Blake Embrey
bf91946bd4 deps: encodeurl@~2.0.0 (#5569) 2024-05-04 16:53:09 -04:00
Evan Hahn
26801a0afd Use object with null prototype for settings closes #4835 2024-04-29 10:12:23 -05:00
Evan Hahn
14439731f9 Use object with null prototype for various app properties
`app.cache`, `app.engines`, and `app.settings` are now created with
`Object.create(null)` instead of `{}`.

This also updates a test to ensure that `app.locals` is created the same
way.
2024-04-29 09:43:25 -05:00
Ulises Gascón
d97d79ed9a docs: add UlisesGascon as triage initiative captain 2024-04-21 11:48:10 +02:00
Ulises Gascón
26e53f0fbc ci: add CodeQL (SAST) (#5433)
PR-URL: https://github.com/expressjs/express/pull/5433

---------

Co-authored-by: Íñigo Marquínez Prado <25435858+inigomarquinez@users.noreply.github.com>
2024-04-17 15:13:07 +02:00
Ulises Gascón
6abec204c0 docs: update triage nomination policy (#5600)
PR-URL: https://github.com/expressjs/express/pull/5600
2024-04-17 13:53:16 +02:00
Ulises Gascón
4b3b8cc231 feat: adopt Node@18 as the minimum supported version 2024-04-11 19:19:47 +02:00
Ulises Gascón
e9bcdd399b ci: adopt Node@18 as the minimum supported version 2024-04-11 19:16:20 +02:00
Íñigo Marquínez Prado
815f799310 docs: update reference to the threat model (#5590)
PR: https://github.com/expressjs/express/pull/5590
2024-04-10 18:53:52 +02:00
Jon Church
7f9e5843b9 add jonchurch as repo captain on several packages 2024-04-09 08:51:51 -05:00
Blake Embrey
93cf646d5c docs: add blakeembrey as captain for encodeurl (#5579) 2024-04-07 18:40:16 +02:00
Ulises Gascón
2676a1f281 docs: add reference to the Threat Model
* docs: add Threat Model

* docs: update reference

Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>

* docs: improve readability

Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>

* docs: add reference to the Threat Model

---------

Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>
2024-04-04 13:01:35 +02:00
Jon Church
6da57c7819 remove examples from the ignore 2024-03-27 09:57:44 -05:00
Jon Church
d546f93f2f add develop to branches 2024-03-27 09:57:44 -05:00
Jon Church
4771ba2bc3 crib fastify's ci concurrency logic
76674fdf46/.github/workflows/ci.yml (L18)
2024-03-27 09:57:44 -05:00
Jon Church
3ae704f67f update ci push trigger only to some branches, ignore examples, .md 2024-03-27 09:57:44 -05:00
Marco Ippolito
8b6d34963d Update Security.md
Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>
2024-03-27 09:57:09 -05:00
Marco Ippolito
36b8148110 Update Security.md
Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>
2024-03-27 09:57:09 -05:00
Marco Ippolito
6d98d2e110 Update Release-Process.md
Co-authored-by: Chris de Almeida <ctcpip@users.noreply.github.com>
2024-03-27 09:57:09 -05:00
marco-ippolito
51a76366e3 refactor: reword to pre-releases 2024-03-27 09:57:09 -05:00
Marco Ippolito
4e3f95c0ea Update Security.md
Co-authored-by: Wes Todd <wes@wesleytodd.com>
2024-03-27 09:57:09 -05:00
Marco Ippolito
88bd6d8e3a Update Release-Process.md
Co-authored-by: Wes Todd <wes@wesleytodd.com>
2024-03-27 09:57:09 -05:00
marco-ippolito
51595d402b feat: document beta releases expectations 2024-03-27 09:57:09 -05:00
Wes Todd
94669f9289 remove duplicate location test for data uri 2024-03-26 09:41:06 -05:00
Wes Todd
cd7d79f92a v5.0.0-beta.3 2024-03-25 09:41:30 -05:00
Wes Todd
5e2345e966 Merge branch '5.0' into 5.x 2024-03-25 09:38:58 -05:00
Wes Todd
6415f7035b Merge tag '4.19.2' into 5.0
4.19.2
2024-03-25 09:37:02 -05:00
Wes Todd
b28db2c12c 4.19.2 2024-03-25 09:29:41 -05:00
Wes Todd
0b746953c4 Improved fix for open redirect allow list bypass
Co-authored-by: Jon Church <me@jonchurch.com>
Co-authored-by: Blake Embrey <hello@blakeembrey.com>
2024-03-25 09:29:41 -05:00
Wes Todd
04bc62787b 4.19.2 2024-03-25 09:26:03 -05:00
Wes Todd
da4d763ff6 Improved fix for open redirect allow list bypass
Co-authored-by: Jon Church <me@jonchurch.com>
Co-authored-by: Blake Embrey <hello@blakeembrey.com>
2024-03-25 09:22:34 -05:00
Wes Todd
7091ec17f0 5.0.0-beta.2 2024-03-20 22:00:19 -05:00
Wes Todd
416ba025a1 build: disable test for 4.x which is failing in v5 2024-03-20 21:52:27 -05:00
Wes Todd
60fb1d2acd Merge tag '4.19.1' into 5.x
4.19.1
2024-03-20 21:17:26 -05:00
Wes Todd
e9f9aaeebd Merge tag '4.19.0' into 5.x
4.19.0
2024-03-20 21:14:00 -05:00
Wes Todd
4f0f6cc67d 4.19.1 2024-03-20 17:17:59 -05:00
Wes Todd
a003cfab03 Allow passing non-strings to res.location with new encoding handling checks fixes #5554 #5555 2024-03-20 17:12:46 -05:00
Wes Todd
a1fa90fcea fixed un-edited version in history.md for 4.19.0 2024-03-20 16:52:48 -05:00
Wes Todd
11f2b1db22 build: fix build due to inconsistent supertest behavior in older versions 2024-03-20 16:33:03 -05:00
Wes Todd
084e36506a 4.19.0 2024-03-20 10:18:54 -05:00
FDrag0n
0867302ddb Prevent open redirect allow list bypass due to encodeurl
Co-authored-by: Jon Church <me@jonchurch.com>
2024-03-20 10:18:54 -05:00
Rand McKinney
567c9c665d Add note on how to update docs for new release (#5541)
* Update Release-Process.md

Add note about updating docs.

* Update Release-Process.md

* Update Release-Process.md
2024-03-16 11:57:42 -06:00
Rich Hodgkins
69a4cf2819 deps: cookie@0.6.0
closes #5404
2024-03-15 10:27:45 -05:00
Wes Todd
4ee853e837 docs: loosen TC activity rules 2024-03-14 12:43:12 +01:00
Wes Todd
414854b82e docs: nominating @wesleytodd to be project captian 2024-03-14 12:40:52 +01:00
Ulises Gascón
06c6b88808 docs: update release date 2024-03-11 16:19:21 +01:00
Ulises Gascón
1b51edac7c 4.18.3 2024-02-26 20:20:53 +01:00
Ulises Gascón
b625132864 build: pin Node 21.x to minor
Co-authored-by: Aravind Nair <22199259+aravindvnair99@users.noreply.github.com>
closes #5430
2024-02-26 20:08:10 +01:00
Ulises Gascón
e3eca80584 build: pin Node 21.x to minor
Co-authored-by: Aravind Nair <22199259+aravindvnair99@users.noreply.github.com>
2024-02-26 20:07:59 +01:00
Ulises Gascon
23b44b3ddd build: support Node.js 21.6.2 2024-02-26 20:07:27 +01:00
Ulises Gascon
b9fea12245 build: support Node.js 21.x in appveyor 2024-02-26 20:06:49 +01:00
Ulises Gascon
c259c3407f build: support Node.js 21.x 2024-02-26 20:05:58 +01:00
Ulises Gascon
fdeb1d3176 build: support Node.js 20.x in appveyor
closes #5429
2024-02-26 19:57:01 +01:00
Ulises Gascón
734b281900 build: support Node.js 20.x 2024-02-26 19:41:28 +01:00
Dmitry Kondar
0e3ab6ec21 examples: improve view count in cookie-sessions
closes #5414
2024-02-19 16:47:26 -05:00
Ulises Gascon
59af63ac2e build: Node.js@18.19
closes #5490
2024-02-19 14:18:24 -05:00
Ulises Gascon
e720c5a21b docs: add documentation for benchmarks
closes #5312
2024-02-19 12:04:49 -05:00
riddlew
3abea7f818 examples: remove multipart example
Closes #5193
closes #5195
2024-02-19 10:04:05 -05:00
christof louw
2a89eb5c74 tests: fix handling multiple callbacks
closes #5233
2024-02-19 08:20:39 -05:00
Gireesh Punathil
59aae7686b docs: add project captains to contribution
closes #4210
closes #5484
2024-02-18 12:21:22 -06:00
Wes Todd
c4fe7de7bc docs: update TC governance rules
closes #5483
2024-02-18 22:04:47 -05:00
Douglas Christopher Wilson
a22920707b build: actions/checkout@v4 2023-11-01 22:08:37 -04:00
Douglas Christopher Wilson
02d1c3916e build: Node.js@19.9 2023-08-23 20:07:50 -04:00
Douglas Christopher Wilson
8d8bfaac7b build: Node.js@18.17 2023-08-23 19:58:41 -04:00
Douglas Christopher Wilson
13df1de857 build: eslint@8.47.0 2023-08-23 19:49:36 -04:00
Raz Luvaton
2a00da2067 tests: use random port in listen test
closes #5162
2023-06-04 11:47:20 -04:00
Douglas Christopher Wilson
24e4a2570d build: Node.js@16.20 2023-04-06 20:43:53 -04:00
Douglas Christopher Wilson
91b6fb83b4 build: use nyc@14.1.1 for Node.js < 10 2023-04-06 20:40:27 -04:00
Rakesh Bisht
3531987844 lint: remove unused function arguments in Route tests
closes #5137
2023-05-15 21:53:48 -04:00
Douglas Christopher Wilson
f540c3b019 build: Node.js@18.15 2023-03-13 22:59:15 -04:00
Douglas Christopher Wilson
b8b2eff3c3 build: eslint@8.36.0 2023-03-13 22:52:34 -04:00
Douglas Christopher Wilson
f4e48bc43e build: ejs@3.1.9 2023-03-13 22:49:54 -04:00
Douglas Christopher Wilson
8c24fa8f7b tests: wait for server close in app.listen() 2023-03-13 22:43:19 -04:00
Douglas Christopher Wilson
0debedf4f3 build: fix code coverage aggregate upload 2023-02-26 13:34:32 -05:00
Douglas Christopher Wilson
74beeac071 Fix routing requests without method 2023-02-23 17:23:22 -05:00
Arnaud Benhamdine
9bc1742937 build: support Node.js 19.x 2023-02-23 15:28:18 -05:00
Rakesh Bisht
5ad95419ba docs: fix typos in history
closes #5131
2023-02-23 12:14:47 -05:00
Douglas Christopher Wilson
8a76f39d98 build: eslint@8.34.0 2023-02-23 00:28:41 -05:00
Douglas Christopher Wilson
60b7c672c1 build: mocha@10.2.0 2023-02-23 00:27:06 -05:00
Douglas Christopher Wilson
1e42a98db6 deps: body-parser@1.20.2 2023-02-23 00:24:20 -05:00
Rakesh Bisht
506fbd63be docs: add missing JSDoc param for parseExtendedQueryString
closes #5130
2023-02-22 21:10:07 -05:00
Douglas Christopher Wilson
b9f7a97fe1 build: use $GITHUB_OUTPUT for environment list 2023-02-22 18:10:59 -05:00
Douglas Christopher Wilson
546969d198 build: Node.js@18.14 2023-02-22 12:07:48 -05:00
Douglas Christopher Wilson
f05b5d0e9c build: Node.js@16.19 2023-02-22 11:59:40 -05:00
Rakesh Bisht
3c1d605da7 lint: remove unused parameters in examples
closes #5113
2023-02-22 10:25:07 -05:00
Rakesh Bisht
6b4c4f5426 docs: fix typos in JSDoc comments
closes #5117
2023-02-22 00:16:40 -05:00
Rakesh Bisht
a1efd9d6cf lint: remove unused parameter from internal function
coses #5119
2023-02-21 22:55:22 -05:00
Rakesh Bisht
c6ee8d6e7f lint: remove unused function arguments in tests
closes #5124
2023-02-20 22:57:13 -05:00
Abdul Rauf
442fd46799 build: actions/checkout@v3
closes #5027
2022-11-01 21:13:10 -04:00
Arnaud Benhamdine
723b67766f build: Node.js@18.12 2022-11-01 21:10:12 -04:00
Arnaud Benhamdine
29e117e676 build: Node.js@16.18 2022-11-01 21:08:43 -04:00
Kevin Jones
06b2b1416d docs: update git clone to https protocol
closes #5032
2022-11-01 21:05:31 -04:00
Douglas Christopher Wilson
8368dc178a 4.18.2 2022-10-08 16:11:42 -04:00
Abhinav Das
61f4049122 docs: replace Freenode with Libera Chat
closes #5013
2022-10-08 14:52:31 -04:00
Douglas Christopher Wilson
bb7907b932 build: Node.js@18.10
closes #5014
2022-10-07 17:48:59 -04:00
Douglas Christopher Wilson
f56ce73186 build: supertest@6.3.0 2022-10-06 10:28:13 -04:00
Douglas Christopher Wilson
24b3dc5516 deps: qs@6.11.0 2022-10-06 10:27:01 -04:00
Douglas Christopher Wilson
689d175b8b deps: body-parser@1.20.1 2022-10-06 10:26:18 -04:00
Douglas Christopher Wilson
340be0f79a build: eslint@8.24.0 2022-10-05 22:40:51 -04:00
REALSTEVEIG
33e8dc303a docs: use Node.js name style
closes #4926
2022-08-19 21:12:14 -04:00
Douglas Christopher Wilson
644f6464b9 build: supertest@6.2.4 2022-08-18 23:42:39 -04:00
Douglas Christopher Wilson
ecd7572f1e build: Node.js@14.20 2022-08-18 23:41:10 -04:00
Douglas Christopher Wilson
97131bcda8 build: Node.js@18.7 2022-08-18 23:01:25 -04:00
Douglas Christopher Wilson
8d98e86d7f build: Node.js@16.17 2022-08-18 23:00:36 -04:00
Alexandru Dragomir
2c47827053 examples: remove unused function arguments in params
closes #4914
2022-05-20 11:57:37 -04:00
Douglas Christopher Wilson
97f0a518d8 tests: verify all handlers called in stack tests 2022-05-20 11:54:35 -04:00
Douglas Christopher Wilson
7ec5dd2b3c Fix regression routing a large stack in a single route
fixes #4913
2022-05-20 09:37:20 -04:00
Douglas Christopher Wilson
ab2c70b954 build: Node.js@18.1 2022-05-20 09:35:20 -04:00
Douglas Christopher Wilson
745a63f825 build: ejs@3.1.8 2022-05-20 09:34:47 -04:00
Douglas Christopher Wilson
a2dfc56a49 build: mocha@10.0.0 2022-05-20 09:33:19 -04:00
Douglas Christopher Wilson
d854c43ea1 4.18.1 2022-04-29 15:32:26 -04:00
Douglas Christopher Wilson
b02a95c693 build: Node.js@16.15 2022-04-29 14:52:20 -04:00
Douglas Christopher Wilson
631ada0c64 Fix hanging on large stack of sync routes
fixes #4899
2022-04-29 13:34:47 -04:00
Hashen
75e0c7a2c9 bench: remove unused parameter
closes #4898
2022-04-28 22:00:49 -04:00
Douglas Christopher Wilson
e2482b7e36 build: ejs@3.1.7 2022-04-28 21:59:32 -04:00
Douglas Christopher Wilson
2df96e349f build: supertest@6.2.3 2022-04-28 13:04:38 -04:00
Douglas Christopher Wilson
a38fae126a build: mocha@9.2.2 2022-04-28 13:04:11 -04:00
Douglas Christopher Wilson
547fdd41dc 4.18.0 2022-04-25 14:53:28 -04:00
Deniz
0b330ef57c bench: print latency and vary connections
closes #4880
2022-04-24 19:31:42 -04:00
Douglas Christopher Wilson
158a17031a build: support Node.js 18.x 2022-04-21 02:09:08 -04:00
Douglas Christopher Wilson
29ea1b2f74 build: use 64-bit Node.js in AppVeyor 2022-04-21 01:38:59 -04:00
Douglas Christopher Wilson
11a209e4b7 build: support Node.js 17.x 2022-04-20 22:02:37 -04:00
phoenix
fd8e45c344 tests: mark stack overflow as long running
closes #4887
2022-04-20 19:52:20 -04:00
Douglas Christopher Wilson
708ac4cdf5 Fix handling very large stacks of sync middleware
closes #4891
2022-04-13 23:29:25 -04:00
Douglas Christopher Wilson
92c5ce59f5 deps: cookie@0.5.0 2022-04-11 22:51:13 -04:00
Hashen
8880ddad1c examples: add missing html label associations
closes #4884
2022-04-11 19:29:14 -04:00
Douglas Christopher Wilson
b91c7ffb28 examples: use http-errors to create errors 2022-04-11 19:28:50 -04:00
Eslam Salem
ecaf67c930 docs: remove Node Security Project from security policy
closes #4890
2022-04-11 18:54:33 -04:00
Ghouse Mohamed
99175c3ef6 docs: fix typo in casing of HTTP
closes #4872
2022-04-08 03:42:09 -04:00
Hashen
1b2e097be2 tests: fix typo in description
closes #4882
2022-04-07 19:20:41 -04:00
Douglas Christopher Wilson
04da4aaf1a build: use supertest@3.4.2 for Node.js 6.x 2022-04-07 19:17:10 -04:00
Douglas Christopher Wilson
2e2d78c4d9 deps: on-finished@2.4.1 2022-04-03 01:15:37 -04:00
3imed-jaberi
980d881e3b deps: statuses@2.0.1
closes #4336
2022-04-02 22:39:35 -04:00
Douglas Christopher Wilson
1df75763e3 deps: qs@6.10.3 2022-04-02 21:56:41 -04:00
Douglas Christopher Wilson
32c558d414 deps: body-parser@1.20.0 2022-04-02 21:51:31 -04:00
Douglas Christopher Wilson
a10770286e Use http-errors for res.format error 2022-03-27 23:41:31 -04:00
Chris Barth
5855339455 Fix behavior of null/undefined as "maxAge" in res.cookie
fixes #3935
closes #3936
2022-03-26 23:11:48 -04:00
Ulises Gascon
1cc8169938 deps: depd@2.0.0
closes #4174
2022-03-26 14:05:25 -04:00
Nadav Ivgi
9482b82d0b Invoke default with same arguments as types in res.format
closes #3587
2022-03-26 01:29:40 -04:00
Douglas Christopher Wilson
10b9b507b7 examples: use updated res.download in example 2022-03-25 18:14:27 -04:00
Douglas Christopher Wilson
03dc367187 Allow options without filename in res.download 2022-03-25 18:13:42 -04:00
Douglas Christopher Wilson
f739b162d9 deps: finalhandler@1.2.0 2022-03-25 01:46:32 -04:00
Douglas Christopher Wilson
c92420648e deps: serve-static@1.15.0 2022-03-25 01:44:51 -04:00
Douglas Christopher Wilson
dd69eedd18 deps: send@0.18.0 2022-03-25 01:43:45 -04:00
Tommaso Tofacchi
0def9bb659 Add "root" option to res.download
fixes #4834
closes #4855
2022-03-25 00:08:38 -04:00
Jon Church
4847d0efa1 Deprecate string and non-integer arguments to res.status
closes #4223
2022-03-23 23:14:08 -04:00
Evan Hahn
c17fe05861 Ignore Object.prototype values in settings through app.set/app.get
closes #4802
closes #4803
2022-03-23 20:05:05 -04:00
Tito D. Kesumo Siregar
87279c08aa Support proper 205 responses using res.send
closes #4592
closes #4596
2022-03-23 20:05:05 -04:00
Kris Kalavantavanich
8bf0720391 build: support Node.js 16.x 2022-03-23 20:05:05 -04:00
Kris Kalavantavanich
eb4c930d5f build: support Node.js 15.x 2022-03-23 20:05:05 -04:00
Hashen
947b6b7d57 lint: remove unnecessary continue statement in loop
closes #4868
2022-03-20 22:59:20 -04:00
Hashen
bf4c3ee00f docs: fix incomplete JSDoc comment
closes #4867
2022-03-20 20:51:39 -04:00
Hashen
2a7417dd84 examples: fixup html
closes #4866
2022-03-20 15:14:33 -04:00
Tobias Speicher
490f1a1738 lint: remove deprecated String.prototype.substr
closes #4860
2022-03-20 12:34:37 -04:00
Douglas Christopher Wilson
446046f886 build: mocha@9.2.1 2022-03-01 00:27:48 -05:00
Douglas Christopher Wilson
291993d73c tests: expand res.sendFile options tests 2022-03-01 00:22:09 -05:00
Steven
e8594c3571 docs: add install size badge
closes #3710
2022-02-28 23:41:41 -05:00
Douglas Christopher Wilson
07aa91f7cb docs: consolidate contributing in readme 2022-02-28 21:52:57 -05:00
Douglas Christopher Wilson
4ed35b4202 docs: switch badges to badgen 2022-02-28 21:23:49 -05:00
Douglas Christopher Wilson
ea66a9b81b docs: update link to github actions ci 2022-02-28 21:15:08 -05:00
apeltop
d0e166c3c6 docs: fix typo in private api jsdoc
closes #4843
2022-02-28 18:37:41 -05:00
Douglas Christopher Wilson
cf9f662655 tests: fix position of res.sendfile(path, options) test 2022-02-24 00:17:01 -05:00
Douglas Christopher Wilson
8da8f79c44 tests: fix callback in res.download test 2022-02-23 00:20:34 -05:00
Douglas Christopher Wilson
18f782bba9 tests: remove duplicate utils 2022-02-23 00:18:36 -05:00
Douglas Christopher Wilson
bc5ca05509 tests: remove usage of should 2022-02-21 19:54:52 -05:00
Douglas Christopher Wilson
9967ffbdc2 tests: update res.append to verify separate header lines 2022-02-21 19:23:25 -05:00
Douglas Christopher Wilson
7df0c840e0 tests: fix up app.locals tests 2022-02-21 19:07:26 -05:00
Douglas Christopher Wilson
d8ed591117 tests: fix req.acceptsLanguage tests 2022-02-20 23:49:42 -05:00
Douglas Christopher Wilson
8ee3420f0f tests: fix req.acceptsEncodings tests 2022-02-20 23:43:02 -05:00
Douglas Christopher Wilson
318fd4b543 Merge tag '4.17.3' 2022-02-17 00:27:11 -05:00
Douglas Christopher Wilson
3d7fce56a3 4.17.3 2022-02-16 21:03:42 -05:00
Douglas Christopher Wilson
f9063712e0 build: update example dependencies 2022-02-16 00:11:24 -05:00
Douglas Christopher Wilson
6381bc6317 deps: qs@6.9.7 2022-02-16 00:03:16 -05:00
Douglas Christopher Wilson
a007863096 deps: body-parser@1.19.2 2022-02-15 23:43:41 -05:00
Douglas Christopher Wilson
6faf26d59f 5.0.0-beta.1 2022-02-14 19:13:14 -05:00
Douglas Christopher Wilson
e98f5848a0 Revert "build: use minimatch@3.0.4 for Node.js < 4" 2022-02-14 18:42:47 -05:00
Douglas Christopher Wilson
a65913776d tests: use strict mode 2022-02-09 01:07:08 -05:00
Douglas Christopher Wilson
5213bd9fe7 docs: fix entry in history 2022-02-08 18:55:09 -05:00
Douglas Christopher Wilson
a39e409cf3 tests: prevent leaking changes to NODE_ENV 2022-02-08 18:40:07 -05:00
KoyamaSohei
82de4de5ab examples: fix path traversal in downloads example
closes #4120
2022-02-08 17:32:10 -05:00
Douglas Christopher Wilson
669c805615 deps: send@1.0.0-beta.1 2022-02-08 09:57:29 -05:00
Douglas Christopher Wilson
620df0e35e deps: serve-static@2.0.0-beta.1 2022-02-08 09:55:19 -05:00
Douglas Christopher Wilson
f6db4ee805 Drop support for Node.js below 4 2022-02-08 09:48:54 -05:00
Douglas Christopher Wilson
12310c5294 build: use nyc for test coverage 2022-02-07 23:08:12 -05:00
Thomas Strauß
884657d546 examples: remove bitwise syntax for includes check
closes #4814
2022-02-07 22:58:44 -05:00
Douglas Christopher Wilson
7511d08328 build: use minimatch@3.0.4 for Node.js < 4 2022-02-07 17:46:47 -05:00
Douglas Christopher Wilson
a0276c6c91 Use mime-types for file to content type mapping 2022-02-06 10:26:18 -05:00
Douglas Christopher Wilson
2585f209f9 tests: fix test missing assertion 2022-02-04 21:18:47 -05:00
Douglas Christopher Wilson
9d0976229d build: supertest@6.2.2 2022-02-04 21:14:41 -05:00
Douglas Christopher Wilson
43cc56eb9e build: clean up gitignore 2022-02-04 16:48:33 -05:00
Douglas Christopher Wilson
1c7bbcc143 build: Node.js@14.19 2022-02-04 16:36:47 -05:00
Douglas Christopher Wilson
9cbbc8ae74 deps: cookie@0.4.2 2022-02-04 16:35:50 -05:00
Douglas Christopher Wilson
6fbc269563 pref: remove unnecessary regexp for trust proxy 2022-02-04 16:34:56 -05:00
Douglas Christopher Wilson
2bc734aa3f deps: accepts@~1.3.8 2022-02-04 16:21:11 -05:00
caioagiani
89bb531b31 docs: fix typo in res.download jsdoc
closes #4805
2022-02-03 23:26:17 -05:00
Douglas Christopher Wilson
744564fcf8 tests: add test for multiple ips in "trust proxy" 2022-02-02 16:19:01 -05:00
Douglas Christopher Wilson
da6cb0ed8a tests: add range tests to res.download 2022-02-02 15:15:41 -05:00
Douglas Christopher Wilson
00ad5bee96 tests: add more tests for app.request & app.response 2022-02-02 15:02:46 -05:00
Douglas Christopher Wilson
141914e817 tests: fix tests that did not bubble errors 2022-02-02 14:16:20 -05:00
Douglas Christopher Wilson
bd4fdfe5f7 tests: remove global dependency on should
fixes #4797
2022-02-02 01:55:16 -05:00
Douglas Christopher Wilson
215f484fb4 tests: fix wording of req.accepts* test cases 2022-02-02 01:42:35 -05:00
Douglas Christopher Wilson
20047bb6e4 examples: use strict mode 2022-02-02 01:30:51 -05:00
Douglas Christopher Wilson
8b9757e8b8 build: fix running linter in CI 2022-02-02 01:25:55 -05:00
Douglas Christopher Wilson
a84e73b958 tests: add test for hello-world example 2022-02-02 01:23:40 -05:00
Douglas Christopher Wilson
69997cbdbe examples: fix error handling in auth example 2022-02-02 00:44:28 -05:00
Douglas Christopher Wilson
3d05e85b0c deps: array-flatten@3.0.0 2022-02-01 21:51:28 -05:00
Douglas Christopher Wilson
c221b8596e build: mocha@9.2.0 2022-01-27 19:02:58 -05:00
Czarek
450c468d04 Change query parser setting default to 'simple'
closes #3361
closes #3621
2021-12-17 23:15:29 -05:00
Douglas Christopher Wilson
af341b0f09 deps: body-parser@2.0.0-beta.1 2021-12-17 23:02:38 -05:00
Douglas Christopher Wilson
1574925cad deps: router@2.0.0-beta.1
closes #4321
2021-12-16 23:05:41 -05:00
Douglas Christopher Wilson
c7d528cdc0 Merge tag '4.17.2' 2021-12-16 23:01:28 -05:00
Alexander Belov
8aabecaf1f docs: fix typo in history
closes #4286
closes #4327
2020-06-29 00:29:30 -04:00
Douglas Christopher Wilson
bd04d8a87f 5.0.0-alpha.8 2020-03-25 20:14:47 -04:00
Douglas Christopher Wilson
121fe9982b Merge tag '4.17.1' 2019-06-08 19:43:21 -04:00
Douglas Christopher Wilson
5f0c829d7c 5.0.0-alpha.7 2018-10-26 22:29:15 -04:00
Douglas Christopher Wilson
c82fa19447 tests: add router promise tests 2018-10-26 21:31:28 -04:00
Douglas Christopher Wilson
fa22245cc6 deps: router@2.0.0-alpha.1 2018-10-23 21:02:44 -04:00
Douglas Christopher Wilson
302a6152b4 Merge tag '4.16.4' 2018-10-23 20:38:42 -04:00
Douglas Christopher Wilson
659fcc1598 deps: router@~1.3.2 2017-10-13 22:59:21 -04:00
Douglas Christopher Wilson
a163e2cdf4 deps: debug@3.1.0 2017-10-13 22:57:58 -04:00
Douglas Christopher Wilson
62e12fe710 Merge tag '4.16.2' 2017-10-13 22:27:30 -04:00
Douglas Christopher Wilson
8fabed82aa Remove path-to-regexp dependency 2017-10-13 22:12:14 -04:00
Douglas Christopher Wilson
f4120a6453 5.0.0-alpha.6 2017-09-25 01:28:00 -04:00
Douglas Christopher Wilson
19c8d64855 Merge tag '4.15.5' 2017-09-25 01:07:08 -04:00
Mike Tunnicliffe
71395f5933 Remove res.redirect(url, status) signature
closes #2941
2017-08-07 20:17:52 -04:00
Mike Tunnicliffe
e3bd14dcca Remove res.send(status, body) signature
closes #2942
2017-08-07 20:06:44 -04:00
Douglas Christopher Wilson
c319fe260a Merge tag '4.15.4' 2017-08-07 19:33:00 -04:00
Douglas Christopher Wilson
21f725e0ef 5.0.0-alpha.5 2017-03-06 08:43:58 -05:00
Douglas Christopher Wilson
e5dbb0cb4e Merge tag '4.15.2' 2017-03-06 08:40:02 -05:00
Douglas Christopher Wilson
a3a9166c52 5.0.0-alpha.4 2017-03-01 18:51:29 -05:00
Wes
06f423d4f5 Remove Express 3.x middleware error stubs
closes #3217
2017-03-01 18:29:48 -05:00
Douglas Christopher Wilson
501e24e0a9 Merge tag '4.15.0' 2017-03-01 18:17:04 -05:00
Douglas Christopher Wilson
c8d9223e93 5.0.0-alpha.3 2017-01-28 22:21:29 -05:00
Douglas Christopher Wilson
4b39a01e6a deps: path-is-absolute@1.0.1 2017-01-28 21:56:53 -05:00
Douglas Christopher Wilson
ad4d52de29 deps: array-flatten@2.1.1 2017-01-28 21:55:32 -05:00
Douglas Christopher Wilson
07077c4457 deps: router@~1.1.5 2017-01-28 21:54:42 -05:00
Douglas Christopher Wilson
bcbb9d56c5 Merge tag '4.14.1' 2017-01-28 21:02:36 -05:00
Mike Tunnicliffe
ab1c9e924e Remove res.jsonp(status, obj) signature
closes #2940
2017-01-27 23:53:41 -05:00
Mike Tunnicliffe
25fdefac45 Remove res.json(status, obj) signature
closes #2939
2017-01-27 23:46:54 -05:00
Mike Tunnicliffe
a856456a95 Remove res.vary() (no arguments) signature
closes #2943
2017-01-27 22:04:36 -05:00
Douglas Christopher Wilson
1dbfee6623 Merge tag '4.14.0' 2016-06-20 00:37:34 -04:00
Douglas Christopher Wilson
8a387d3ede deps: array-flatten@2.0.0 2016-01-21 21:28:24 -05:00
Douglas Christopher Wilson
943f28f05f deps: router@~1.1.3 2016-01-21 21:26:03 -05:00
Douglas Christopher Wilson
7cafdb5824 Merge tag '4.13.4' 2016-01-21 21:23:07 -05:00
Douglas Christopher Wilson
2c668f87c7 5.0.0-alpha.2 2015-07-07 01:33:55 -04:00
Douglas Christopher Wilson
6343288bef Make res.render callback is always async, even for sync view engines
closes #2668
2015-07-07 01:02:13 -04:00
Jeremiah Senkpiel
694869d2aa Use path-is-absolute module for absolute path detection
closes #2620
2015-07-06 23:55:17 -04:00
Douglas Christopher Wilson
cec5780db4 Use router module for routing
closes #2411
2015-07-06 23:46:00 -04:00
Douglas Christopher Wilson
21d52daafb Remove req.param() 2015-07-06 21:15:16 -04:00
Douglas Christopher Wilson
a7d15f382e Remove un-used depd import in router 2015-07-06 21:13:49 -04:00
Douglas Christopher Wilson
6c751191dd Remove utils.flatten 2015-07-06 21:12:44 -04:00
Douglas Christopher Wilson
1e2951a832 Remove app.param(fn) signature 2015-07-06 16:45:09 -04:00
Douglas Christopher Wilson
3a1f27fcde Remove ":" stripping from app.param() 2015-07-06 16:31:51 -04:00
Douglas Christopher Wilson
b309b873f1 Merge tag '4.13.1' 2015-07-06 16:13:54 -04:00
Douglas Christopher Wilson
f90e045334 Merge tag '4.12.4' 2015-05-18 00:41:42 -04:00
Douglas Christopher Wilson
f6ec710534 Merge tag '4.12.0' 2015-02-23 01:00:12 -05:00
Douglas Christopher Wilson
a9ef9e13fb Merge tag '4.11.2' 2015-02-01 15:41:51 -05:00
Douglas Christopher Wilson
f56e2a2503 docs: simplify 5.x history 2015-01-21 04:01:41 -05:00
Douglas Christopher Wilson
8a5ecd3d89 Merge tag '4.11.1' 2015-01-21 03:58:41 -05:00
Douglas Christopher Wilson
4052c15c7f 5.0.0-alpha.1 2014-11-06 21:52:29 -05:00
Douglas Christopher Wilson
97ccc52207 Remove res.send(status) signature 2014-11-06 21:20:46 -05:00
Douglas Christopher Wilson
0fc4f0735a Remove res.sendfile 2014-11-06 21:03:04 -05:00
Douglas Christopher Wilson
ccdbe4ea37 Remove req.acceptsLanguage 2014-11-06 20:54:29 -05:00
Douglas Christopher Wilson
59f2b4048a Remove acceptsEncoding 2014-11-06 20:53:17 -05:00
Douglas Christopher Wilson
7f2532808a Remove req.acceptsCharset 2014-11-06 20:52:14 -05:00
Douglas Christopher Wilson
be35e4927c Remove utils.contentDisposition 2014-11-06 20:48:32 -05:00
Douglas Christopher Wilson
f31dcff10c Remove app.del 2014-11-06 20:44:42 -05:00
Douglas Christopher Wilson
509ebb1aff Add app.router reference back 2014-11-06 20:20:33 -05:00
Douglas Christopher Wilson
78e50547f1 Refactor away init middleware 2014-11-06 20:18:51 -05:00
Douglas Christopher Wilson
dcc4eaabe8 Change req.query to a getter 2014-11-06 20:18:48 -05:00
Douglas Christopher Wilson
8c6f9c4253 Remove app.router error message 2014-11-06 20:18:44 -05:00
Douglas Christopher Wilson
88103063fe Remove res.jsonp(obj, status) signature 2014-11-06 20:18:42 -05:00
Douglas Christopher Wilson
164638b24f Remove res.json(obj, status) signature 2014-11-06 20:18:40 -05:00
Douglas Christopher Wilson
e66625be50 Remove res.send(body, status) signature 2014-11-06 20:18:39 -05:00
Douglas Christopher Wilson
085a29685a Change req.host to return host 2014-11-06 20:18:37 -05:00
164 changed files with 5816 additions and 4535 deletions

View File

@@ -1,4 +1,4 @@
# http://editorconfig.org
# https://editorconfig.org
root = true
[*]

View File

@@ -1,5 +1,7 @@
root: true
env:
es2022: true
node: true
rules:
eol-last: error
eqeqeq: [error, allow-null]

17
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,17 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: monthly
- package-ecosystem: npm
directory: /
schedule:
interval: monthly
time: "23:00"
timezone: Europe/London
open-pull-requests-limit: 10
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-major"]

View File

@@ -1,160 +1,114 @@
name: ci
on:
- pull_request
- push
push:
branches:
- master
- develop
- '4.x'
- '5.x'
- '5.0'
paths-ignore:
- '*.md'
pull_request:
paths-ignore:
- '*.md'
permissions:
contents: read
# Cancel in progress workflows
# in the scenario where we already had a run going for that PR/branch/tag but then triggered a new run
concurrency:
group: "${{ github.workflow }} ✨ ${{ github.event.pull_request.head.label || github.head_ref || github.ref }}"
cancel-in-progress: true
jobs:
test:
lint:
name: Lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 'lts/*'
- name: Install dependencies
run: npm install --ignore-scripts --include=dev
- name: Run lint
run: npm run lint
test:
strategy:
fail-fast: false
matrix:
name:
- Node.js 0.10
- Node.js 0.12
- io.js 1.x
- io.js 2.x
- io.js 3.x
- Node.js 4.x
- Node.js 5.x
- Node.js 6.x
- Node.js 7.x
- Node.js 8.x
- Node.js 9.x
- Node.js 10.x
- Node.js 11.x
- Node.js 12.x
- Node.js 13.x
- Node.js 14.x
os: [ubuntu-latest, windows-latest]
node-version: [18, 19, 20, 21, 22, 23]
# Node.js release schedule: https://nodejs.org/en/about/releases/
include:
- name: Node.js 0.10
node-version: "0.10"
npm-i: mocha@3.5.3 supertest@2.0.0
- name: Node.js 0.12
node-version: "0.12"
npm-i: mocha@3.5.3 supertest@2.0.0
- name: io.js 1.x
node-version: "1.8"
npm-i: mocha@3.5.3 supertest@2.0.0
- name: io.js 2.x
node-version: "2.5"
npm-i: mocha@3.5.3 supertest@2.0.0
- name: io.js 3.x
node-version: "3.3"
npm-i: mocha@3.5.3 supertest@2.0.0
- name: Node.js 4.x
node-version: "4.9"
npm-i: mocha@5.2.0 supertest@3.4.2
- name: Node.js 5.x
node-version: "5.12"
npm-i: mocha@5.2.0 supertest@3.4.2
- name: Node.js 6.x
node-version: "6.17"
npm-i: mocha@6.2.2
- name: Node.js 7.x
node-version: "7.10"
npm-i: mocha@6.2.2
- name: Node.js 8.x
node-version: "8.17"
npm-i: mocha@7.2.0
- name: Node.js 9.x
node-version: "9.11"
npm-i: mocha@7.2.0
- name: Node.js 10.x
node-version: "10.24"
npm-i: mocha@8.4.0
- name: Node.js 11.x
node-version: "11.15"
npm-i: mocha@8.4.0
- name: Node.js 12.x
node-version: "12.22"
- name: Node.js 13.x
node-version: "13.14"
- name: Node.js 14.x
node-version: "14.18"
name: Node.js ${{ matrix.node-version }} - ${{matrix.os}}
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Install Node.js ${{ matrix.node-version }}
shell: bash -eo pipefail -l {0}
run: |
nvm install --default ${{ matrix.node-version }}
dirname "$(nvm which ${{ matrix.node-version }})" >> "$GITHUB_PATH"
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- name: Configure npm
run: |
npm config set loglevel error
npm config set shrinkwrap false
- name: Configure npm loglevel
run: |
npm config set loglevel error
shell: bash
- name: Install npm module(s) ${{ matrix.npm-i }}
run: npm install --save-dev ${{ matrix.npm-i }}
if: matrix.npm-i != ''
- name: Install dependencies
run: npm install
- name: Remove non-test dependencies
run: npm rm --silent --save-dev connect-redis
- name: Output Node and NPM versions
run: |
echo "Node.js version: $(node -v)"
echo "NPM version: $(npm -v)"
- 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
node -pe 'Object.keys(require("./package").devDependencies).join("\n")' | \
grep -E '^eslint(-|$)' | \
sort -r | \
xargs -n1 npm rm --silent --save-dev
fi
- name: Run tests
shell: bash
run: npm run test-ci
- name: Install Node.js dependencies
run: npm install
- name: List environment
id: list_env
shell: bash
run: |
echo "node@$(node -v)"
echo "npm@$(npm -v)"
npm -s ls ||:
- name: Run tests
shell: bash
run: npm run test-ci
- name: Lint code
if: steps.list_env.outputs.eslint != ''
run: npm run lint
- name: Collect code coverage
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
flag-name: run-${{ matrix.test_number }}
parallel: true
- name: Upload code coverage
uses: actions/upload-artifact@v4
with:
name: coverage-node-${{ matrix.node-version }}-${{ matrix.os }}
path: ./coverage/lcov.info
retention-days: 1
coverage:
needs: test
runs-on: ubuntu-latest
permissions:
contents: read
checks: write
steps:
- name: Upload code coverage
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.github_token }}
parallel-finished: true
- uses: actions/checkout@v4
- name: Install lcov
shell: bash
run: sudo apt-get -y install lcov
- name: Collect coverage reports
uses: actions/download-artifact@v4
with:
path: ./coverage
pattern: coverage-node-*
- name: Merge coverage reports
shell: bash
run: find ./coverage -name lcov.info -exec printf '-a %q\n' {} \; | xargs lcov -o ./lcov.info
- name: Upload coverage report
uses: coverallsapp/github-action@v2
with:
file: ./lcov.info

66
.github/workflows/codeql.yml vendored Normal file
View File

@@ -0,0 +1,66 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: ["master"]
pull_request:
# The branches below must be a subset of the branches above
branches: ["master"]
schedule:
- cron: "0 0 * * 1"
permissions:
contents: read
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
steps:
- name: Checkout repository
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@3ab4101902695724f9365a384f86c1074d94e18c # v3.24.7
with:
languages: javascript
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
# - name: Autobuild
# uses: github/codeql-action/autobuild@3ab4101902695724f9365a384f86c1074d94e18c # v3.24.7
# Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
# If the Autobuild fails above, remove it and uncomment the following three lines.
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
# - run: |
# echo "Run, Build Application using script"
# ./location_of_script_within_repo/buildscript.sh
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@3ab4101902695724f9365a384f86c1074d94e18c # v3.24.7
with:
category: "/language:javascript"

98
.github/workflows/legacy.yml vendored Normal file
View File

@@ -0,0 +1,98 @@
name: legacy
on:
push:
branches:
- master
- develop
- '4.x'
- '5.x'
- '5.0'
paths-ignore:
- '*.md'
pull_request:
paths-ignore:
- '*.md'
permissions:
contents: read
# Cancel in progress workflows
# in the scenario where we already had a run going for that PR/branch/tag but then triggered a new run
concurrency:
group: "${{ github.workflow }} ✨ ${{ github.event.pull_request.head.label || github.head_ref || github.ref }}"
cancel-in-progress: true
jobs:
test:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
node-version: [16, 17]
# Node.js release schedule: https://nodejs.org/en/about/releases/
name: Node.js ${{ matrix.node-version }} - ${{matrix.os}}
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- name: Configure npm loglevel
run: |
npm config set loglevel error
shell: bash
- name: Install dependencies
run: npm install
- name: Output Node and NPM versions
run: |
echo "Node.js version: $(node -v)"
echo "NPM version: $(npm -v)"
- name: Run tests
shell: bash
run: npm run test-ci
- name: Upload code coverage
uses: actions/upload-artifact@v4
with:
name: coverage-node-${{ matrix.node-version }}-${{ matrix.os }}
path: ./coverage/lcov.info
retention-days: 1
coverage:
needs: test
runs-on: ubuntu-latest
permissions:
contents: read
checks: write
steps:
- uses: actions/checkout@v4
- name: Install lcov
shell: bash
run: sudo apt-get -y install lcov
- name: Collect coverage reports
uses: actions/download-artifact@v4
with:
path: ./coverage
pattern: coverage-node-*
- name: Merge coverage reports
shell: bash
run: find ./coverage -name lcov.info -exec printf '-a %q\n' {} \; | xargs lcov -o ./lcov.info
- name: Upload coverage report
uses: coverallsapp/github-action@v2
with:
file: ./lcov.info

72
.github/workflows/scorecard.yml vendored Normal file
View File

@@ -0,0 +1,72 @@
# This workflow uses actions that are not certified by GitHub. They are provided
# by a third-party and are governed by separate terms of service, privacy
# policy, and support documentation.
name: Scorecard supply-chain security
on:
# For Branch-Protection check. Only the default branch is supported. See
# https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection
branch_protection_rule:
# To guarantee Maintained check is occasionally updated. See
# https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained
schedule:
- cron: '16 21 * * 1'
push:
branches: [ "master" ]
# Declare default permissions as read only.
permissions: read-all
jobs:
analysis:
name: Scorecard analysis
runs-on: ubuntu-latest
permissions:
# Needed to upload the results to code-scanning dashboard.
security-events: write
# Needed to publish results and get a badge (see publish_results below).
id-token: write
# Uncomment the permissions below if installing in a private repository.
# contents: read
# actions: read
steps:
- name: "Checkout code"
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- name: "Run analysis"
uses: ossf/scorecard-action@62b2cac7ed8198b15735ed49ab1e5cf35480ba46 # v2.4.0
with:
results_file: results.sarif
results_format: sarif
# (Optional) "write" PAT token. Uncomment the `repo_token` line below if:
# - you want to enable the Branch-Protection check on a *public* repository, or
# - you are installing Scorecard on a *private* repository
# To create the PAT, follow the steps in https://github.com/ossf/scorecard-action#authentication-with-pat.
# repo_token: ${{ secrets.SCORECARD_TOKEN }}
# Public repositories:
# - Publish results to OpenSSF REST API for easy access by consumers
# - Allows the repository to include the Scorecard badge.
# - See https://github.com/ossf/scorecard-action#publishing-results.
# For private repositories:
# - `publish_results` will always be set to `false`, regardless
# of the value entered here.
publish_results: true
# Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
# format to the repository Actions tab.
- name: "Upload artifact"
uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0
with:
name: SARIF file
path: results.sarif
retention-days: 5
# Upload the results to GitHub's code scanning dashboard.
- name: "Upload to code-scanning"
uses: github/codeql-action/upload-sarif@dd746615b3b9d728a6a37ca2045b68ca76d4841a # v3.28.8
with:
sarif_file: results.sarif

21
.gitignore vendored
View File

@@ -1,27 +1,16 @@
# OS X
.DS_Store*
Icon?
._*
# Windows
Thumbs.db
ehthumbs.db
Desktop.ini
# Linux
.directory
*~
# npm
node_modules
package-lock.json
npm-shrinkwrap.json
*.log
*.gz
# Coveralls
.nyc_output
coverage
# Benchmarking
benchmarks/graphs
# ignore additional files using core.excludesFile
# https://git-scm.com/docs/gitignore

1
.npmrc Normal file
View File

@@ -0,0 +1 @@
package-lock=false

View File

@@ -9,7 +9,7 @@ also easily visible to outsiders.
## Section 1: Scope
Express is a http web server framework with a simple and expressive API
Express is a HTTP web server framework with a simple and expressive API
which is highly aligned with Node.js core. We aim to be the best in
class for writing performant, spec compliant, and powerful web servers
in Node.js. As one of the oldest and most popular web frameworks in
@@ -20,11 +20,11 @@ alike.
Express is made of many modules spread between three GitHub Orgs:
- [expressjs](http://github.com/expressjs/): Top level middleware and
- [expressjs](https://github.com/expressjs/): Top level middleware and
libraries
- [pillarjs](http://github.com/pillarjs/): Components which make up
- [pillarjs](https://github.com/pillarjs/): Components which make up
Express but can also be used for other web frameworks
- [jshttp](http://github.com/jshttp/): Low level http libraries
- [jshttp](https://github.com/jshttp/): Low level HTTP libraries
### 1.2: Out-of-Scope

View File

@@ -127,7 +127,7 @@ project community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant, version 2.0](cc-20-doc).
This Code of Conduct is adapted from the [Contributor Covenant, version 2.0][cc-20-doc].
Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).

View File

@@ -7,7 +7,7 @@ Open issues for the expressjs.com website in https://github.com/expressjs/expres
## PRs and Code contributions
* Tests must pass.
* Follow the [JavaScript Standard Style](http://standardjs.com/) and `npm run lint`.
* Follow the [JavaScript Standard Style](https://standardjs.com/) and `npm run lint`.
* If you fix a bug, add a test.
## Branches

View File

@@ -12,6 +12,7 @@ contributors can be involved in decision making.
* A **Contributor** is any individual creating or commenting on an issue or pull request.
* A **Committer** is a subset of contributors who have been given write access to the repository.
* A **Project Captain** is the lead maintainer of a repository.
* A **TC (Technical Committee)** is a group of committers representing the required technical
expertise to resolve rare disputes.
* A **Triager** is a subset of contributors who have been given triage access to the repository.
@@ -62,33 +63,19 @@ compromise among committers be the default resolution mechanism.
Anyone can become a triager! Read more about the process of being a triager in
[the triage process document](Triager-Guide.md).
[Open an issue in `expressjs/express` repo](https://github.com/expressjs/express/issues/new)
to request the triage role. State that you have read and agree to the
[Code of Conduct](Code-Of-Conduct.md) and details of the role.
Currently, any existing [organization member](https://github.com/orgs/expressjs/people) can nominate
a new triager. If you are interested in becoming a triager, our best advice is to actively participate
in the community by helping triaging issues and pull requests. As well we recommend
to engage in other community activities like attending the TC meetings, and participating in the Slack
discussions. If you feel ready and have been helping triage some issues, reach out to an active member of the organization to ask if they'd
be willing to support you. If they agree, they can create a pull request to formalize your nomination. In the case of an objection to the nomination, the triage team is responsible for working with the individuals involved and finding a resolution.
Here is an example issue content you can copy and paste:
```
Title: Request triager role for <your GitHub username>
I have read and understood the project's Code of Conduct.
I also have read and understood the process and best practices around Express triaging.
I request for a triager role for the following GitHub organizations:
jshttp
pillarjs
express
```
Once you have opened your issue, a member of the TC will add you to the `triage` team in
the organizations requested. They will then close the issue.
Happy triaging!
You can also reach out to any of the [organization members](https://github.com/orgs/expressjs/people)
if you have questions or need guidance.
## Becoming a Committer
All contributors who land a non-trivial contribution should be on-boarded in a timely manner,
All contributors who have landed significant and valuable contributions should be onboarded in a timely manner,
and added as a committer, and be given write access to the repository.
Committers are expected to follow this policy and continue to send pull requests, go through
@@ -102,12 +89,157 @@ If a consensus cannot be reached that has no objections then a majority wins vot
is called. It is also expected that the majority of decisions made by the TC are via
a consensus seeking process and that voting is only used as a last-resort.
Resolution may involve returning the issue to committers with suggestions on how to
move forward towards a consensus. It is not expected that a meeting of the TC
Resolution may involve returning the issue to project captains with suggestions on
how to move forward towards a consensus. It is not expected that a meeting of the TC
will resolve all issues on its agenda during that meeting and may prefer to continue
the discussion happening among the committers.
the discussion happening among the project captains.
Members can be added to the TC at any time. Any committer can nominate another committer
Members can be added to the TC at any time. Any TC member can nominate another committer
to the TC and the TC uses its standard consensus seeking process to evaluate whether or
not to add this new member. Members who do not participate consistently at the level of
a majority of the other members are expected to resign.
not to add this new member. The TC will consist of a minimum of 3 active members and a
maximum of 10. If the TC should drop below 5 members the active TC members should nominate
someone new. If a TC member is stepping down, they are encouraged (but not required) to
nominate someone to take their place.
TC members will be added as admin's on the Github orgs, npm orgs, and other resources as
necessary to be effective in the role.
To remain "active" a TC member should have participation within the last 12 months and miss
no more than six consecutive TC meetings. Our goal is to increase participation, not punish
people for any lack of participation, this guideline should be only be used as such
(replace an inactive member with a new active one, for example). Members who do not meet this
are expected to step down. If A TC member does not step down, an issue can be opened in the
discussions repo to move them to inactive status. TC members who step down or are removed due
to inactivity will be moved into inactive status.
Inactive status members can become active members by self nomination if the TC is not already
larger than the maximum of 10. They will also be given preference if, while at max size, an
active member steps down.
## Project Captains
The Express TC can designate captains for individual projects/repos in the
organizations. These captains are responsible for being the primary
day-to-day maintainers of the repo on a technical and community front.
Repo captains are empowered with repo ownership and package publication rights.
When there are conflicts, especially on topics that effect the Express project
at large, captains are responsible to raise it up to the TC and drive
those conflicts to resolution. Captains are also responsible for making sure
community members follow the community guidelines, maintaining the repo
and the published package, as well as in providing user support.
Like TC members, Repo captains are a subset of committers.
To become a captain for a project the candidate is expected to participate in that
project for at least 6 months as a committer prior to the request. They should have
helped with code contributions as well as triaging issues. They are also required to
have 2FA enabled on both their GitHub and npm accounts.
Any TC member or an existing captain on the **same** repo can nominate another committer
to the captain role. To do so, they should submit a PR to this document, updating the
**Active Project Captains** section (while maintaining the sort order) with the project
name, the nominee's GitHub handle, and their npm username (if different).
- Repos can have as many captains as make sense for the scope of work.
- A TC member or an existing repo captain **on the same project** can nominate a new captain.
Repo captains from other projects should not nominate captains for a different project.
The PR will require at least 2 approvals from TC members and 2 weeks hold time to allow
for comment and/or dissent. When the PR is merged, a TC member will add them to the
proper GitHub/npm groups.
### Active Projects and Captains
- [`expressjs/badgeboard`](https://github.com/expressjs/badgeboard): @wesleytodd
- [`expressjs/basic-auth-connect`](https://github.com/expressjs/basic-auth-connect): @ulisesGascon
- [`expressjs/body-parser`](https://github.com/expressjs/body-parser): @wesleytodd, @jonchurch, @ulisesGascon
- [`expressjs/compression`](https://github.com/expressjs/compression): @ulisesGascon
- [`expressjs/connect-multiparty`](https://github.com/expressjs/connect-multiparty): @ulisesGascon
- [`expressjs/cookie-parser`](https://github.com/expressjs/cookie-parser): @wesleytodd, @UlisesGascon
- [`expressjs/cookie-session`](https://github.com/expressjs/cookie-session): @ulisesGascon
- [`expressjs/cors`](https://github.com/expressjs/cors): @jonchurch, @ulisesGascon
- [`expressjs/discussions`](https://github.com/expressjs/discussions): @wesleytodd
- [`expressjs/errorhandler`](https://github.com/expressjs/errorhandler): @ulisesGascon
- [`expressjs/express-paginate`](https://github.com/expressjs/express-paginate): @ulisesGascon
- [`expressjs/express`](https://github.com/expressjs/express): @wesleytodd, @ulisesGascon
- [`expressjs/expressjs.com`](https://github.com/expressjs/expressjs.com): @crandmck, @jonchurch, @bjohansebas
- [`expressjs/flash`](https://github.com/expressjs/flash): @ulisesGascon
- [`expressjs/generator`](https://github.com/expressjs/generator): @wesleytodd
- [`expressjs/method-override`](https://github.com/expressjs/method-override): @ulisesGascon
- [`expressjs/morgan`](https://github.com/expressjs/morgan): @jonchurch, @ulisesGascon
- [`expressjs/multer`](https://github.com/expressjs/multer): @LinusU, @ulisesGascon
- [`expressjs/response-time`](https://github.com/expressjs/response-time): @UlisesGascon
- [`expressjs/serve-favicon`](https://github.com/expressjs/serve-favicon): @ulisesGascon
- [`expressjs/serve-index`](https://github.com/expressjs/serve-index): @ulisesGascon
- [`expressjs/serve-static`](https://github.com/expressjs/serve-static): @ulisesGascon
- [`expressjs/session`](https://github.com/expressjs/session): @ulisesGascon
- [`expressjs/statusboard`](https://github.com/expressjs/statusboard): @wesleytodd
- [`expressjs/timeout`](https://github.com/expressjs/timeout): @ulisesGascon
- [`expressjs/vhost`](https://github.com/expressjs/vhost): @ulisesGascon
- [`jshttp/accepts`](https://github.com/jshttp/accepts): @blakeembrey
- [`jshttp/basic-auth`](https://github.com/jshttp/basic-auth): @blakeembrey
- [`jshttp/compressible`](https://github.com/jshttp/compressible): @blakeembrey
- [`jshttp/content-disposition`](https://github.com/jshttp/content-disposition): @blakeembrey
- [`jshttp/content-type`](https://github.com/jshttp/content-type): @blakeembrey
- [`jshttp/cookie`](https://github.com/jshttp/cookie): @blakeembrey
- [`jshttp/etag`](https://github.com/jshttp/etag): @blakeembrey
- [`jshttp/forwarded`](https://github.com/jshttp/forwarded): @blakeembrey
- [`jshttp/fresh`](https://github.com/jshttp/fresh): @blakeembrey
- [`jshttp/http-assert`](https://github.com/jshttp/http-assert): @wesleytodd, @jonchurch, @ulisesGascon
- [`jshttp/http-errors`](https://github.com/jshttp/http-errors): @wesleytodd, @jonchurch, @ulisesGascon
- [`jshttp/media-typer`](https://github.com/jshttp/media-typer): @blakeembrey
- [`jshttp/methods`](https://github.com/jshttp/methods): @blakeembrey
- [`jshttp/mime-db`](https://github.com/jshttp/mime-db): @blakeembrey, @UlisesGascon
- [`jshttp/mime-types`](https://github.com/jshttp/mime-types): @blakeembrey, @UlisesGascon
- [`jshttp/negotiator`](https://github.com/jshttp/negotiator): @blakeembrey
- [`jshttp/on-finished`](https://github.com/jshttp/on-finished): @wesleytodd, @ulisesGascon
- [`jshttp/on-headers`](https://github.com/jshttp/on-headers): @blakeembrey
- [`jshttp/proxy-addr`](https://github.com/jshttp/proxy-addr): @wesleytodd, @ulisesGascon
- [`jshttp/range-parser`](https://github.com/jshttp/range-parser): @blakeembrey
- [`jshttp/statuses`](https://github.com/jshttp/statuses): @blakeembrey
- [`jshttp/type-is`](https://github.com/jshttp/type-is): @blakeembrey
- [`jshttp/vary`](https://github.com/jshttp/vary): @blakeembrey
- [`pillarjs/cookies`](https://github.com/pillarjs/cookies): @blakeembrey
- [`pillarjs/csrf`](https://github.com/pillarjs/csrf): @ulisesGascon
- [`pillarjs/encodeurl`](https://github.com/pillarjs/encodeurl): @blakeembrey
- [`pillarjs/finalhandler`](https://github.com/pillarjs/finalhandler): @wesleytodd, @ulisesGascon
- [`pillarjs/hbs`](https://github.com/pillarjs/hbs): @ulisesGascon
- [`pillarjs/multiparty`](https://github.com/pillarjs/multiparty): @blakeembrey
- [`pillarjs/parseurl`](https://github.com/pillarjs/parseurl): @blakeembrey
- [`pillarjs/path-to-regexp`](https://github.com/pillarjs/path-to-regexp): @blakeembrey
- [`pillarjs/request`](https://github.com/pillarjs/request): @wesleytodd
- [`pillarjs/resolve-path`](https://github.com/pillarjs/resolve-path): @blakeembrey
- [`pillarjs/router`](https://github.com/pillarjs/router): @wesleytodd, @ulisesGascon
- [`pillarjs/send`](https://github.com/pillarjs/send): @blakeembrey
- [`pillarjs/understanding-csrf`](https://github.com/pillarjs/understanding-csrf): @ulisesGascon
### Current Initiative Captains
- Triage team [ref](https://github.com/expressjs/discussions/issues/227): @UlisesGascon
## Developer's Certificate of Origin 1.1
```text
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```

View File

@@ -1,3 +1,355 @@
unreleased
========================
* Remove `utils-merge` dependency - use spread syntax instead
* Remove `Object.setPrototypeOf` polyfill
* cleanup: remove AsyncLocalStorage check from tests
* cleanup: remove unnecessary require for global Buffer
* perf: use loop for acceptParams
* Replace `methods` dependency with standard library
* refactor: prefix built-in node module imports
* Remove unused `depd` dependency
* Add support for `Uint8Array` in `res.send`
* Add support for ETag option in res.sendFile
* Extend res.links() to allow adding multiple links with the same rel
* deps: debug@^4.4.0
* deps: body-parser@^2.1.0
* deps: router@^2.1.0
* deps: nyc@^17.1.0
* deps: mocha@^10.7.3
* deps: marked@^15.0.3
* deps: express-session@^1.18.1
* deps: ejs@^3.1.10
* deps: content-type@^1.0.5
* deps: connect-redis@^8.0.1
* deps: supertest@^6.3.4
* deps: qs@^6.14.0
5.0.1 / 2024-10-08
==========
* Update `cookie` semver lock to address [CVE-2024-47764](https://nvd.nist.gov/vuln/detail/CVE-2024-47764)
5.0.0 / 2024-09-10
=========================
* remove:
- `path-is-absolute` dependency - use `path.isAbsolute` instead
* breaking:
* `res.status()` accepts only integers, and input must be greater than 99 and less than 1000
* will throw a `RangeError: Invalid status code: ${code}. Status code must be greater than 99 and less than 1000.` for inputs outside this range
* will throw a `TypeError: Invalid status code: ${code}. Status code must be an integer.` for non integer inputs
* deps: send@1.0.0
* `res.redirect('back')` and `res.location('back')` is no longer a supported magic string, explicitly use `req.get('Referrer') || '/'`.
* change:
- `res.clearCookie` will ignore user provided `maxAge` and `expires` options
* deps: cookie-signature@^1.2.1
* deps: debug@4.3.6
* deps: merge-descriptors@^2.0.0
* deps: serve-static@^2.1.0
* deps: qs@6.13.0
* deps: accepts@^2.0.0
* deps: mime-types@^3.0.0
- `application/javascript` => `text/javascript`
* deps: type-is@^2.0.0
* deps: content-disposition@^1.0.0
* deps: finalhandler@^2.0.0
* deps: fresh@^2.0.0
* deps: body-parser@^2.0.1
* deps: send@^1.1.0
5.0.0-beta.3 / 2024-03-25
=========================
This incorporates all changes after 4.19.1 up to 4.19.2.
5.0.0-beta.2 / 2024-03-20
=========================
This incorporates all changes after 4.17.2 up to 4.19.1.
5.0.0-beta.1 / 2022-02-14
=========================
This is the first Express 5.0 beta release, based off 4.17.2 and includes
changes from 5.0.0-alpha.8.
* change:
- Default "query parser" setting to `'simple'`
- Requires Node.js 4+
- Use `mime-types` for file to content type mapping
* deps: array-flatten@3.0.0
* deps: body-parser@2.0.0-beta.1
- `req.body` is no longer always initialized to `{}`
- `urlencoded` parser now defaults `extended` to `false`
- Use `on-finished` to determine when body read
* deps: router@2.0.0-beta.1
- Add new `?`, `*`, and `+` parameter modifiers
- Internalize private `router.process_params` method
- Matching group expressions are only RegExp syntax
- Named matching groups no longer available by position in `req.params`
- Regular expressions can only be used in a matching group
- Remove `debug` dependency
- Special `*` path segment behavior removed
- deps: array-flatten@3.0.0
- deps: parseurl@~1.3.3
- deps: path-to-regexp@3.2.0
- deps: setprototypeof@1.2.0
* deps: send@1.0.0-beta.1
- Change `dotfiles` option default to `'ignore'`
- Remove `hidden` option; use `dotfiles` option instead
- Use `mime-types` for file to content type mapping
- deps: debug@3.1.0
* deps: serve-static@2.0.0-beta.1
- Change `dotfiles` option default to `'ignore'`
- Remove `hidden` option; use `dotfiles` option instead
- Use `mime-types` for file to content type mapping
- Remove `express.static.mime` export; use `mime-types` package instead
- deps: send@1.0.0-beta.1
5.0.0-alpha.8 / 2020-03-25
==========================
This is the eighth Express 5.0 alpha release, based off 4.17.1 and includes
changes from 5.0.0-alpha.7.
5.0.0-alpha.7 / 2018-10-26
==========================
This is the seventh Express 5.0 alpha release, based off 4.16.4 and includes
changes from 5.0.0-alpha.6.
The major change with this alpha is the basic support for returned, rejected
Promises in the router.
* remove:
- `path-to-regexp` dependency
* deps: debug@3.1.0
- Add `DEBUG_HIDE_DATE` environment variable
- Change timer to per-namespace instead of global
- Change non-TTY date format
- Remove `DEBUG_FD` environment variable support
- Support 256 namespace colors
* deps: router@2.0.0-alpha.1
- Add basic support for returned, rejected Promises
- Fix JSDoc for `Router` constructor
- deps: debug@3.1.0
- deps: parseurl@~1.3.2
- deps: setprototypeof@1.1.0
- deps: utils-merge@1.0.1
5.0.0-alpha.6 / 2017-09-24
==========================
This is the sixth Express 5.0 alpha release, based off 4.15.5 and includes
changes from 5.0.0-alpha.5.
* remove:
- `res.redirect(url, status)` signature - use `res.redirect(status, url)`
- `res.send(status, body)` signature - use `res.status(status).send(body)`
* deps: router@~1.3.1
- deps: debug@2.6.8
5.0.0-alpha.5 / 2017-03-06
==========================
This is the fifth Express 5.0 alpha release, based off 4.15.2 and includes
changes from 5.0.0-alpha.4.
5.0.0-alpha.4 / 2017-03-01
==========================
This is the fourth Express 5.0 alpha release, based off 4.15.0 and includes
changes from 5.0.0-alpha.3.
* remove:
- Remove Express 3.x middleware error stubs
* deps: router@~1.3.0
- Add `next("router")` to exit from router
- Fix case where `router.use` skipped requests routes did not
- Skip routing when `req.url` is not set
- Use `%o` in path debug to tell types apart
- deps: debug@2.6.1
- deps: setprototypeof@1.0.3
- perf: add fast match path for `*` route
5.0.0-alpha.3 / 2017-01-28
==========================
This is the third Express 5.0 alpha release, based off 4.14.1 and includes
changes from 5.0.0-alpha.2.
* remove:
- `res.json(status, obj)` signature - use `res.status(status).json(obj)`
- `res.jsonp(status, obj)` signature - use `res.status(status).jsonp(obj)`
- `res.vary()` (no arguments) -- provide a field name as an argument
* deps: array-flatten@2.1.1
* deps: path-is-absolute@1.0.1
* deps: router@~1.1.5
- deps: array-flatten@2.0.1
- deps: methods@~1.1.2
- deps: parseurl@~1.3.1
- deps: setprototypeof@1.0.2
5.0.0-alpha.2 / 2015-07-06
==========================
This is the second Express 5.0 alpha release, based off 4.13.1 and includes
changes from 5.0.0-alpha.1.
* remove:
- `app.param(fn)`
- `req.param()` -- use `req.params`, `req.body`, or `req.query` instead
* change:
- `res.render` callback is always async, even for sync view engines
- The leading `:` character in `name` for `app.param(name, fn)` is no longer removed
- Use `router` module for routing
- Use `path-is-absolute` module for absolute path detection
5.0.0-alpha.1 / 2014-11-06
==========================
This is the first Express 5.0 alpha release, based off 4.10.1.
* remove:
- `app.del` - use `app.delete`
- `req.acceptsCharset` - use `req.acceptsCharsets`
- `req.acceptsEncoding` - use `req.acceptsEncodings`
- `req.acceptsLanguage` - use `req.acceptsLanguages`
- `res.json(obj, status)` signature - use `res.json(status, obj)`
- `res.jsonp(obj, status)` signature - use `res.jsonp(status, obj)`
- `res.send(body, status)` signature - use `res.send(status, body)`
- `res.send(status)` signature - use `res.sendStatus(status)`
- `res.sendfile` - use `res.sendFile` instead
- `express.query` middleware
* change:
- `req.host` now returns host (`hostname:port`) - use `req.hostname` for only hostname
- `req.query` is now a getter instead of a plain property
* add:
- `app.router` is a reference to the base router
4.20.0 / 2024-09-10
==========
* deps: serve-static@0.16.0
* Remove link renderization in html while redirecting
* deps: send@0.19.0
* Remove link renderization in html while redirecting
* deps: body-parser@0.6.0
* add `depth` option to customize the depth level in the parser
* IMPORTANT: The default `depth` level for parsing URL-encoded data is now `32` (previously was `Infinity`)
* Remove link renderization in html while using `res.redirect`
* deps: path-to-regexp@0.1.10
- Adds support for named matching groups in the routes using a regex
- Adds backtracking protection to parameters without regexes defined
* deps: encodeurl@~2.0.0
- Removes encoding of `\`, `|`, and `^` to align better with URL spec
* Deprecate passing `options.maxAge` and `options.expires` to `res.clearCookie`
- Will be ignored in v5, clearCookie will set a cookie with an expires in the past to instruct clients to delete the cookie
4.19.2 / 2024-03-25
==========
* Improved fix for open redirect allow list bypass
4.19.1 / 2024-03-20
==========
* Allow passing non-strings to res.location with new encoding handling checks
4.19.0 / 2024-03-20
==========
* Prevent open redirect allow list bypass due to encodeurl
* deps: cookie@0.6.0
4.18.3 / 2024-02-29
==========
* Fix routing requests without method
* deps: body-parser@1.20.2
- Fix strict json error message on Node.js 19+
- deps: content-type@~1.0.5
- deps: raw-body@2.5.2
* deps: cookie@0.6.0
- Add `partitioned` option
4.18.2 / 2022-10-08
===================
* Fix regression routing a large stack in a single route
* deps: body-parser@1.20.1
- deps: qs@6.11.0
- perf: remove unnecessary object clone
* deps: qs@6.11.0
4.18.1 / 2022-04-29
===================
* Fix hanging on large stack of sync routes
4.18.0 / 2022-04-25
===================
* Add "root" option to `res.download`
* Allow `options` without `filename` in `res.download`
* Deprecate string and non-integer arguments to `res.status`
* Fix behavior of `null`/`undefined` as `maxAge` in `res.cookie`
* Fix handling very large stacks of sync middleware
* Ignore `Object.prototype` values in settings through `app.set`/`app.get`
* Invoke `default` with same arguments as types in `res.format`
* Support proper 205 responses using `res.send`
* Use `http-errors` for `res.format` error
* deps: body-parser@1.20.0
- Fix error message for json parse whitespace in `strict`
- Fix internal error when inflated body exceeds limit
- Prevent loss of async hooks context
- Prevent hanging when request already read
- deps: depd@2.0.0
- deps: http-errors@2.0.0
- deps: on-finished@2.4.1
- deps: qs@6.10.3
- deps: raw-body@2.5.1
* deps: cookie@0.5.0
- Add `priority` option
- Fix `expires` option to reject invalid dates
* deps: depd@2.0.0
- Replace internal `eval` usage with `Function` constructor
- Use instance methods on `process` to check for listeners
* deps: finalhandler@1.2.0
- Remove set content headers that break response
- deps: on-finished@2.4.1
- deps: statuses@2.0.1
* deps: on-finished@2.4.1
- Prevent loss of async hooks context
* deps: qs@6.10.3
* deps: send@0.18.0
- Fix emitted 416 error missing headers property
- Limit the headers removed for 304 response
- deps: depd@2.0.0
- deps: destroy@1.2.0
- deps: http-errors@2.0.0
- deps: on-finished@2.4.1
- deps: statuses@2.0.1
* deps: serve-static@1.15.0
- deps: send@0.18.0
* deps: statuses@2.0.1
- Remove code 306
- Rename `425 Unordered Collection` to standard `425 Too Early`
4.17.3 / 2022-02-16
===================
* deps: accepts@~1.3.8
- deps: mime-types@~2.1.34
- deps: negotiator@0.6.3
* deps: body-parser@1.19.2
- deps: bytes@3.1.2
- deps: qs@6.9.7
- deps: raw-body@2.4.3
* deps: cookie@0.4.2
* deps: qs@6.9.7
* Fix handling of `__proto__` keys
* pref: remove unnecessary regexp for trust proxy
4.17.2 / 2021-12-16
===================
@@ -2033,7 +2385,7 @@
* deps: connect@2.21.0
- deprecate `connect(middleware)` -- use `app.use(middleware)` instead
- deprecate `connect.createServer()` -- use `connect()` instead
- fix `res.setHeader()` patch to work with with get -> append -> set pattern
- fix `res.setHeader()` patch to work with get -> append -> set pattern
- deps: compression@~1.0.8
- deps: errorhandler@~1.1.1
- deps: express-session@~1.5.0
@@ -3244,8 +3596,8 @@ Shaw]
* Added node v0.1.97 compatibility
* Added support for deleting cookies via Request#cookie('key', null)
* Updated haml submodule
* Fixed not-found page, now using using charset utf-8
* Fixed show-exceptions page, now using using charset utf-8
* Fixed not-found page, now using charset utf-8
* Fixed show-exceptions page, now using charset utf-8
* Fixed view support due to fs.readFile Buffers
* Changed; mime.type() no longer accepts ".type" due to node extname() changes
@@ -3280,7 +3632,7 @@ Shaw]
==================
* Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s
encoding is set to 'utf8' or 'utf-8'.
encoding is set to 'utf8' or 'utf-8').
* Added "encoding" option to Request#render(). Closes #299
* Added "dump exceptions" setting, which is enabled by default.
* Added simple ejs template engine support
@@ -3319,7 +3671,7 @@ Shaw]
* Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js
* Added callback function support to Request#halt() as 3rd/4th arg
* Added preprocessing of route param wildcards using param(). Closes #251
* Added view partial support (with collections etc)
* Added view partial support (with collections etc.)
* Fixed bug preventing falsey params (such as ?page=0). Closes #286
* Fixed setting of multiple cookies. Closes #199
* Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml)

214
Readme.md
View File

@@ -1,18 +1,35 @@
[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/)
[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](https://expressjs.com/)
Fast, unopinionated, minimalist web framework for [node](http://nodejs.org).
**Fast, unopinionated, minimalist web framework for [Node.js](https://nodejs.org).**
**This project has a [Code of Conduct][].**
## Table of contents
* [Installation](#Installation)
* [Features](#Features)
* [Docs & Community](#docs--community)
* [Quick Start](#Quick-Start)
* [Running Tests](#Running-Tests)
* [Philosophy](#Philosophy)
* [Examples](#Examples)
* [Contributing to Express](#Contributing)
* [TC (Technical Committee)](#tc-technical-committee)
* [Triagers](#triagers)
* [License](#license)
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-downloads-url]
[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer]
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Linux Build][ci-image]][ci-url]
[![Windows Build][appveyor-image]][appveyor-url]
[![Test Coverage][coveralls-image]][coveralls-url]
```js
const express = require('express')
import express from 'express'
const app = express()
app.get('/', function (req, res) {
app.get('/', (req, res) => {
res.send('Hello World')
})
@@ -25,7 +42,7 @@ This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/).
Before installing, [download and install Node.js](https://nodejs.org/en/download/).
Node.js 0.10 or higher is required.
Node.js 18 or higher is required.
If this is a brand new project, make sure to create a `package.json` first with
the [`npm init` command](https://docs.npmjs.com/creating-a-package-json-file).
@@ -34,10 +51,10 @@ Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
```bash
$ npm install express
npm install express
```
Follow [our installing guide](http://expressjs.com/en/starter/installing.html)
Follow [our installing guide](https://expressjs.com/en/starter/installing.html)
for more information.
## Features
@@ -52,18 +69,11 @@ for more information.
## Docs & Community
* [Website and Documentation](http://expressjs.com/) - [[website repo](https://github.com/expressjs/expressjs.com)]
* [#express](https://webchat.freenode.net/?channels=express) on freenode IRC
* [Website and Documentation](https://expressjs.com/) - [[website repo](https://github.com/expressjs/expressjs.com)]
* [GitHub Organization](https://github.com/expressjs) for Official Middleware & Modules
* Visit the [Wiki](https://github.com/expressjs/express/wiki)
* [Google Group](https://groups.google.com/group/express-js) for discussion
* [Gitter](https://gitter.im/expressjs/express) for support and discussion
* [Github Discussions](https://github.com/expressjs/discussions) for discussion on the development and usage of Express
**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).
### Security Issues
If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md).
**PROTIP** Be sure to read the [migration guide to v5](https://expressjs.com/en/guide/migrating-5)
## Quick Start
@@ -72,25 +82,25 @@ If you discover a security vulnerability in Express, please see [Security Polici
Install the executable. The executable's major version will match Express's:
```bash
$ npm install -g express-generator@4
npm install -g express-generator@4
```
Create the app:
```bash
$ express /tmp/foo && cd /tmp/foo
express /tmp/foo && cd /tmp/foo
```
Install dependencies:
```bash
$ npm install
npm install
```
Start the server:
```bash
$ npm start
npm start
```
View the website at: http://localhost:3000
@@ -102,57 +112,155 @@ $ npm start
HTTP APIs.
Express does not force you to use any specific ORM or template engine. With support for over
14 template engines via [Consolidate.js](https://github.com/tj/consolidate.js),
14 template engines via [@ladjs/consolidate](https://github.com/ladjs/consolidate),
you can quickly craft your perfect framework.
## Examples
To view the examples, clone the Express repo and install the dependencies:
To view the examples, clone the Express repository:
```bash
$ git clone git://github.com/expressjs/express.git --depth 1
$ cd express
$ npm install
git clone https://github.com/expressjs/express.git --depth 1 && cd express
```
Then install the dependencies:
```bash
npm install
```
Then run whichever example you want:
```bash
$ node examples/content-negotiation
```
## Tests
To run the test suite, first install the dependencies, then run `npm test`:
```bash
$ npm install
$ npm test
node examples/content-negotiation
```
## Contributing
[Contributing Guide](Contributing.md)
[![Linux Build][github-actions-ci-image]][github-actions-ci-url]
[![Test Coverage][coveralls-image]][coveralls-url]
The Express.js project welcomes all constructive contributions. Contributions take many forms,
from code for bug fixes and enhancements, to additions and fixes to documentation, additional
tests, triaging incoming pull requests and issues, and more!
See the [Contributing Guide](Contributing.md) for more technical details on contributing.
### Security Issues
If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md).
### Running Tests
To run the test suite, first install the dependencies:
```bash
npm install
```
Then run `npm test`:
```bash
npm test
```
## People
The original author of Express is [TJ Holowaychuk](https://github.com/tj)
The current lead maintainer is [Douglas Christopher Wilson](https://github.com/dougwilson)
[List of all contributors](https://github.com/expressjs/express/graphs/contributors)
### TC (Technical Committee)
* [UlisesGascon](https://github.com/UlisesGascon) - **Ulises Gascón** (he/him)
* [jonchurch](https://github.com/jonchurch) - **Jon Church**
* [wesleytodd](https://github.com/wesleytodd) - **Wes Todd**
* [LinusU](https://github.com/LinusU) - **Linus Unnebäck**
* [blakeembrey](https://github.com/blakeembrey) - **Blake Embrey**
* [sheplu](https://github.com/sheplu) - **Jean Burellier**
* [crandmck](https://github.com/crandmck) - **Rand McKinney**
* [ctcpip](https://github.com/ctcpip) - **Chris de Almeida**
<details>
<summary>TC emeriti members</summary>
#### TC emeriti members
* [dougwilson](https://github.com/dougwilson) - **Douglas Wilson**
* [hacksparrow](https://github.com/hacksparrow) - **Hage Yaapa**
* [jonathanong](https://github.com/jonathanong) - **jongleberry**
* [niftylettuce](https://github.com/niftylettuce) - **niftylettuce**
* [troygoode](https://github.com/troygoode) - **Troy Goode**
</details>
### Triagers
* [aravindvnair99](https://github.com/aravindvnair99) - **Aravind Nair**
* [bjohansebas](https://github.com/bjohansebas) - **Sebastian Beltran**
* [carpasse](https://github.com/carpasse) - **Carlos Serrano**
* [CBID2](https://github.com/CBID2) - **Christine Belzie**
* [dpopp07](https://github.com/dpopp07) - **Dustin Popp**
* [UlisesGascon](https://github.com/UlisesGascon) - **Ulises Gascón** (he/him)
* [mertcanaltin](https://github.com/mertcanaltin) - **Mert Can Altin**
* [3imed-jaberi](https://github.com/3imed-jaberi) - **Imed Jaberi**
* [IamLizu](https://github.com/IamLizu) - **S M Mahmudul Hasan** (he/him)
* [Phillip9587](https://github.com/Phillip9587) - **Phillip Barta**
* [Sushmeet](https://github.com/Sushmeet) - **Sushmeet Sunger**
* [rxmarbles](https://github.com/rxmarbles) **Rick Markins** (He/him)
<details>
<summary>Triagers emeriti members</summary>
#### Emeritus Triagers
* [AuggieH](https://github.com/AuggieH) - **Auggie Hudak**
* [G-Rath](https://github.com/G-Rath) - **Gareth Jones**
* [MohammadXroid](https://github.com/MohammadXroid) - **Mohammad Ayashi**
* [NawafSwe](https://github.com/NawafSwe) - **Nawaf Alsharqi**
* [NotMoni](https://github.com/NotMoni) - **Moni**
* [VigneshMurugan](https://github.com/VigneshMurugan) - **Vignesh Murugan**
* [davidmashe](https://github.com/davidmashe) - **David Ashe**
* [digitaIfabric](https://github.com/digitaIfabric) - **David**
* [e-l-i-s-e](https://github.com/e-l-i-s-e) - **Elise Bonner**
* [fed135](https://github.com/fed135) - **Frederic Charette**
* [firmanJS](https://github.com/firmanJS) - **Firman Abdul Hakim**
* [getspooky](https://github.com/getspooky) - **Yasser Ameur**
* [ghinks](https://github.com/ghinks) - **Glenn**
* [ghousemohamed](https://github.com/ghousemohamed) - **Ghouse Mohamed**
* [gireeshpunathil](https://github.com/gireeshpunathil) - **Gireesh Punathil**
* [jake32321](https://github.com/jake32321) - **Jake Reed**
* [jonchurch](https://github.com/jonchurch) - **Jon Church**
* [lekanikotun](https://github.com/lekanikotun) - **Troy Goode**
* [marsonya](https://github.com/marsonya) - **Lekan Ikotun**
* [mastermatt](https://github.com/mastermatt) - **Matt R. Wilson**
* [maxakuru](https://github.com/maxakuru) - **Max Edell**
* [mlrawlings](https://github.com/mlrawlings) - **Michael Rawlings**
* [rodion-arr](https://github.com/rodion-arr) - **Rodion Abdurakhimov**
* [sheplu](https://github.com/sheplu) - **Jean Burellier**
* [tarunyadav1](https://github.com/tarunyadav1) - **Tarun yadav**
* [tunniclm](https://github.com/tunniclm) - **Mike Tunnicliffe**
* [enyoghasim](https://github.com/enyoghasim) - **David Enyoghasim**
* [0ss](https://github.com/0ss) - **Salah**
* [import-brain](https://github.com/import-brain) - **Eric Cheng** (he/him)
* [dakshkhetan](https://github.com/dakshkhetan) - **Daksh Khetan** (he/him)
* [lucasraziel](https://github.com/lucasraziel) - **Lucas Soares Do Rego**
</details>
## License
[MIT](LICENSE)
[ci-image]: https://img.shields.io/github/workflow/status/expressjs/express/ci/master.svg?label=linux
[ci-url]: https://github.com/expressjs/express/actions?query=workflow%3Aci
[npm-image]: https://img.shields.io/npm/v/express.svg
[npm-url]: https://npmjs.org/package/express
[downloads-image]: https://img.shields.io/npm/dm/express.svg
[downloads-url]: https://npmcharts.com/compare/express?minimal=true
[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/express/master.svg?label=windows
[appveyor-url]: https://ci.appveyor.com/project/dougwilson/express
[coveralls-image]: https://img.shields.io/coveralls/expressjs/express/master.svg
[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/express/master
[coveralls-url]: https://coveralls.io/r/expressjs/express?branch=master
[github-actions-ci-image]: https://badgen.net/github/checks/expressjs/express/master?label=CI
[github-actions-ci-url]: https://github.com/expressjs/express/actions/workflows/ci.yml
[npm-downloads-image]: https://badgen.net/npm/dm/express
[npm-downloads-url]: https://npmcharts.com/compare/express?minimal=true
[npm-url]: https://npmjs.org/package/express
[npm-version-image]: https://badgen.net/npm/v/express
[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/express/badge
[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/express
[Code of Conduct]: https://github.com/expressjs/express/blob/master/Code-Of-Conduct.md

View File

@@ -31,7 +31,7 @@ Before publishing, the following preconditions should be met:
below) will exist documenting:
- the proposed changes
- the type of release: patch, minor or major
- the version number (according to semantic versioning - http://semver.org)
- the version number (according to semantic versioning - https://semver.org)
- The proposed changes should be complete.
There are two main release flows: patch and non-patch.
@@ -77,6 +77,13 @@ non-patch flow.
- This branch contains the commits accepted so far that implement the proposal
in the tracking pull request.
### Pre-release Versions
Alpha and Beta releases are made from a proposal branch. The version number should be
incremented to the next minor version with a `-beta` or `-alpha` suffix.
For example, if the next beta release is `5.0.1`, the beta release would be `5.0.1-beta.0`.
The pre-releases are unstable and not suitable for production use.
### Patch flow
In the patch flow, simple changes are committed to the release branch which
@@ -122,9 +129,10 @@ $ git merge --ff-only <proposal-branch>
<release-branch> - see "Release branch" of "Branches" above.
<proposal-branch> - see "Proposal branch" of "Non-patch flow" above.
**NOTE:** You may need to rebase the proposal branch to allow a fast-forward
merge. Using a fast-forward merge keeps the history clean as it does
not introduce merge commits.
> [!NOTE]
> You may need to rebase the proposal branch to allow a fast-forward
> merge. Using a fast-forward merge keeps the history clean as it does
> not introduce merge commits.
### Step 3. Update the History.md and package.json to the new version number
@@ -182,5 +190,13 @@ $ npm login <npm-username>
$ npm publish
```
**NOTE:** The version number to publish will be picked up automatically from
package.json.
> [!NOTE]
> The version number to publish will be picked up automatically from
> package.json.
### Step 7. Update documentation website
The documentation website https://expressjs.com/ documents the current release version in various places. To update these, follow these steps:
1. Manually run the [`Update External Docs` workflow](https://github.com/expressjs/expressjs.com/actions/workflows/update-external-docs.yml) in expressjs.com repository.
2. Add a new section to the [changelog](https://github.com/expressjs/expressjs.com/blob/gh-pages/en/changelog/index.md) in the expressjs.com website.

View File

@@ -14,7 +14,7 @@ Thank you for improving the security of Express. We appreciate your efforts and
responsible disclosure and will make every effort to acknowledge your
contributions.
Report security bugs by emailing the lead maintainer in the Readme.md file.
Report security bugs by emailing `express-security@lists.openjsf.org`.
To ensure the timely response to your report, please ensure that the entirety
of the report is contained within the email body and not solely behind a web
@@ -27,8 +27,13 @@ endeavor to keep you informed of the progress towards a fix and full
announcement, and may ask for additional information or guidance.
Report security bugs in third-party modules to the person or team maintaining
the module. You can also report a vulnerability through the
[Node Security Project](https://nodesecurity.io/report).
the module.
## Pre-release Versions
Alpha and Beta releases are unstable and **not suitable for production use**.
Vulnerabilities found in pre-releases should be reported according to the [Reporting a Bug](#reporting-a-bug) section.
Due to the unstable nature of the branch it is not guaranteed that any fixes will be released in the next pre-release.
## Disclosure Policy
@@ -41,6 +46,10 @@ involving the following steps:
* Prepare fixes for all releases still under maintenance. These fixes will be
released as fast as possible to npm.
## The Express Threat Model
We are currently working on a new version of the security model, the most updated version can be found [here](https://github.com/expressjs/security-wg/blob/main/docs/ThreatModel.md)
## Comments on this Policy
If you have suggestions on how this process could be improved please submit a

View File

@@ -9,11 +9,18 @@ classification:
* `needs triage`: This can be kept if the triager is unsure which next steps to take
* `awaiting more info`: If more info has been requested from the author, apply this label.
* `question`: User questions that do not appear to be bugs or enhancements.
* `discuss`: Topics for discussion. Might end in an `enhancement` or `question` label.
* `bug`: Issues that present a reasonable conviction there is a reproducible bug.
* `enhancement`: Issues that are found to be a reasonable candidate feature additions.
If the issue is a question or discussion, it should be moved to GitHub Discussions.
### Moving Discussions and Questions to GitHub Discussions
For issues labeled with `question` or `discuss`, it is recommended to move them to GitHub Discussions instead:
* **Questions**: User questions that do not appear to be bugs or enhancements should be moved to GitHub Discussions.
* **Discussions**: Topics for discussion should be moved to GitHub Discussions. If the discussion leads to a new feature or bug identification, it can be moved back to Issues.
In all cases, issues may be closed by maintainers if they don't receive a timely response when
further information is sought, or when additional questions are asked.
@@ -61,3 +68,5 @@ If you have questions feel free to reach out to any of the TC members.
- For recurring issues, it is helpful to create functional examples to demonstrate (publish as gists or a repo)
- Review and identify the maintainers. If necessary, at-mention one or more of them if you are unsure what to do
- Make sure all your interactions are professional, welcoming, and respectful to the parties involved.
- When an issue refers to security concerns, responsibility is delegated to the repository captain or the security group in any public communication.
- If an issue has been open for a long time, the person in charge should be contacted internally through the private Slack chat.

View File

@@ -1,83 +0,0 @@
environment:
matrix:
- nodejs_version: "0.10"
- nodejs_version: "0.12"
- nodejs_version: "1.8"
- nodejs_version: "2.5"
- nodejs_version: "3.3"
- nodejs_version: "4.9"
- nodejs_version: "5.12"
- nodejs_version: "6.17"
- nodejs_version: "7.10"
- nodejs_version: "8.17"
- nodejs_version: "9.11"
- nodejs_version: "10.24"
- nodejs_version: "11.15"
- nodejs_version: "12.22"
- nodejs_version: "13.14"
- nodejs_version: "14.18"
cache:
- node_modules
install:
# Install Node.js
- ps: >-
try { Install-Product node $env:nodejs_version -ErrorAction Stop }
catch { Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version) }
# Configure npm
- ps: |
npm config set loglevel error
npm config set shrinkwrap false
# Remove all non-test dependencies
- ps: |
# Remove example dependencies
npm rm --silent --save-dev connect-redis
# Remove lint dependencies
cmd.exe /c "node -pe `"Object.keys(require('./package').devDependencies).join('\n')`"" | `
sls "^eslint(-|$)" | `
%{ npm rm --silent --save-dev $_ }
# Setup Node.js version-specific dependencies
- ps: |
# mocha for testing
# - use 3.x for Node.js < 4
# - use 5.x for Node.js < 6
# - use 6.x for Node.js < 8
# - use 7.x for Node.js < 10
# - use 8.x for Node.js < 12
if ([int]$env:nodejs_version.split(".")[0] -lt 4) {
npm install --silent --save-dev mocha@3.5.3
} elseif ([int]$env:nodejs_version.split(".")[0] -lt 6) {
npm install --silent --save-dev mocha@5.2.0
} elseif ([int]$env:nodejs_version.split(".")[0] -lt 8) {
npm install --silent --save-dev mocha@6.2.2
} elseif ([int]$env:nodejs_version.split(".")[0] -lt 10) {
npm install --silent --save-dev mocha@7.2.0
} elseif ([int]$env:nodejs_version.split(".")[0] -lt 12) {
npm install --silent --save-dev mocha@8.4.0
}
- ps: |
# supertest for http calls
# - use 2.0.0 for Node.js < 4
# - use 3.4.2 for Node.js < 6
if ([int]$env:nodejs_version.split(".")[0] -lt 4) {
npm install --silent --save-dev supertest@2.0.0
} elseif ([int]$env:nodejs_version.split(".")[0] -lt 6) {
npm install --silent --save-dev supertest@3.4.2
}
# Update Node.js modules
- ps: |
# Prune & rebuild node_modules
if (Test-Path -Path node_modules) {
npm prune
npm rebuild
}
# Install Node.js modules
- npm install
build: off
test_script:
# Output version data
- ps: |
node --version
npm --version
# Run test script
- npm run test-ci
version: "{build}"

View File

@@ -1,13 +1,17 @@
all:
@./run 1 middleware
@./run 5 middleware
@./run 10 middleware
@./run 15 middleware
@./run 20 middleware
@./run 30 middleware
@./run 50 middleware
@./run 100 middleware
@./run 1 middleware 50
@./run 5 middleware 50
@./run 10 middleware 50
@./run 15 middleware 50
@./run 20 middleware 50
@./run 30 middleware 50
@./run 50 middleware 50
@./run 100 middleware 50
@./run 10 middleware 100
@./run 10 middleware 250
@./run 10 middleware 500
@./run 10 middleware 1000
@echo
.PHONY: all

34
benchmarks/README.md Normal file
View File

@@ -0,0 +1,34 @@
# Express Benchmarks
## Installation
You will need to install [wrk](https://github.com/wg/wrk/blob/master/INSTALL) in order to run the benchmarks.
## Running
To run the benchmarks, first install the dependencies `npm i`, then run `make`
The output will look something like this:
```
50 connections
1 middleware
7.15ms
6784.01
[...redacted...]
1000 connections
10 middleware
139.21ms
6155.19
```
### Tip: Include Node.js version in output
You can use `make && node -v` to include the node.js version in the output.
### Tip: Save the results to a file
You can use `make > results.log` to save the results to a file `results.log`.

View File

@@ -13,7 +13,7 @@ while (n--) {
});
}
app.use(function(req, res, next){
app.use(function(req, res){
res.send('Hello World')
});

View File

@@ -4,13 +4,15 @@ echo
MW=$1 node $2 &
pid=$!
echo " $3 connections"
sleep 2
wrk 'http://localhost:3333/?foo[bar]=baz' \
-d 3 \
-c 50 \
-c $3 \
-t 8 \
| grep 'Requests/sec' \
| awk '{ print " " $2 }'
| grep 'Requests/sec\|Latency' \
| awk '{ print " " $2 }'
kill $pid

View File

@@ -13,7 +13,6 @@ This page contains list of examples using Express.
- [hello-world](./hello-world) - Simple request handler
- [markdown](./markdown) - Markdown as template engine
- [multi-router](./multi-router) - Working with multiple Express routers
- [multipart](./multipart) - Accepting multipart-encoded forms
- [mvc](./mvc) - MVC-style controllers
- [online](./online) - Tracking online user activity with `online` and `redis` packages
- [params](./params) - Working with route parameters

View File

@@ -1,10 +1,12 @@
'use strict'
/**
* Module dependencies.
*/
var express = require('../..');
var hash = require('pbkdf2-password')()
var path = require('path');
var path = require('node:path');
var session = require('express-session');
var app = module.exports = express();
@@ -16,7 +18,7 @@ app.set('views', path.join(__dirname, 'views'));
// middleware
app.use(express.urlencoded({ extended: false }))
app.use(express.urlencoded())
app.use(session({
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
@@ -59,14 +61,14 @@ function authenticate(name, pass, fn) {
if (!module.parent) console.log('authenticating %s:%s', name, pass);
var user = users[name];
// query the db for the given username
if (!user) return fn(new Error('cannot find user'));
if (!user) return fn(null, null)
// apply the same algorithm to the POSTed password, applying
// the hash against the pass / salt, if there is a match we
// found the user
hash({ password: pass, salt: user.salt }, function (err, pass, salt, hash) {
if (err) return fn(err);
if (hash === user.hash) return fn(null, user)
fn(new Error('invalid password'));
fn(null, null)
});
}
@@ -99,8 +101,10 @@ app.get('/login', function(req, res){
res.render('login');
});
app.post('/login', function(req, res){
app.post('/login', function (req, res, next) {
if (!req.body) return res.sendStatus(400)
authenticate(req.body.username, req.body.password, function(err, user){
if (err) return next(err)
if (user) {
// Regenerate session when signing in
// to prevent fixation
@@ -112,7 +116,7 @@ app.post('/login', function(req, res){
req.session.success = 'Authenticated as ' + user.name
+ ' click to <a href="/logout">logout</a>. '
+ ' You may now access <a href="/restricted">/restricted</a>.';
res.redirect('back');
res.redirect(req.get('Referrer') || '/');
});
} else {
req.session.error = 'Authentication failed, please check your '

View File

@@ -10,7 +10,7 @@
font: 13px Helvetica, Arial, sans-serif;
}
.error {
color: red
color: red;
}
.success {
color: green;

View File

@@ -6,12 +6,12 @@
Try accessing <a href="/restricted">/restricted</a>, then authenticate with "tj" and "foobar".
<form method="post" action="/login">
<p>
<label>Username:</label>
<input type="text" name="username">
<label for="username">Username:</label>
<input type="text" name="username" id="username">
</p>
<p>
<label>Password:</label>
<input type="text" name="password">
<label for="password">Password:</label>
<input type="text" name="password" id="password">
</p>
<p>
<input type="submit" value="Login">

View File

@@ -1,3 +1,5 @@
'use strict'
var users = [];
users.push({ name: 'Tobi' });

View File

@@ -1,3 +1,5 @@
'use strict'
var express = require('../../');
var app = module.exports = express();
var users = require('./db');

View File

@@ -1,3 +1,4 @@
'use strict'
var users = require('./db');

View File

@@ -1,3 +1,5 @@
'use strict'
/**
* Module dependencies.
*/
@@ -11,13 +13,10 @@ var app = module.exports = express();
app.use(cookieSession({ secret: 'manny is cool' }));
// do something with the session
app.use(count);
// custom middleware
function count(req, res) {
app.get('/', function (req, res) {
req.session.count = (req.session.count || 0) + 1
res.send('viewed ' + req.session.count + ' times\n')
}
})
/* istanbul ignore next */
if (!module.parent) {

View File

@@ -1,3 +1,5 @@
'use strict'
/**
* Module dependencies.
*/
@@ -17,7 +19,7 @@ if (process.env.NODE_ENV !== 'test') app.use(logger(':method :url'))
app.use(cookieParser('my secret here'));
// parses x-www-form-urlencoded
app.use(express.urlencoded({ extended: false }))
app.use(express.urlencoded())
app.get('/', function(req, res){
if (req.cookies.remember) {
@@ -31,13 +33,17 @@ app.get('/', function(req, res){
app.get('/forget', function(req, res){
res.clearCookie('remember');
res.redirect('back');
res.redirect(req.get('Referrer') || '/');
});
app.post('/', function(req, res){
var minute = 60000;
if (req.body.remember) res.cookie('remember', 1, { maxAge: minute });
res.redirect('back');
if (req.body && req.body.remember) {
res.cookie('remember', 1, { maxAge: minute })
}
res.redirect(req.get('Referrer') || '/');
});
/* istanbul ignore next */

View File

@@ -1,11 +1,17 @@
'use strict'
/**
* Module dependencies.
*/
var express = require('../../');
var path = require('path');
var path = require('node:path');
var app = module.exports = express();
// path to where the files are stored on disk
var FILES_DIR = path.join(__dirname, 'files')
app.get('/', function(req, res){
res.send('<ul>' +
'<li>Download <a href="/files/notes/groceries.txt">notes/groceries.txt</a>.</li>' +
@@ -17,10 +23,8 @@ app.get('/', function(req, res){
// /files/* is accessed via req.params[0]
// but here we name it :file
app.get('/files/:file(*)', function(req, res, next){
var filePath = path.join(__dirname, 'files', req.params.file);
res.download(filePath, function (err) {
app.get('/files/*file', function (req, res, next) {
res.download(req.params.file.join('/'), { root: FILES_DIR }, function (err) {
if (!err) return; // file sent
if (err.status !== 404) return next(err); // non-404 error
// file for download not found

View File

@@ -1,9 +1,11 @@
'use strict'
/**
* Module dependencies.
*/
var express = require('../../');
var path = require('path');
var path = require('node:path');
var app = module.exports = express();

View File

@@ -1,9 +1,11 @@
'use strict'
/**
* Module dependencies.
*/
var express = require('../../');
var path = require('path');
var path = require('node:path');
var app = module.exports = express();
var logger = require('morgan');
var silent = process.env.NODE_ENV === 'test'

View File

@@ -1,3 +1,5 @@
'use strict'
/**
* Module dependencies.
*/
@@ -24,7 +26,7 @@ function error(err, req, res, next) {
res.send('Internal Server Error');
}
app.get('/', function(req, res){
app.get('/', function () {
// Caught and passed down to the errorHandler middleware
throw new Error('something broke!');
});

View File

@@ -1,6 +1,8 @@
'use strict'
var express = require('../../');
var app = express();
var app = module.exports = express()
app.get('/', function(req, res){
res.send('Hello World');

View File

@@ -1,12 +1,14 @@
'use strict'
/**
* Module dependencies.
*/
var escapeHtml = require('escape-html');
var express = require('../..');
var fs = require('fs');
var fs = require('node:fs');
var marked = require('marked');
var path = require('path');
var path = require('node:path');
var app = module.exports = express();
@@ -24,7 +26,7 @@ app.engine('md', function(path, options, fn){
app.set('views', path.join(__dirname, 'views'));
// make it the default so we dont need .md
// make it the default, so we don't need .md
app.set('view engine', 'md');
app.get('/', function(req, res){

View File

@@ -1,3 +1,5 @@
'use strict'
var express = require('../../..');
var apiv1 = express.Router();

View File

@@ -1,3 +1,5 @@
'use strict'
var express = require('../../..');
var apiv2 = express.Router();

View File

@@ -1,3 +1,5 @@
'use strict'
var express = require('../..');
var app = module.exports = express();

View File

@@ -1,60 +0,0 @@
/**
* Module dependencies.
*/
var express = require('../..');
var multiparty = require('multiparty');
var format = require('util').format;
var app = module.exports = express();
app.get('/', function(req, res){
res.send('<form method="post" enctype="multipart/form-data">'
+ '<p>Title: <input type="text" name="title" /></p>'
+ '<p>Image: <input type="file" name="image" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
app.post('/', function(req, res, next){
// create a form to begin parsing
var form = new multiparty.Form();
var image;
var title;
form.on('error', next);
form.on('close', function(){
res.send(format('\nuploaded %s (%d Kb) as %s'
, image.filename
, image.size / 1024 | 0
, title));
});
// listen on field event for title
form.on('field', function(name, val){
if (name !== 'title') return;
title = val;
});
// listen on part event for image file
form.on('part', function(part){
if (!part.filename) return;
if (part.name !== 'image') return part.resume();
image = {};
image.filename = part.filename;
image.size = 0;
part.on('data', function(buf){
image.size += buf.length;
});
});
// parse the form
form.parse(req);
});
/* istanbul ignore next */
if (!module.parent) {
app.listen(4000);
console.log('Express started on port 4000');
}

View File

@@ -1,3 +1,5 @@
'use strict'
exports.index = function(req, res){
res.redirect('/users');
};

View File

@@ -1,3 +1,5 @@
'use strict'
/**
* Module dependencies.
*/

View File

@@ -1,3 +1,5 @@
'use strict'
/**
* Module dependencies.
*/

View File

@@ -1,3 +1,5 @@
'use strict'
/**
* Module dependencies.
*/

View File

@@ -1,3 +1,5 @@
'use strict'
// faux database
var pets = exports.pets = [];

View File

@@ -1,10 +1,12 @@
'use strict'
/**
* Module dependencies.
*/
var express = require('../..');
var logger = require('morgan');
var path = require('path');
var path = require('node:path');
var session = require('express-session');
var methodOverride = require('method-override');

View File

@@ -1,10 +1,12 @@
'use strict'
/**
* Module dependencies.
*/
var express = require('../../..');
var fs = require('fs');
var path = require('path');
var fs = require('node:fs');
var path = require('node:path');
module.exports = function(parent, options){
var dir = path.join(__dirname, '..', 'controllers');

View File

@@ -1,3 +1,4 @@
'use strict'
// install redis first:
// https://redis.io/

View File

@@ -1,7 +1,10 @@
'use strict'
/**
* Module dependencies.
*/
var createError = require('http-errors')
var express = require('../../');
var app = module.exports = express();
@@ -15,14 +18,6 @@ var users = [
, { name: 'bandit' }
];
// Create HTTP error
function createError(status, message) {
var err = new Error(message);
err.status = status;
return err;
}
// Convert :to and :from to integers
app.param(['to', 'from'], function(req, res, next, num, name){
@@ -37,7 +32,8 @@ app.param(['to', 'from'], function(req, res, next, num, name){
// Load user by id
app.param('user', function(req, res, next, id){
if (req.user = users[id]) {
req.user = users[id]
if (req.user) {
next();
} else {
next(createError(404, 'failed to find user'));
@@ -56,7 +52,7 @@ app.get('/', function(req, res){
* GET :user.
*/
app.get('/user/:user', function(req, res, next){
app.get('/user/:user', function (req, res) {
res.send('user ' + req.user.name);
});
@@ -64,7 +60,7 @@ app.get('/user/:user', function(req, res, next){
* GET users :from - :to.
*/
app.get('/users/:from-:to', function(req, res, next){
app.get('/users/:from-:to', function (req, res) {
var from = req.params.from;
var to = req.params.to;
var names = users.map(function(user){ return user.name; });

View File

@@ -1,3 +1,5 @@
'use strict'
/**
* Module dependencies.
*/
@@ -10,7 +12,7 @@ var app = module.exports = express();
app.resource = function(path, obj) {
this.get(path, obj.index);
this.get(path + '/:a..:b.:format?', function(req, res){
this.get(path + '/:a..:b{.:format}', function(req, res){
var a = parseInt(req.params.a, 10);
var b = parseInt(req.params.b, 10);
var format = req.params.format;

View File

@@ -1,3 +1,5 @@
'use strict'
/**
* Module dependencies.
*/

View File

@@ -1,3 +1,5 @@
'use strict'
/**
* Module dependencies.
*/

View File

@@ -1,9 +1,11 @@
'use strict'
/**
* Module dependencies.
*/
var express = require('../..');
var path = require('path');
var path = require('node:path');
var app = express();
var logger = require('morgan');
var cookieParser = require('cookie-parser');
@@ -36,7 +38,7 @@ app.get('/', site.index);
// User
app.get('/users', user.list);
app.all('/user/:id/:op?', user.load);
app.all('/user/:id{/:op}', user.load);
app.get('/user/:id', user.view);
app.get('/user/:id/view', user.view);
app.get('/user/:id/edit', user.edit);

View File

@@ -1,3 +1,5 @@
'use strict'
// Fake posts database
var posts = [

View File

@@ -1,3 +1,5 @@
'use strict'
exports.index = function(req, res){
res.render('index', { title: 'Route Separation Example' });
};

View File

@@ -1,3 +1,5 @@
'use strict'
// Fake user database
var users = [
@@ -41,5 +43,5 @@ exports.update = function(req, res){
var user = req.body.user;
req.user.name = user.name;
req.user.email = user.email;
res.redirect('back');
res.redirect(req.get('Referrer') || '/');
};

View File

@@ -3,7 +3,7 @@
<h1>Editing <%= user.name %></h1>
<div id="user">
<form action="?_method=put", method="post">
<form action="?_method=put" method="post">
<p>
Name:
<input type="text" value="<%= user.name %>" name="user[name]" />

View File

@@ -1,3 +1,4 @@
'use strict'
// install redis first:
// https://redis.io/
@@ -11,7 +12,7 @@
*/
var express = require('../..');
var path = require('path');
var path = require('node:path');
var redis = require('redis');
var db = redis.createClient();
@@ -34,10 +35,10 @@ db.sadd('cat', 'luna');
* GET search for :query.
*/
app.get('/search/:query?', function(req, res){
app.get('/search/:query?', function(req, res, next){
var query = req.params.query;
db.smembers(query, function(err, vals){
if (err) return res.send(500);
if (err) return next(err);
res.send(vals);
});
});

View File

@@ -1,3 +1,5 @@
'use strict'
var search = document.querySelector('[type=search]');
var code = document.querySelector('pre');

View File

@@ -4,7 +4,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Search example</title>
<style type="text/css">
<style>
body {
font: 14px "Helvetica Neue", Helvetica;
padding: 50px;
@@ -15,7 +15,7 @@
<h2>Search</h2>
<p>Try searching for "ferret" or "cat".</p>
<input type="search" name="search" value="" />
<pre />
<pre></pre>
<script src="/client.js" charset="utf-8"></script>
</body>
</html>

View File

@@ -1,3 +1,4 @@
'use strict'
// install redis first:
// https://redis.io/

View File

@@ -1,3 +1,5 @@
'use strict'
/**
* Module dependencies.
*/

View File

@@ -1,10 +1,12 @@
'use strict'
/**
* Module dependencies.
*/
var express = require('../..');
var logger = require('morgan');
var path = require('path');
var path = require('node:path');
var app = express();
// log requests

View File

@@ -1,3 +1,5 @@
'use strict'
/**
* Module dependencies.
*/

View File

@@ -1,9 +1,11 @@
'use strict'
/**
* Module dependencies.
*/
var https = require('https');
var path = require('path');
var https = require('node:https');
var path = require('node:path');
var extname = path.extname;
/**

View File

@@ -1,3 +1,5 @@
'use strict'
/**
* Module dependencies.
*/

View File

@@ -1,9 +1,11 @@
'use strict'
/**
* Module dependencies.
*/
var express = require('../..');
var path = require('path');
var path = require('node:path');
var User = require('./user');
var app = express();
@@ -59,7 +61,7 @@ function users(req, res, next) {
})
}
app.get('/middleware', count, users, function(req, res, next){
app.get('/middleware', count, users, function (req, res) {
res.render('index', {
title: 'Users',
count: req.count,
@@ -97,7 +99,7 @@ function users2(req, res, next) {
})
}
app.get('/middleware-locals', count2, users2, function(req, res, next){
app.get('/middleware-locals', count2, users2, function (req, res) {
// you can see now how we have much less
// to pass to res.render(). If we have
// several routes related to users this

View File

@@ -1,3 +1,5 @@
'use strict'
module.exports = User;
// faux model

View File

@@ -1,3 +1,5 @@
'use strict'
/**
* Module dependencies.
*/
@@ -32,7 +34,7 @@ app.use('/api', function(req, res, next){
if (!key) return next(error(400, 'api key required'));
// key is invalid
if (!~apiKeys.indexOf(key)) return next(error(401, 'invalid api key'));
if (apiKeys.indexOf(key) === -1) return next(error(401, 'invalid api key'))
// all good, store req.key for route access
req.key = key;
@@ -70,12 +72,12 @@ var userRepos = {
// and simply expose the data
// example: http://localhost:3000/api/users/?api-key=foo
app.get('/api/users', function(req, res, next){
app.get('/api/users', function (req, res) {
res.send(users);
});
// example: http://localhost:3000/api/repos/?api-key=foo
app.get('/api/repos', function(req, res, next){
app.get('/api/repos', function (req, res) {
res.send(repos);
});

View File

@@ -14,22 +14,24 @@
*/
var finalhandler = require('finalhandler');
var Router = require('./router');
var methods = require('methods');
var middleware = require('./middleware/init');
var query = require('./middleware/query');
var debug = require('debug')('express:application');
var View = require('./view');
var http = require('http');
var http = require('node:http');
var methods = require('./utils').methods;
var compileETag = require('./utils').compileETag;
var compileQueryParser = require('./utils').compileQueryParser;
var compileTrust = require('./utils').compileTrust;
var deprecate = require('depd')('express');
var flatten = require('array-flatten');
var merge = require('utils-merge');
var resolve = require('path').resolve;
var setPrototypeOf = require('setprototypeof')
var resolve = require('node:path').resolve;
var once = require('once')
var Router = require('router');
/**
* Module variables.
* @private
*/
var slice = Array.prototype.slice;
var flatten = Array.prototype.flat;
/**
* Application prototype.
@@ -55,11 +57,29 @@ var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';
*/
app.init = function init() {
this.cache = {};
this.engines = {};
this.settings = {};
var router = null;
this.cache = Object.create(null);
this.engines = Object.create(null);
this.settings = Object.create(null);
this.defaultConfiguration();
// Setup getting to lazily add base router
Object.defineProperty(this, 'router', {
configurable: true,
enumerable: true,
get: function getrouter() {
if (router === null) {
router = new Router({
caseSensitive: this.enabled('case sensitive routing'),
strict: this.enabled('strict routing')
});
}
return router;
}
});
};
/**
@@ -74,7 +94,7 @@ app.defaultConfiguration = function defaultConfiguration() {
this.enable('x-powered-by');
this.set('etag', 'weak');
this.set('env', env);
this.set('query parser', 'extended');
this.set('query parser', 'simple')
this.set('subdomain offset', 2);
this.set('trust proxy', false);
@@ -95,10 +115,10 @@ app.defaultConfiguration = function defaultConfiguration() {
}
// inherit protos
setPrototypeOf(this.request, parent.request)
setPrototypeOf(this.response, parent.response)
setPrototypeOf(this.engines, parent.engines)
setPrototypeOf(this.settings, parent.settings)
Object.setPrototypeOf(this.request, parent.request)
Object.setPrototypeOf(this.response, parent.response)
Object.setPrototypeOf(this.engines, parent.engines)
Object.setPrototypeOf(this.settings, parent.settings)
});
// setup locals
@@ -118,32 +138,6 @@ app.defaultConfiguration = function defaultConfiguration() {
if (env === 'production') {
this.enable('view cache');
}
Object.defineProperty(this, 'router', {
get: function() {
throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');
}
});
};
/**
* lazily adds the base router if it has not yet been added.
*
* We cannot add the base router in the defaultConfiguration because
* it reads app settings which might be set after that has run.
*
* @private
*/
app.lazyrouter = function lazyrouter() {
if (!this._router) {
this._router = new Router({
caseSensitive: this.enabled('case sensitive routing'),
strict: this.enabled('strict routing')
});
this._router.use(query(this.get('query parser fn')));
this._router.use(middleware.init(this));
}
};
/**
@@ -156,22 +150,31 @@ app.lazyrouter = function lazyrouter() {
*/
app.handle = function handle(req, res, callback) {
var router = this._router;
// final handler
var done = callback || finalhandler(req, res, {
env: this.get('env'),
onerror: logerror.bind(this)
});
// no routes
if (!router) {
debug('no routes defined on app');
done();
return;
// set powered by header
if (this.enabled('x-powered-by')) {
res.setHeader('X-Powered-By', 'Express');
}
router.handle(req, res, done);
// set circular references
req.res = res;
res.req = req;
// alter the prototypes
Object.setPrototypeOf(req, this.request)
Object.setPrototypeOf(res, this.response)
// setup locals
if (!res.locals) {
res.locals = Object.create(null);
}
this.router.handle(req, res, done);
};
/**
@@ -204,15 +207,14 @@ app.use = function use(fn) {
}
}
var fns = flatten(slice.call(arguments, offset));
var fns = flatten.call(slice.call(arguments, offset), Infinity);
if (fns.length === 0) {
throw new TypeError('app.use() requires a middleware function')
}
// setup router
this.lazyrouter();
var router = this._router;
// get router
var router = this.router;
fns.forEach(function (fn) {
// non-express app
@@ -228,8 +230,8 @@ app.use = function use(fn) {
router.use(path, function mounted_app(req, res, next) {
var orig = req.app;
fn.handle(req, res, function (err) {
setPrototypeOf(req, orig.request)
setPrototypeOf(res, orig.response)
Object.setPrototypeOf(req, orig.request)
Object.setPrototypeOf(res, orig.response)
next(err);
});
});
@@ -252,8 +254,7 @@ app.use = function use(fn) {
*/
app.route = function route(path) {
this.lazyrouter();
return this._router.route(path);
return this.router.route(path);
};
/**
@@ -319,8 +320,6 @@ app.engine = function engine(ext, fn) {
*/
app.param = function param(name, fn) {
this.lazyrouter();
if (Array.isArray(name)) {
for (var i = 0; i < name.length; i++) {
this.param(name[i], fn);
@@ -329,7 +328,7 @@ app.param = function param(name, fn) {
return this;
}
this._router.param(name, fn);
this.router.param(name, fn);
return this;
};
@@ -469,16 +468,14 @@ app.disable = function disable(setting) {
* Delegate `.VERB(...)` calls to `router.VERB(...)`.
*/
methods.forEach(function(method){
app[method] = function(path){
methods.forEach(function (method) {
app[method] = function (path) {
if (method === 'get' && arguments.length === 1) {
// app.get(setting)
return this.set(path);
}
this.lazyrouter();
var route = this._router.route(path);
var route = this.route(path);
route[method].apply(route, slice.call(arguments, 1));
return this;
};
@@ -495,9 +492,7 @@ methods.forEach(function(method){
*/
app.all = function all(path) {
this.lazyrouter();
var route = this._router.route(path);
var route = this.route(path);
var args = slice.call(arguments, 1);
for (var i = 0; i < methods.length; i++) {
@@ -507,10 +502,6 @@ app.all = function all(path) {
return this;
};
// del -> delete alias
app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');
/**
* Render the given view `name` name with `options`
* and a callback accepting an error and the
@@ -533,7 +524,6 @@ app.render = function render(name, options, callback) {
var done = callback;
var engines = this.engines;
var opts = options;
var renderOptions = {};
var view;
// support callback function as second arg
@@ -542,16 +532,8 @@ app.render = function render(name, options, callback) {
opts = {};
}
// merge app.locals
merge(renderOptions, this.locals);
// merge options._locals
if (opts._locals) {
merge(renderOptions, opts._locals);
}
// merge options
merge(renderOptions, opts);
var renderOptions = { ...this.locals, ...opts._locals, ...opts };
// set .cache unless explicitly provided
if (renderOptions.cache == null) {
@@ -601,8 +583,8 @@ app.render = function render(name, options, callback) {
* and HTTPS server you may do so with the "http"
* and "https" modules as shown here:
*
* var http = require('http')
* , https = require('https')
* var http = require('node:http')
* , https = require('node:https')
* , express = require('express')
* , app = express();
*
@@ -614,9 +596,14 @@ app.render = function render(name, options, callback) {
*/
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
var server = http.createServer(this)
var args = Array.prototype.slice.call(arguments)
if (typeof args[args.length - 1] === 'function') {
var done = args[args.length - 1] = once(args[args.length - 1])
server.once('error', done)
}
return server.listen.apply(server, args)
}
/**
* Log error using console.error.

View File

@@ -13,11 +13,10 @@
*/
var bodyParser = require('body-parser')
var EventEmitter = require('events').EventEmitter;
var EventEmitter = require('node:events').EventEmitter;
var mixin = require('merge-descriptors');
var proto = require('./application');
var Route = require('./router/route');
var Router = require('./router');
var Router = require('router');
var req = require('./request');
var res = require('./response');
@@ -68,7 +67,7 @@ exports.response = res;
* Expose constructors.
*/
exports.Route = Route;
exports.Route = Router.Route;
exports.Router = Router;
/**
@@ -76,41 +75,7 @@ exports.Router = Router;
*/
exports.json = bodyParser.json
exports.query = require('./middleware/query');
exports.raw = bodyParser.raw
exports.static = require('serve-static');
exports.text = bodyParser.text
exports.urlencoded = bodyParser.urlencoded
/**
* Replace removed middleware with an appropriate error message.
*/
var removedMiddlewares = [
'bodyParser',
'compress',
'cookieSession',
'session',
'logger',
'cookieParser',
'favicon',
'responseTime',
'errorHandler',
'timeout',
'methodOverride',
'vhost',
'csrf',
'directory',
'limit',
'multipart',
'staticCache'
]
removedMiddlewares.forEach(function (name) {
Object.defineProperty(exports, name, {
get: function () {
throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.');
},
configurable: true
});
});

View File

@@ -1,43 +0,0 @@
/*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var setPrototypeOf = require('setprototypeof')
/**
* Initialization middleware, exposing the
* request and response to each other, as well
* as defaulting the X-Powered-By header field.
*
* @param {Function} app
* @return {Function}
* @api private
*/
exports.init = function(app){
return function expressInit(req, res, next){
if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express');
req.res = res;
res.req = req;
req.next = next;
setPrototypeOf(req, app.request)
setPrototypeOf(res, app.response)
res.locals = res.locals || Object.create(null);
next();
};
};

View File

@@ -1,47 +0,0 @@
/*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
*/
var merge = require('utils-merge')
var parseUrl = require('parseurl');
var qs = require('qs');
/**
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = function query(options) {
var opts = merge({}, options)
var queryparse = qs.parse;
if (typeof options === 'function') {
queryparse = options;
opts = undefined;
}
if (opts !== undefined && opts.allowPrototypes === undefined) {
// back-compat for qs module
opts.allowPrototypes = true;
}
return function query(req, res, next){
if (!req.query) {
var val = parseUrl(req).query;
req.query = queryparse(val, opts);
}
next();
};
};

View File

@@ -14,10 +14,9 @@
*/
var accepts = require('accepts');
var deprecate = require('depd')('express');
var isIP = require('net').isIP;
var isIP = require('node:net').isIP;
var typeis = require('type-is');
var http = require('http');
var http = require('node:http');
var fresh = require('fresh');
var parseRange = require('range-parser');
var parse = require('parseurl');
@@ -147,9 +146,6 @@ req.acceptsEncodings = function(){
return accept.encodings.apply(accept, arguments);
};
req.acceptsEncoding = deprecate.function(req.acceptsEncodings,
'req.acceptsEncoding: Use acceptsEncodings instead');
/**
* Check if the given `charset`s are acceptable,
* otherwise you should respond with 406 "Not Acceptable".
@@ -164,9 +160,6 @@ req.acceptsCharsets = function(){
return accept.charsets.apply(accept, arguments);
};
req.acceptsCharset = deprecate.function(req.acceptsCharsets,
'req.acceptsCharset: Use acceptsCharsets instead');
/**
* Check if the given `lang`s are acceptable,
* otherwise you should respond with 406 "Not Acceptable".
@@ -181,9 +174,6 @@ req.acceptsLanguages = function(){
return accept.languages.apply(accept, arguments);
};
req.acceptsLanguage = deprecate.function(req.acceptsLanguages,
'req.acceptsLanguage: Use acceptsLanguages instead');
/**
* Parse Range header field, capping to the given `size`.
*
@@ -216,38 +206,27 @@ req.range = function range(size, options) {
};
/**
* Return the value of param `name` when present or `defaultValue`.
* Parse the query string of `req.url`.
*
* - Checks route placeholders, ex: _/user/:id_
* - Checks body params, ex: id=12, {"id":12}
* - Checks query string params, ex: ?id=12
* This uses the "query parser" setting to parse the raw
* string into an object.
*
* To utilize request bodies, `req.body`
* should be an object. This can be done by using
* the `bodyParser()` middleware.
*
* @param {String} name
* @param {Mixed} [defaultValue]
* @return {String}
* @public
* @api public
*/
req.param = function param(name, defaultValue) {
var params = this.params || {};
var body = this.body || {};
var query = this.query || {};
defineGetter(req, 'query', function query(){
var queryparse = this.app.get('query parser fn');
var args = arguments.length === 1
? 'name'
: 'name, default';
deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead');
if (!queryparse) {
// parsing is disabled
return Object.create(null);
}
if (null != params[name] && params.hasOwnProperty(name)) return params[name];
if (null != body[name]) return body[name];
if (null != query[name]) return query[name];
var querystring = parse(this).query;
return defaultValue;
};
return queryparse(querystring);
});
/**
* Check if the incoming request contains the "Content-Type"
@@ -414,7 +393,7 @@ defineGetter(req, 'path', function path() {
});
/**
* Parse the "Host" header field to a hostname.
* Parse the "Host" header field to a host.
*
* When the "trust proxy" setting trusts the socket
* address, the "X-Forwarded-Host" header field will
@@ -424,18 +403,35 @@ defineGetter(req, 'path', function path() {
* @public
*/
defineGetter(req, 'hostname', function hostname(){
defineGetter(req, 'host', function host(){
var trust = this.app.get('trust proxy fn');
var host = this.get('X-Forwarded-Host');
var val = this.get('X-Forwarded-Host');
if (!host || !trust(this.connection.remoteAddress, 0)) {
host = this.get('Host');
} else if (host.indexOf(',') !== -1) {
if (!val || !trust(this.connection.remoteAddress, 0)) {
val = this.get('Host');
} else if (val.indexOf(',') !== -1) {
// Note: X-Forwarded-Host is normally only ever a
// single value, but this is to be safe.
host = host.substring(0, host.indexOf(',')).trimRight()
val = val.substring(0, val.indexOf(',')).trimRight()
}
return val || undefined;
});
/**
* Parse the "Host" header field to a hostname.
*
* When the "trust proxy" setting trusts the socket
* address, the "X-Forwarded-Host" header field will
* be trusted.
*
* @return {String}
* @api public
*/
defineGetter(req, 'hostname', function hostname(){
var host = this.host;
if (!host) return;
// IPv6 literal support
@@ -449,15 +445,9 @@ defineGetter(req, 'hostname', function hostname(){
: host;
});
// TODO: change req.host to return host in next major
defineGetter(req, 'host', deprecate.function(function host(){
return this.hostname;
}, 'req.host: Use req.hostname instead'));
/**
* Check if the request is fresh, aka
* Last-Modified and/or the ETag
* Last-Modified or the ETag
* still match.
*
* @return {Boolean}

View File

@@ -12,17 +12,16 @@
* @private
*/
var Buffer = require('safe-buffer').Buffer
var contentDisposition = require('content-disposition');
var deprecate = require('depd')('express');
var createError = require('http-errors')
var encodeUrl = require('encodeurl');
var escapeHtml = require('escape-html');
var http = require('http');
var isAbsolute = require('./utils').isAbsolute;
var http = require('node:http');
var onFinished = require('on-finished');
var path = require('path');
var mime = require('mime-types')
var path = require('node:path');
var pathIsAbsolute = require('node:path').isAbsolute;
var statuses = require('statuses')
var merge = require('utils-merge');
var sign = require('cookie-signature').sign;
var normalizeType = require('./utils').normalizeType;
var normalizeTypes = require('./utils').normalizeTypes;
@@ -30,7 +29,6 @@ var setCharset = require('./utils').setCharset;
var cookie = require('cookie');
var send = require('send');
var extname = path.extname;
var mime = send.mime;
var resolve = path.resolve;
var vary = require('vary');
@@ -49,21 +47,28 @@ var res = Object.create(http.ServerResponse.prototype)
module.exports = res
/**
* Module variables.
* @private
*/
var charsetRegExp = /;\s*charset\s*=/;
/**
* Set status `code`.
* Set the HTTP status code for the response.
*
* @param {Number} code
* @return {ServerResponse}
* Expects an integer value between 100 and 999 inclusive.
* Throws an error if the provided status code is not an integer or if it's outside the allowable range.
*
* @param {number} code - The HTTP status code to set.
* @return {ServerResponse} - Returns itself for chaining methods.
* @throws {TypeError} If `code` is not an integer.
* @throws {RangeError} If `code` is outside the range 100 to 999.
* @public
*/
res.status = function status(code) {
// Check if the status code is not an integer
if (!Number.isInteger(code)) {
throw new TypeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be an integer.`);
}
// Check if the status code is outside of Node's valid range
if (code < 100 || code > 999) {
throw new RangeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be greater than 99 and less than 1000.`);
}
this.statusCode = code;
return this;
};
@@ -75,7 +80,11 @@ res.status = function status(code) {
*
* res.links({
* next: 'http://api.example.com/users?page=2',
* last: 'http://api.example.com/users?page=5'
* last: 'http://api.example.com/users?page=5',
* pages: [
* 'http://api.example.com/users?page=1',
* 'http://api.example.com/users?page=2'
* ]
* });
*
* @param {Object} links
@@ -83,11 +92,18 @@ res.status = function status(code) {
* @public
*/
res.links = function(links){
res.links = function(links) {
var link = this.get('Link') || '';
if (link) link += ', ';
return this.set('Link', link + Object.keys(links).map(function(rel){
return '<' + links[rel] + '>; rel="' + rel + '"';
return this.set('Link', link + Object.keys(links).map(function(rel) {
// Allow multiple links if links[rel] is an array
if (Array.isArray(links[rel])) {
return links[rel].map(function (singleLink) {
return `<${singleLink}>; rel="${rel}"`;
}).join(', ');
} else {
return `<${links[rel]}>; rel="${rel}"`;
}
}).join(', '));
};
@@ -113,31 +129,6 @@ res.send = function send(body) {
// settings
var app = this.app;
// allow status / body
if (arguments.length === 2) {
// res.send(body, status) backwards compat
if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {
deprecate('res.send(body, status): Use res.status(status).send(body) instead');
this.statusCode = arguments[1];
} else {
deprecate('res.send(status, body): Use res.status(status).send(body) instead');
this.statusCode = arguments[0];
chunk = arguments[1];
}
}
// disambiguate res.send(status) and res.send(status, num)
if (typeof chunk === 'number' && arguments.length === 1) {
// res.send(status) will set status message as text string
if (!this.get('Content-Type')) {
this.type('txt');
}
deprecate('res.send(status): Use res.sendStatus(status) instead');
this.statusCode = chunk;
chunk = statuses[chunk]
}
switch (typeof chunk) {
// string defaulting to html
case 'string':
@@ -150,7 +141,7 @@ res.send = function send(body) {
case 'object':
if (chunk === null) {
chunk = '';
} else if (Buffer.isBuffer(chunk)) {
} else if (ArrayBuffer.isView(chunk)) {
if (!this.get('Content-Type')) {
this.type('bin');
}
@@ -203,7 +194,7 @@ res.send = function send(body) {
}
// freshness
if (req.fresh) this.statusCode = 304;
if (req.fresh) this.status(304);
// strip irrelevant headers
if (204 === this.statusCode || 304 === this.statusCode) {
@@ -213,6 +204,13 @@ res.send = function send(body) {
chunk = '';
}
// alter headers for 205
if (this.statusCode === 205) {
this.set('Content-Length', '0')
this.removeHeader('Transfer-Encoding')
chunk = ''
}
if (req.method === 'HEAD') {
// skip body for HEAD
this.end();
@@ -237,27 +235,12 @@ res.send = function send(body) {
*/
res.json = function json(obj) {
var val = obj;
// allow status / body
if (arguments.length === 2) {
// res.json(body, status) backwards compat
if (typeof arguments[1] === 'number') {
deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');
this.statusCode = arguments[1];
} else {
deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');
this.statusCode = arguments[0];
val = arguments[1];
}
}
// settings
var app = this.app;
var escape = app.get('json escape')
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = stringify(val, replacer, spaces, escape)
var body = stringify(obj, replacer, spaces, escape)
// content-type
if (!this.get('Content-Type')) {
@@ -280,27 +263,12 @@ res.json = function json(obj) {
*/
res.jsonp = function jsonp(obj) {
var val = obj;
// allow status / body
if (arguments.length === 2) {
// res.jsonp(body, status) backwards compat
if (typeof arguments[1] === 'number') {
deprecate('res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead');
this.statusCode = arguments[1];
} else {
deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');
this.statusCode = arguments[0];
val = arguments[1];
}
}
// settings
var app = this.app;
var escape = app.get('json escape')
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = stringify(val, replacer, spaces, escape)
var body = stringify(obj, replacer, spaces, escape)
var callback = this.req.query[app.get('jsonp callback name')];
// content-type
@@ -356,9 +324,9 @@ res.jsonp = function jsonp(obj) {
*/
res.sendStatus = function sendStatus(statusCode) {
var body = statuses[statusCode] || String(statusCode)
var body = statuses.message[statusCode] || String(statusCode)
this.statusCode = statusCode;
this.status(statusCode);
this.type('txt');
return this.send(body);
@@ -426,12 +394,15 @@ res.sendFile = function sendFile(path, options, callback) {
opts = {};
}
if (!opts.root && !isAbsolute(path)) {
if (!opts.root && !pathIsAbsolute(path)) {
throw new TypeError('path must be absolute or specify root to res.sendFile');
}
// create file stream
var pathname = encodeURI(path);
// wire application etag option to send
opts.etag = this.app.enabled('etag');
var file = send(req, pathname, opts);
// transfer
@@ -446,85 +417,13 @@ res.sendFile = function sendFile(path, options, callback) {
});
};
/**
* Transfer the file at the given `path`.
*
* Automatically sets the _Content-Type_ response header field.
* The callback `callback(err)` is invoked when the transfer is complete
* or when an error occurs. Be sure to check `res.headersSent`
* if you wish to attempt responding, as the header and some data
* may have already been transferred.
*
* Options:
*
* - `maxAge` defaulting to 0 (can be string converted by `ms`)
* - `root` root directory for relative filenames
* - `headers` object of headers to serve with file
* - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
*
* Other options are passed along to `send`.
*
* Examples:
*
* The following example illustrates how `res.sendfile()` may
* be used as an alternative for the `static()` middleware for
* dynamic situations. The code backing `res.sendfile()` is actually
* the same code, so HTTP cache support etc is identical.
*
* app.get('/user/:uid/photos/:file', function(req, res){
* var uid = req.params.uid
* , file = req.params.file;
*
* req.user.mayViewFilesFrom(uid, function(yes){
* if (yes) {
* res.sendfile('/uploads/' + uid + '/' + file);
* } else {
* res.send(403, 'Sorry! you cant see that.');
* }
* });
* });
*
* @public
*/
res.sendfile = function (path, options, callback) {
var done = callback;
var req = this.req;
var res = this;
var next = req.next;
var opts = options || {};
// support function as second arg
if (typeof options === 'function') {
done = options;
opts = {};
}
// create file stream
var file = send(req, path, opts);
// transfer
sendfile(res, file, opts, function (err) {
if (done) return done(err);
if (err && err.code === 'EISDIR') return next();
// next() all but write errors
if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {
next(err);
}
});
};
res.sendfile = deprecate.function(res.sendfile,
'res.sendfile: Use res.sendFile instead');
/**
* Transfer the file at the given `path` as an attachment.
*
* Optionally providing an alternate attachment `filename`,
* and optional callback `callback(err)`. The callback is invoked
* when the data transfer is complete, or when an error has
* ocurred. Be sure to check `res.headersSent` if you plan to respond.
* occurred. Be sure to check `res.headersSent` if you plan to respond.
*
* Optionally providing an `options` object to use with `res.sendFile()`.
* This function will set the `Content-Disposition` header, overriding
@@ -551,6 +450,13 @@ res.download = function download (path, filename, options, callback) {
opts = null
}
// support optional filename, where options may be in it's place
if (typeof filename === 'object' &&
(typeof options === 'function' || options === undefined)) {
name = null
opts = filename
}
// set Content-Disposition when file is sent
var headers = {
'Content-Disposition': contentDisposition(name || path)
@@ -572,15 +478,19 @@ res.download = function download (path, filename, options, callback) {
opts.headers = headers
// Resolve the full path for sendFile
var fullPath = resolve(path);
var fullPath = !opts.root
? resolve(path)
: path
// send file
return this.sendFile(fullPath, opts, done)
};
/**
* Set _Content-Type_ response header with `type` through `mime.lookup()`
* Set _Content-Type_ response header with `type` through `mime.contentType()`
* when it does not contain "/", or set the Content-Type to `type` otherwise.
* When no mapping is found though `mime.contentType()`, the type is set to
* "application/octet-stream".
*
* Examples:
*
@@ -598,7 +508,7 @@ res.download = function download (path, filename, options, callback) {
res.contentType =
res.type = function contentType(type) {
var ct = type.indexOf('/') === -1
? mime.lookup(type)
? (mime.contentType(type) || 'application/octet-stream')
: type;
return this.set('Content-Type', ct);
@@ -665,9 +575,8 @@ res.format = function(obj){
var req = this.req;
var next = req.next;
var fn = obj.default;
if (fn) delete obj.default;
var keys = Object.keys(obj);
var keys = Object.keys(obj)
.filter(function (v) { return v !== 'default' })
var key = keys.length > 0
? req.accepts(keys)
@@ -678,13 +587,12 @@ res.format = function(obj){
if (key) {
this.set('Content-Type', normalizeType(key).value);
obj[key](req, this, next);
} else if (fn) {
fn();
} else if (obj.default) {
obj.default(req, this, next)
} else {
var err = new Error('Not Acceptable');
err.status = err.statusCode = 406;
err.types = normalizeTypes(keys).map(function(o){ return o.value });
next(err);
next(createError(406, {
types: normalizeTypes(keys).map(function (o) { return o.value })
}))
}
return this;
@@ -749,6 +657,9 @@ res.append = function append(field, val) {
*
* Aliased as `res.header()`.
*
* When the set header is "Content-Type", the type is expanded to include
* the charset if not present using `mime.contentType()`.
*
* @param {String|Object} field
* @param {String|Array} val
* @return {ServerResponse} for chaining
@@ -767,10 +678,7 @@ res.header = function header(field, val) {
if (Array.isArray(value)) {
throw new TypeError('Content-Type cannot be set to an Array');
}
if (!charsetRegExp.test(value)) {
var charset = mime.charsets.lookup(value.split(';')[0]);
if (charset) value += '; charset=' + charset.toLowerCase();
}
value = mime.contentType(value)
}
this.setHeader(field, value);
@@ -804,7 +712,10 @@ res.get = function(field){
*/
res.clearCookie = function clearCookie(name, options) {
var opts = merge({ expires: new Date(1), path: '/' }, options);
// Force cookie expiration by setting expires to the past
const opts = { path: '/', ...options, expires: new Date(1)};
// ensure maxAge is not passed
delete opts.maxAge
return this.cookie(name, '', opts);
};
@@ -834,7 +745,7 @@ res.clearCookie = function clearCookie(name, options) {
*/
res.cookie = function (name, value, options) {
var opts = merge({}, options);
var opts = { ...options };
var secret = this.req.secret;
var signed = opts.signed;
@@ -850,9 +761,13 @@ res.cookie = function (name, value, options) {
val = 's:' + sign(val, secret);
}
if ('maxAge' in opts) {
opts.expires = new Date(Date.now() + opts.maxAge);
opts.maxAge /= 1000;
if (opts.maxAge != null) {
var maxAge = opts.maxAge - 0
if (!isNaN(maxAge)) {
opts.expires = new Date(Date.now() + maxAge)
opts.maxAge = Math.floor(maxAge / 1000)
}
}
if (opts.path == null) {
@@ -882,25 +797,13 @@ res.cookie = function (name, value, options) {
*/
res.location = function location(url) {
var loc = url;
// "back" is an alias for the referrer
if (url === 'back') {
loc = this.req.get('Referrer') || '/';
}
// set location
return this.set('Location', encodeUrl(loc));
return this.set('Location', encodeUrl(url));
};
/**
* Redirect to the given `url` with optional response `status`
* defaulting to 302.
*
* The resulting `url` is determined by `res.location()`, so
* it will play nicely with mounted apps, relative paths,
* `"back"` etc.
*
* Examples:
*
* res.redirect('/foo/bar');
@@ -918,13 +821,20 @@ res.redirect = function redirect(url) {
// allow status / url
if (arguments.length === 2) {
if (typeof arguments[0] === 'number') {
status = arguments[0];
address = arguments[1];
} else {
deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');
status = arguments[1];
}
status = arguments[0]
address = arguments[1]
}
if (!address) {
throw new TypeError('url argument is required to res.redirect');
}
if (typeof address !== 'string') {
throw new TypeError('res.redirect: url must be a string');
}
if (typeof status !== 'number') {
throw new TypeError('res.redirect: status must be a number');
}
// Set location header
@@ -933,12 +843,12 @@ res.redirect = function redirect(url) {
// Support text/{plain,html} by default
this.format({
text: function(){
body = statuses[status] + '. Redirecting to ' + address
body = statuses.message[status] + '. Redirecting to ' + address
},
html: function(){
var u = escapeHtml(address);
body = '<p>' + statuses[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'
body = '<p>' + statuses.message[status] + '. Redirecting to ' + u + '</p>'
},
default: function(){
@@ -947,7 +857,7 @@ res.redirect = function redirect(url) {
});
// Respond
this.statusCode = status;
this.status(status);
this.set('Content-Length', Buffer.byteLength(body));
if (this.req.method === 'HEAD') {
@@ -967,12 +877,6 @@ res.redirect = function redirect(url) {
*/
res.vary = function(field){
// checks for back-compat
if (!field || (Array.isArray(field) && !field.length)) {
deprecate('res.vary(): Provide a field name');
return this;
}
vary(this, field);
return this;
@@ -1113,7 +1017,7 @@ function sendfile(res, file, options, callback) {
* ability to escape characters that can trigger HTML sniffing.
*
* @param {*} value
* @param {function} replaces
* @param {function} replacer
* @param {number} spaces
* @param {boolean} escape
* @returns {string}

View File

@@ -1,668 +0,0 @@
/*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var Route = require('./route');
var Layer = require('./layer');
var methods = require('methods');
var mixin = require('utils-merge');
var debug = require('debug')('express:router');
var deprecate = require('depd')('express');
var flatten = require('array-flatten');
var parseUrl = require('parseurl');
var setPrototypeOf = require('setprototypeof')
/**
* Module variables.
* @private
*/
var objectRegExp = /^\[object (\S+)\]$/;
var slice = Array.prototype.slice;
var toString = Object.prototype.toString;
/**
* Initialize a new `Router` with the given `options`.
*
* @param {Object} [options]
* @return {Router} which is an callable function
* @public
*/
var proto = module.exports = function(options) {
var opts = options || {};
function router(req, res, next) {
router.handle(req, res, next);
}
// mixin Router class functions
setPrototypeOf(router, proto)
router.params = {};
router._params = [];
router.caseSensitive = opts.caseSensitive;
router.mergeParams = opts.mergeParams;
router.strict = opts.strict;
router.stack = [];
return router;
};
/**
* Map the given param placeholder `name`(s) to the given callback.
*
* Parameter mapping is used to provide pre-conditions to routes
* which use normalized placeholders. For example a _:user_id_ parameter
* could automatically load a user's information from the database without
* any additional code,
*
* The callback uses the same signature as middleware, the only difference
* being that the value of the placeholder is passed, in this case the _id_
* of the user. Once the `next()` function is invoked, just like middleware
* it will continue on to execute the route, or subsequent parameter functions.
*
* Just like in middleware, you must either respond to the request or call next
* to avoid stalling the request.
*
* app.param('user_id', function(req, res, next, id){
* User.find(id, function(err, user){
* if (err) {
* return next(err);
* } else if (!user) {
* return next(new Error('failed to load user'));
* }
* req.user = user;
* next();
* });
* });
*
* @param {String} name
* @param {Function} fn
* @return {app} for chaining
* @public
*/
proto.param = function param(name, fn) {
// param logic
if (typeof name === 'function') {
deprecate('router.param(fn): Refactor to use path params');
this._params.push(name);
return;
}
// apply param functions
var params = this._params;
var len = params.length;
var ret;
if (name[0] === ':') {
deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead');
name = name.substr(1);
}
for (var i = 0; i < len; ++i) {
if (ret = params[i](name, fn)) {
fn = ret;
}
}
// ensure we end up with a
// middleware function
if ('function' !== typeof fn) {
throw new Error('invalid param() call for ' + name + ', got ' + fn);
}
(this.params[name] = this.params[name] || []).push(fn);
return this;
};
/**
* Dispatch a req, res into the router.
* @private
*/
proto.handle = function handle(req, res, out) {
var self = this;
debug('dispatching %s %s', req.method, req.url);
var idx = 0;
var protohost = getProtohost(req.url) || ''
var removed = '';
var slashAdded = false;
var paramcalled = {};
// store options for OPTIONS request
// only used if OPTIONS request
var options = [];
// middleware and routes
var stack = self.stack;
// manage inter-router variables
var parentParams = req.params;
var parentUrl = req.baseUrl || '';
var done = restore(out, req, 'baseUrl', 'next', 'params');
// setup next layer
req.next = next;
// for options requests, respond with a default if nothing else responds
if (req.method === 'OPTIONS') {
done = wrap(done, function(old, err) {
if (err || options.length === 0) return old(err);
sendOptionsResponse(res, options, old);
});
}
// setup basic req values
req.baseUrl = parentUrl;
req.originalUrl = req.originalUrl || req.url;
next();
function next(err) {
var layerError = err === 'route'
? null
: err;
// remove added slash
if (slashAdded) {
req.url = req.url.substr(1);
slashAdded = false;
}
// restore altered req.url
if (removed.length !== 0) {
req.baseUrl = parentUrl;
req.url = protohost + removed + req.url.substr(protohost.length);
removed = '';
}
// signal to exit router
if (layerError === 'router') {
setImmediate(done, null)
return
}
// no more matching layers
if (idx >= stack.length) {
setImmediate(done, layerError);
return;
}
// get pathname of request
var path = getPathname(req);
if (path == null) {
return done(layerError);
}
// find next matching layer
var layer;
var match;
var route;
while (match !== true && idx < stack.length) {
layer = stack[idx++];
match = matchLayer(layer, path);
route = layer.route;
if (typeof match !== 'boolean') {
// hold on to layerError
layerError = layerError || match;
}
if (match !== true) {
continue;
}
if (!route) {
// process non-route handlers normally
continue;
}
if (layerError) {
// routes do not match with a pending error
match = false;
continue;
}
var method = req.method;
var has_method = route._handles_method(method);
// build up automatic options response
if (!has_method && method === 'OPTIONS') {
appendMethods(options, route._options());
}
// don't even bother matching route
if (!has_method && method !== 'HEAD') {
match = false;
continue;
}
}
// no match
if (match !== true) {
return done(layerError);
}
// store route for dispatch on change
if (route) {
req.route = route;
}
// Capture one-time layer values
req.params = self.mergeParams
? mergeParams(layer.params, parentParams)
: layer.params;
var layerPath = layer.path;
// this should be done for the layer
self.process_params(layer, paramcalled, req, res, function (err) {
if (err) {
return next(layerError || err);
}
if (route) {
return layer.handle_request(req, res, next);
}
trim_prefix(layer, layerError, layerPath, path);
});
}
function trim_prefix(layer, layerError, layerPath, path) {
if (layerPath.length !== 0) {
// Validate path is a prefix match
if (layerPath !== path.substr(0, layerPath.length)) {
next(layerError)
return
}
// Validate path breaks on a path separator
var c = path[layerPath.length]
if (c && c !== '/' && c !== '.') return next(layerError)
// Trim off the part of the url that matches the route
// middleware (.use stuff) needs to have the path stripped
debug('trim prefix (%s) from url %s', layerPath, req.url);
removed = layerPath;
req.url = protohost + req.url.substr(protohost.length + removed.length);
// Ensure leading slash
if (!protohost && req.url[0] !== '/') {
req.url = '/' + req.url;
slashAdded = true;
}
// Setup base URL (no trailing slash)
req.baseUrl = parentUrl + (removed[removed.length - 1] === '/'
? removed.substring(0, removed.length - 1)
: removed);
}
debug('%s %s : %s', layer.name, layerPath, req.originalUrl);
if (layerError) {
layer.handle_error(layerError, req, res, next);
} else {
layer.handle_request(req, res, next);
}
}
};
/**
* Process any parameters for the layer.
* @private
*/
proto.process_params = function process_params(layer, called, req, res, done) {
var params = this.params;
// captured parameters from the layer, keys and values
var keys = layer.keys;
// fast track
if (!keys || keys.length === 0) {
return done();
}
var i = 0;
var name;
var paramIndex = 0;
var key;
var paramVal;
var paramCallbacks;
var paramCalled;
// process params in order
// param callbacks can be async
function param(err) {
if (err) {
return done(err);
}
if (i >= keys.length ) {
return done();
}
paramIndex = 0;
key = keys[i++];
name = key.name;
paramVal = req.params[name];
paramCallbacks = params[name];
paramCalled = called[name];
if (paramVal === undefined || !paramCallbacks) {
return param();
}
// param previously called with same value or error occurred
if (paramCalled && (paramCalled.match === paramVal
|| (paramCalled.error && paramCalled.error !== 'route'))) {
// restore value
req.params[name] = paramCalled.value;
// next param
return param(paramCalled.error);
}
called[name] = paramCalled = {
error: null,
match: paramVal,
value: paramVal
};
paramCallback();
}
// single param callbacks
function paramCallback(err) {
var fn = paramCallbacks[paramIndex++];
// store updated value
paramCalled.value = req.params[key.name];
if (err) {
// store error
paramCalled.error = err;
param(err);
return;
}
if (!fn) return param();
try {
fn(req, res, paramCallback, paramVal, key.name);
} catch (e) {
paramCallback(e);
}
}
param();
};
/**
* Use the given middleware function, with optional path, defaulting to "/".
*
* Use (like `.all`) will run for any http METHOD, but it will not add
* handlers for those methods so OPTIONS requests will not consider `.use`
* functions even if they could respond.
*
* The other difference is that _route_ path is stripped and not visible
* to the handler function. The main effect of this feature is that mounted
* handlers can operate without any code changes regardless of the "prefix"
* pathname.
*
* @public
*/
proto.use = function use(fn) {
var offset = 0;
var path = '/';
// default path to '/'
// disambiguate router.use([fn])
if (typeof fn !== 'function') {
var arg = fn;
while (Array.isArray(arg) && arg.length !== 0) {
arg = arg[0];
}
// first arg is the path
if (typeof arg !== 'function') {
offset = 1;
path = fn;
}
}
var callbacks = flatten(slice.call(arguments, offset));
if (callbacks.length === 0) {
throw new TypeError('Router.use() requires a middleware function')
}
for (var i = 0; i < callbacks.length; i++) {
var fn = callbacks[i];
if (typeof fn !== 'function') {
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
}
// add the middleware
debug('use %o %s', path, fn.name || '<anonymous>')
var layer = new Layer(path, {
sensitive: this.caseSensitive,
strict: false,
end: false
}, fn);
layer.route = undefined;
this.stack.push(layer);
}
return this;
};
/**
* Create a new Route for the given path.
*
* Each route contains a separate middleware stack and VERB handlers.
*
* See the Route api documentation for details on adding handlers
* and middleware to routes.
*
* @param {String} path
* @return {Route}
* @public
*/
proto.route = function route(path) {
var route = new Route(path);
var layer = new Layer(path, {
sensitive: this.caseSensitive,
strict: this.strict,
end: true
}, route.dispatch.bind(route));
layer.route = route;
this.stack.push(layer);
return route;
};
// create Router#VERB functions
methods.concat('all').forEach(function(method){
proto[method] = function(path){
var route = this.route(path)
route[method].apply(route, slice.call(arguments, 1));
return this;
};
});
// append methods to a list of methods
function appendMethods(list, addition) {
for (var i = 0; i < addition.length; i++) {
var method = addition[i];
if (list.indexOf(method) === -1) {
list.push(method);
}
}
}
// get pathname of request
function getPathname(req) {
try {
return parseUrl(req).pathname;
} catch (err) {
return undefined;
}
}
// Get get protocol + host for a URL
function getProtohost(url) {
if (typeof url !== 'string' || url.length === 0 || url[0] === '/') {
return undefined
}
var searchIndex = url.indexOf('?')
var pathLength = searchIndex !== -1
? searchIndex
: url.length
var fqdnIndex = url.substr(0, pathLength).indexOf('://')
return fqdnIndex !== -1
? url.substr(0, url.indexOf('/', 3 + fqdnIndex))
: undefined
}
// get type for error message
function gettype(obj) {
var type = typeof obj;
if (type !== 'object') {
return type;
}
// inspect [[Class]] for objects
return toString.call(obj)
.replace(objectRegExp, '$1');
}
/**
* Match path to a layer.
*
* @param {Layer} layer
* @param {string} path
* @private
*/
function matchLayer(layer, path) {
try {
return layer.match(path);
} catch (err) {
return err;
}
}
// merge params with parent params
function mergeParams(params, parent) {
if (typeof parent !== 'object' || !parent) {
return params;
}
// make copy of parent for base
var obj = mixin({}, parent);
// simple non-numeric merging
if (!(0 in params) || !(0 in parent)) {
return mixin(obj, params);
}
var i = 0;
var o = 0;
// determine numeric gaps
while (i in params) {
i++;
}
while (o in parent) {
o++;
}
// offset numeric indices in params before merge
for (i--; i >= 0; i--) {
params[i + o] = params[i];
// create holes for the merge when necessary
if (i < o) {
delete params[i];
}
}
return mixin(obj, params);
}
// restore obj props after function
function restore(fn, obj) {
var props = new Array(arguments.length - 2);
var vals = new Array(arguments.length - 2);
for (var i = 0; i < props.length; i++) {
props[i] = arguments[i + 2];
vals[i] = obj[props[i]];
}
return function () {
// restore vals
for (var i = 0; i < props.length; i++) {
obj[props[i]] = vals[i];
}
return fn.apply(this, arguments);
};
}
// send an OPTIONS response
function sendOptionsResponse(res, options, next) {
try {
var body = options.join(',');
res.set('Allow', body);
res.send(body);
} catch (err) {
next(err);
}
}
// wrap a function
function wrap(old, fn) {
return function proxy() {
var args = new Array(arguments.length + 1);
args[0] = old;
for (var i = 0, len = arguments.length; i < len; i++) {
args[i + 1] = arguments[i];
}
fn.apply(this, args);
};
}

View File

@@ -1,181 +0,0 @@
/*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var pathRegexp = require('path-to-regexp');
var debug = require('debug')('express:router:layer');
/**
* Module variables.
* @private
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Module exports.
* @public
*/
module.exports = Layer;
function Layer(path, options, fn) {
if (!(this instanceof Layer)) {
return new Layer(path, options, fn);
}
debug('new %o', path)
var opts = options || {};
this.handle = fn;
this.name = fn.name || '<anonymous>';
this.params = undefined;
this.path = undefined;
this.regexp = pathRegexp(path, this.keys = [], opts);
// set fast path flags
this.regexp.fast_star = path === '*'
this.regexp.fast_slash = path === '/' && opts.end === false
}
/**
* Handle the error for the layer.
*
* @param {Error} error
* @param {Request} req
* @param {Response} res
* @param {function} next
* @api private
*/
Layer.prototype.handle_error = function handle_error(error, req, res, next) {
var fn = this.handle;
if (fn.length !== 4) {
// not a standard error handler
return next(error);
}
try {
fn(error, req, res, next);
} catch (err) {
next(err);
}
};
/**
* Handle the request for the layer.
*
* @param {Request} req
* @param {Response} res
* @param {function} next
* @api private
*/
Layer.prototype.handle_request = function handle(req, res, next) {
var fn = this.handle;
if (fn.length > 3) {
// not a standard request handler
return next();
}
try {
fn(req, res, next);
} catch (err) {
next(err);
}
};
/**
* Check if this route matches `path`, if so
* populate `.params`.
*
* @param {String} path
* @return {Boolean}
* @api private
*/
Layer.prototype.match = function match(path) {
var match
if (path != null) {
// fast path non-ending match for / (any path matches)
if (this.regexp.fast_slash) {
this.params = {}
this.path = ''
return true
}
// fast path for * (everything matched in a param)
if (this.regexp.fast_star) {
this.params = {'0': decode_param(path)}
this.path = path
return true
}
// match the path
match = this.regexp.exec(path)
}
if (!match) {
this.params = undefined;
this.path = undefined;
return false;
}
// store values
this.params = {};
this.path = match[0]
var keys = this.keys;
var params = this.params;
for (var i = 1; i < match.length; i++) {
var key = keys[i - 1];
var prop = key.name;
var val = decode_param(match[i])
if (val !== undefined || !(hasOwnProperty.call(params, prop))) {
params[prop] = val;
}
}
return true;
};
/**
* Decode param value.
*
* @param {string} val
* @return {string}
* @private
*/
function decode_param(val) {
if (typeof val !== 'string' || val.length === 0) {
return val;
}
try {
return decodeURIComponent(val);
} catch (err) {
if (err instanceof URIError) {
err.message = 'Failed to decode param \'' + val + '\'';
err.status = err.statusCode = 400;
}
throw err;
}
}

View File

@@ -1,216 +0,0 @@
/*!
* express
* Copyright(c) 2009-2013 TJ Holowaychuk
* Copyright(c) 2013 Roman Shtylman
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var debug = require('debug')('express:router:route');
var flatten = require('array-flatten');
var Layer = require('./layer');
var methods = require('methods');
/**
* Module variables.
* @private
*/
var slice = Array.prototype.slice;
var toString = Object.prototype.toString;
/**
* Module exports.
* @public
*/
module.exports = Route;
/**
* Initialize `Route` with the given `path`,
*
* @param {String} path
* @public
*/
function Route(path) {
this.path = path;
this.stack = [];
debug('new %o', path)
// route handlers for various http methods
this.methods = {};
}
/**
* Determine if the route handles a given method.
* @private
*/
Route.prototype._handles_method = function _handles_method(method) {
if (this.methods._all) {
return true;
}
var name = method.toLowerCase();
if (name === 'head' && !this.methods['head']) {
name = 'get';
}
return Boolean(this.methods[name]);
};
/**
* @return {Array} supported HTTP methods
* @private
*/
Route.prototype._options = function _options() {
var methods = Object.keys(this.methods);
// append automatic head
if (this.methods.get && !this.methods.head) {
methods.push('head');
}
for (var i = 0; i < methods.length; i++) {
// make upper case
methods[i] = methods[i].toUpperCase();
}
return methods;
};
/**
* dispatch req, res into this route
* @private
*/
Route.prototype.dispatch = function dispatch(req, res, done) {
var idx = 0;
var stack = this.stack;
if (stack.length === 0) {
return done();
}
var method = req.method.toLowerCase();
if (method === 'head' && !this.methods['head']) {
method = 'get';
}
req.route = this;
next();
function next(err) {
// signal to exit route
if (err && err === 'route') {
return done();
}
// signal to exit router
if (err && err === 'router') {
return done(err)
}
var layer = stack[idx++];
if (!layer) {
return done(err);
}
if (layer.method && layer.method !== method) {
return next(err);
}
if (err) {
layer.handle_error(err, req, res, next);
} else {
layer.handle_request(req, res, next);
}
}
};
/**
* Add a handler for all HTTP verbs to this route.
*
* Behaves just like middleware and can respond or call `next`
* to continue processing.
*
* You can use multiple `.all` call to add multiple handlers.
*
* function check_something(req, res, next){
* next();
* };
*
* function validate_user(req, res, next){
* next();
* };
*
* route
* .all(validate_user)
* .all(check_something)
* .get(function(req, res, next){
* res.send('hello world');
* });
*
* @param {function} handler
* @return {Route} for chaining
* @api public
*/
Route.prototype.all = function all() {
var handles = flatten(slice.call(arguments));
for (var i = 0; i < handles.length; i++) {
var handle = handles[i];
if (typeof handle !== 'function') {
var type = toString.call(handle);
var msg = 'Route.all() requires a callback function but got a ' + type
throw new TypeError(msg);
}
var layer = Layer('/', {}, handle);
layer.method = undefined;
this.methods._all = true;
this.stack.push(layer);
}
return this;
};
methods.forEach(function(method){
Route.prototype[method] = function(){
var handles = flatten(slice.call(arguments));
for (var i = 0; i < handles.length; i++) {
var handle = handles[i];
if (typeof handle !== 'function') {
var type = toString.call(handle);
var msg = 'Route.' + method + '() requires a callback function but got a ' + type
throw new Error(msg);
}
debug('%s %o', method, this.path)
var layer = Layer('/', {}, handle);
layer.method = method;
this.methods[method] = true;
this.stack.push(layer);
}
return this;
};
});

View File

@@ -12,17 +12,20 @@
* @api private
*/
var Buffer = require('safe-buffer').Buffer
var contentDisposition = require('content-disposition');
var { METHODS } = require('node:http');
var contentType = require('content-type');
var deprecate = require('depd')('express');
var flatten = require('array-flatten');
var mime = require('send').mime;
var etag = require('etag');
var mime = require('mime-types')
var proxyaddr = require('proxy-addr');
var qs = require('qs');
var querystring = require('querystring');
/**
* A list of lowercased HTTP methods that are supported by Node.js.
* @api private
*/
exports.methods = METHODS.map((method) => method.toLowerCase());
/**
* Return strong ETag for `body`.
*
@@ -45,31 +48,6 @@ exports.etag = createETagGenerator({ weak: false })
exports.wetag = createETagGenerator({ weak: true })
/**
* Check if `path` looks absolute.
*
* @param {String} path
* @return {Boolean}
* @api private
*/
exports.isAbsolute = function(path){
if ('/' === path[0]) return true;
if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path
if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path
};
/**
* Flatten the given `arr`.
*
* @param {Array} arr
* @return {Array}
* @api private
*/
exports.flatten = deprecate.function(flatten,
'utils.flatten: use array-flatten npm module instead');
/**
* Normalize the given `type`, for example "html" becomes "text/html".
*
@@ -81,7 +59,7 @@ exports.flatten = deprecate.function(flatten,
exports.normalizeType = function(type){
return ~type.indexOf('/')
? acceptParams(type)
: { value: mime.lookup(type), params: {} };
: { value: (mime.lookup(type) || 'application/octet-stream'), params: {} }
};
/**
@@ -92,49 +70,48 @@ exports.normalizeType = function(type){
* @api private
*/
exports.normalizeTypes = function(types){
var ret = [];
for (var i = 0; i < types.length; ++i) {
ret.push(exports.normalizeType(types[i]));
}
return ret;
exports.normalizeTypes = function(types) {
return types.map(exports.normalizeType);
};
/**
* Generate Content-Disposition header appropriate for the filename.
* non-ascii filenames are urlencoded and a filename* parameter is added
*
* @param {String} filename
* @return {String}
* @api private
*/
exports.contentDisposition = deprecate.function(contentDisposition,
'utils.contentDisposition: use content-disposition npm module instead');
/**
* Parse accept params `str` returning an
* object with `.value`, `.quality` and `.params`.
* also includes `.originalIndex` for stable sorting
*
* @param {String} str
* @return {Object}
* @api private
*/
function acceptParams(str, index) {
var parts = str.split(/ *; */);
var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index };
function acceptParams (str) {
var length = str.length;
var colonIndex = str.indexOf(';');
var index = colonIndex === -1 ? length : colonIndex;
var ret = { value: str.slice(0, index).trim(), quality: 1, params: {} };
for (var i = 1; i < parts.length; ++i) {
var pms = parts[i].split(/ *= */);
if ('q' === pms[0]) {
ret.quality = parseFloat(pms[1]);
} else {
ret.params[pms[0]] = pms[1];
while (index < length) {
var splitIndex = str.indexOf('=', index);
if (splitIndex === -1) break;
var colonIndex = str.indexOf(';', index);
var endIndex = colonIndex === -1 ? length : colonIndex;
if (splitIndex > endIndex) {
index = str.lastIndexOf(';', splitIndex - 1) + 1;
continue;
}
var key = str.slice(index, splitIndex).trim();
var value = str.slice(splitIndex + 1, endIndex).trim();
if (key === 'q') {
ret.quality = parseFloat(value);
} else {
ret.params[key] = value;
}
index = endIndex + 1;
}
return ret;
@@ -193,7 +170,6 @@ exports.compileQueryParser = function compileQueryParser(val) {
fn = querystring.parse;
break;
case false:
fn = newObject;
break;
case 'extended':
fn = parseExtendedQueryString;
@@ -228,7 +204,8 @@ exports.compileTrust = function(val) {
if (typeof val === 'string') {
// Support comma-separated values
val = val.split(/ *, */);
val = val.split(',')
.map(function (v) { return v.trim() })
}
return proxyaddr.compile(val || []);
@@ -280,6 +257,7 @@ function createETagGenerator (options) {
/**
* Parse an extended query string with qs.
*
* @param {String} str
* @return {Object}
* @private
*/
@@ -289,14 +267,3 @@ function parseExtendedQueryString(str) {
allowPrototypes: true
});
}
/**
* Return new empty object.
*
* @return {Object}
* @api private
*/
function newObject() {
return {};
}

View File

@@ -14,8 +14,8 @@
*/
var debug = require('debug')('express:view');
var path = require('path');
var fs = require('fs');
var path = require('node:path');
var fs = require('node:fs');
/**
* Module variables.
@@ -74,7 +74,7 @@ function View(name, options) {
if (!opts.engines[this.ext]) {
// load engine
var mod = this.ext.substr(1)
var mod = this.ext.slice(1)
debug('require "%s"', mod)
// default engine export
@@ -131,8 +131,31 @@ View.prototype.lookup = function lookup(name) {
*/
View.prototype.render = function render(options, callback) {
var sync = true;
debug('render "%s"', this.path);
this.engine(this.path, options, callback);
// render, normalizing sync callbacks
this.engine(this.path, options, function onRender() {
if (!sync) {
return callback.apply(this, arguments);
}
// copy arguments
var args = new Array(arguments.length);
var cntx = this;
for (var i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
// force callback to be async
return process.nextTick(function renderTick() {
return callback.apply(cntx, args);
});
});
sync = false;
};
/**

View File

@@ -1,7 +1,7 @@
{
"name": "express",
"description": "Fast, unopinionated, minimalist web framework",
"version": "4.17.2",
"version": "5.0.1",
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"contributors": [
"Aaron Heckmann <aaron.heckmann+github@gmail.com>",
@@ -14,7 +14,11 @@
],
"license": "MIT",
"repository": "expressjs/express",
"homepage": "http://expressjs.com/",
"homepage": "https://expressjs.com/",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
},
"keywords": [
"express",
"framework",
@@ -28,59 +32,54 @@
"api"
],
"dependencies": {
"accepts": "~1.3.7",
"array-flatten": "1.1.1",
"body-parser": "1.19.1",
"content-disposition": "0.5.4",
"content-type": "~1.0.4",
"cookie": "0.4.1",
"cookie-signature": "1.0.6",
"debug": "2.6.9",
"depd": "~1.1.2",
"encodeurl": "~1.0.2",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "~1.1.2",
"fresh": "0.5.2",
"merge-descriptors": "1.0.1",
"methods": "~1.1.2",
"on-finished": "~2.3.0",
"parseurl": "~1.3.3",
"path-to-regexp": "0.1.7",
"proxy-addr": "~2.0.7",
"qs": "6.9.6",
"range-parser": "~1.2.1",
"safe-buffer": "5.2.1",
"send": "0.17.2",
"serve-static": "1.14.2",
"setprototypeof": "1.2.0",
"statuses": "~1.5.0",
"type-is": "~1.6.18",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
"accepts": "^2.0.0",
"body-parser": "^2.1.0",
"content-disposition": "^1.0.0",
"content-type": "^1.0.5",
"cookie": "^0.7.1",
"cookie-signature": "^1.2.1",
"debug": "^4.4.0",
"encodeurl": "^2.0.0",
"escape-html": "^1.0.3",
"etag": "^1.8.1",
"finalhandler": "^2.0.0",
"fresh": "^2.0.0",
"http-errors": "^2.0.0",
"merge-descriptors": "^2.0.0",
"mime-types": "^3.0.0",
"on-finished": "^2.4.1",
"once": "^1.4.0",
"parseurl": "^1.3.3",
"proxy-addr": "^2.0.7",
"qs": "^6.14.0",
"range-parser": "^1.2.1",
"router": "^2.1.0",
"send": "^1.1.0",
"serve-static": "^2.1.0",
"statuses": "^2.0.1",
"type-is": "^2.0.0",
"vary": "^1.1.2"
},
"devDependencies": {
"after": "0.8.2",
"connect-redis": "3.4.2",
"cookie-parser": "1.4.6",
"connect-redis": "^8.0.1",
"cookie-parser": "1.4.7",
"cookie-session": "2.0.0",
"ejs": "3.1.6",
"eslint": "7.32.0",
"express-session": "1.17.2",
"ejs": "^3.1.10",
"eslint": "8.47.0",
"express-session": "^1.18.1",
"hbs": "4.2.0",
"istanbul": "0.4.5",
"marked": "0.7.0",
"marked": "^15.0.3",
"method-override": "3.0.0",
"mocha": "9.1.3",
"mocha": "^10.7.3",
"morgan": "1.10.0",
"multiparty": "4.2.2",
"nyc": "^17.1.0",
"pbkdf2-password": "1.2.1",
"should": "13.2.3",
"supertest": "6.1.6",
"supertest": "^6.3.0",
"vhost": "~3.0.2"
},
"engines": {
"node": ">= 0.10.0"
"node": ">= 18"
},
"files": [
"LICENSE",
@@ -91,9 +90,9 @@
],
"scripts": {
"lint": "eslint .",
"test": "mocha --require test/support/env --reporter spec --bail --check-leaks test/ test/acceptance/",
"test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/ test/acceptance/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/ test/acceptance/",
"test": "mocha --require test/support/env --reporter spec --check-leaks test/ test/acceptance/",
"test-ci": "nyc --exclude examples --exclude test --exclude benchmarks --reporter=lcovonly --reporter=text npm test",
"test-cov": "nyc --exclude examples --exclude test --exclude benchmarks --reporter=html --reporter=text npm test",
"test-tap": "mocha --require test/support/env --reporter tap --check-leaks test/ test/acceptance/"
}
}

View File

@@ -1,9 +1,10 @@
'use strict'
var after = require('after');
var should = require('should');
var assert = require('node:assert')
var express = require('../')
, Route = express.Route
, methods = require('methods')
, methods = require('../lib/utils').methods
describe('Route', function(){
it('should work without handlers', function(done) {
@@ -12,6 +13,37 @@ describe('Route', function(){
route.dispatch(req, {}, done)
})
it('should not stack overflow with a large sync stack', function (done) {
this.timeout(5000) // long-running test
var req = { method: 'GET', url: '/' }
var route = new Route('/foo')
route.get(function (req, res, next) {
req.counter = 0
next()
})
for (var i = 0; i < 6000; i++) {
route.all(function (req, res, next) {
req.counter++
next()
})
}
route.get(function (req, res, next) {
req.called = true
next()
})
route.dispatch(req, {}, function (err) {
if (err) return done(err)
assert.ok(req.called)
assert.strictEqual(req.counter, 6000)
done()
})
})
describe('.all', function(){
it('should add handler', function(done){
var req = { method: 'GET', url: '/' };
@@ -24,7 +56,7 @@ describe('Route', function(){
route.dispatch(req, {}, function (err) {
if (err) return done(err);
should(req.called).be.ok()
assert.ok(req.called)
done();
});
})
@@ -34,7 +66,7 @@ describe('Route', function(){
var route = new Route('/foo');
var cb = after(methods.length, function (err) {
if (err) return done(err);
count.should.equal(methods.length);
assert.strictEqual(count, methods.length)
done();
});
@@ -65,7 +97,7 @@ describe('Route', function(){
route.dispatch(req, {}, function (err) {
if (err) return done(err);
req.count.should.equal(2);
assert.strictEqual(req.count, 2)
done();
});
})
@@ -83,7 +115,7 @@ describe('Route', function(){
route.dispatch(req, {}, function (err) {
if (err) return done(err);
should(req.called).be.ok()
assert.ok(req.called)
done();
});
})
@@ -92,7 +124,7 @@ describe('Route', function(){
var req = { method: 'POST', url: '/' };
var route = new Route('');
route.get(function(req, res, next) {
route.get(function () {
throw new Error('not me!');
})
@@ -103,7 +135,7 @@ describe('Route', function(){
route.dispatch(req, {}, function (err) {
if (err) return done(err);
should(req.called).be.true()
assert.ok(req.called)
done();
});
})
@@ -129,7 +161,7 @@ describe('Route', function(){
route.dispatch(req, {}, function (err) {
if (err) return done(err);
req.order.should.equal('abc');
assert.strictEqual(req.order, 'abc')
done();
});
})
@@ -155,9 +187,9 @@ describe('Route', function(){
});
route.dispatch(req, {}, function (err) {
should(err).be.ok()
should(err.message).equal('foobar');
req.order.should.equal('a');
assert.ok(err)
assert.strictEqual(err.message, 'foobar')
assert.strictEqual(req.order, 'a')
done();
});
})
@@ -166,7 +198,7 @@ describe('Route', function(){
var req = { order: '', method: 'GET', url: '/' };
var route = new Route('');
route.all(function(req, res, next){
route.all(function () {
throw new Error('foobar');
});
@@ -181,9 +213,9 @@ describe('Route', function(){
});
route.dispatch(req, {}, function (err) {
should(err).be.ok()
should(err.message).equal('foobar');
req.order.should.equal('a');
assert.ok(err)
assert.strictEqual(err.message, 'foobar')
assert.strictEqual(req.order, 'a')
done();
});
});
@@ -192,7 +224,7 @@ describe('Route', function(){
var req = { method: 'GET', url: '/' };
var route = new Route('');
route.get(function(req, res, next){
route.get(function () {
throw new Error('boom!');
});
@@ -207,7 +239,7 @@ describe('Route', function(){
route.dispatch(req, {}, function (err) {
if (err) return done(err);
should(req.message).equal('oops');
assert.strictEqual(req.message, 'oops')
done();
});
});
@@ -221,8 +253,8 @@ describe('Route', function(){
});
route.dispatch(req, {}, function(err){
should(err).be.ok()
err.message.should.equal('boom!');
assert.ok(err)
assert.strictEqual(err.message, 'boom!')
done();
});
});
@@ -233,7 +265,7 @@ describe('Route', function(){
route.all(function(err, req, res, next){
// this should not execute
true.should.be.false()
throw new Error('should not be called')
});
route.dispatch(req, {}, done);

View File

@@ -1,12 +1,13 @@
'use strict'
var after = require('after');
var express = require('../')
, Router = express.Router
, methods = require('methods')
, assert = require('assert');
, methods = require('../lib/utils').methods
, assert = require('node:assert');
describe('Router', function(){
it('should return a function with router methods', function() {
describe('Router', function () {
it('should return a function with router methods', function () {
var router = new Router();
assert(typeof router === 'function')
@@ -15,32 +16,32 @@ describe('Router', function(){
assert(typeof router.use === 'function')
});
it('should support .use of other routers', function(done){
it('should support .use of other routers', function (done) {
var router = new Router();
var another = new Router();
another.get('/bar', function(req, res){
another.get('/bar', function (req, res) {
res.end();
});
router.use('/foo', another);
router.handle({ url: '/foo/bar', method: 'GET' }, { end: done });
router.handle({ url: '/foo/bar', method: 'GET' }, { end: done }, function () { });
});
it('should support dynamic routes', function(done){
it('should support dynamic routes', function (done) {
var router = new Router();
var another = new Router();
another.get('/:bar', function(req, res){
another.get('/:bar', function (req, res) {
assert.strictEqual(req.params.bar, 'route')
res.end();
});
router.use('/:foo', another);
router.handle({ url: '/test/route', method: 'GET' }, { end: done });
router.handle({ url: '/test/route', method: 'GET' }, { end: done }, function () { });
});
it('should handle blank URL', function(done){
it('should handle blank URL', function (done) {
var router = new Router();
router.use(function (req, res) {
@@ -60,8 +61,37 @@ describe('Router', function(){
router.handle({ method: 'GET' }, {}, done)
})
it('should not stack overflow with many registered routes', function(done){
var handler = function(req, res){ res.end(new Error('wrong handler')) };
it('handle missing method', function (done) {
var all = false
var router = new Router()
var route = router.route('/foo')
var use = false
route.post(function (req, res, next) { next(new Error('should not run')) })
route.all(function (req, res, next) {
all = true
next()
})
route.get(function (req, res, next) { next(new Error('should not run')) })
router.get('/foo', function (req, res, next) { next(new Error('should not run')) })
router.use(function (req, res, next) {
use = true
next()
})
router.handle({ url: '/foo' }, {}, function (err) {
if (err) return done(err)
assert.ok(all)
assert.ok(use)
done()
})
})
it('should not stack overflow with many registered routes', function (done) {
this.timeout(5000) // long-running test
var handler = function (req, res) { res.end(new Error('wrong handler')) };
var router = new Router();
for (var i = 0; i < 6000; i++) {
@@ -72,72 +102,126 @@ describe('Router', function(){
res.end();
});
router.handle({ url: '/', method: 'GET' }, { end: done });
router.handle({ url: '/', method: 'GET' }, { end: done }, function () { });
});
describe('.handle', function(){
it('should dispatch', function(done){
it('should not stack overflow with a large sync route stack', function (done) {
this.timeout(5000) // long-running test
var router = new Router()
router.get('/foo', function (req, res, next) {
req.counter = 0
next()
})
for (var i = 0; i < 6000; i++) {
router.get('/foo', function (req, res, next) {
req.counter++
next()
})
}
router.get('/foo', function (req, res) {
assert.strictEqual(req.counter, 6000)
res.end()
})
router.handle({ url: '/foo', method: 'GET' }, { end: done }, function (err) {
assert(!err, err);
});
})
it('should not stack overflow with a large sync middleware stack', function (done) {
this.timeout(5000) // long-running test
var router = new Router()
router.use(function (req, res, next) {
req.counter = 0
next()
})
for (var i = 0; i < 6000; i++) {
router.use(function (req, res, next) {
req.counter++
next()
})
}
router.use(function (req, res) {
assert.strictEqual(req.counter, 6000)
res.end()
})
router.handle({ url: '/', method: 'GET' }, { end: done }, function (err) {
assert(!err, err);
})
})
describe('.handle', function () {
it('should dispatch', function (done) {
var router = new Router();
router.route('/foo').get(function(req, res){
router.route('/foo').get(function (req, res) {
res.send('foo');
});
var res = {
send: function(val) {
send: function (val) {
assert.strictEqual(val, 'foo')
done();
}
}
router.handle({ url: '/foo', method: 'GET' }, res);
router.handle({ url: '/foo', method: 'GET' }, res, function () { });
})
})
describe('.multiple callbacks', function(){
it('should throw if a callback is null', function(){
describe('.multiple callbacks', function () {
it('should throw if a callback is null', function () {
assert.throws(function () {
var router = new Router();
router.route('/foo').all(null);
})
})
it('should throw if a callback is undefined', function(){
it('should throw if a callback is undefined', function () {
assert.throws(function () {
var router = new Router();
router.route('/foo').all(undefined);
})
})
it('should throw if a callback is not a function', function(){
it('should throw if a callback is not a function', function () {
assert.throws(function () {
var router = new Router();
router.route('/foo').all('not a function');
})
})
it('should not throw if all callbacks are functions', function(){
it('should not throw if all callbacks are functions', function () {
var router = new Router();
router.route('/foo').all(function(){}).all(function(){});
router.route('/foo').all(function () { }).all(function () { });
})
})
describe('error', function(){
it('should skip non error middleware', function(done){
describe('error', function () {
it('should skip non error middleware', function (done) {
var router = new Router();
router.get('/foo', function(req, res, next){
router.get('/foo', function (req, res, next) {
next(new Error('foo'));
});
router.get('/bar', function(req, res, next){
router.get('/bar', function (req, res, next) {
next(new Error('bar'));
});
router.use(function(req, res, next){
router.use(function (req, res, next) {
assert(false);
});
router.use(function(err, req, res, next){
router.use(function (err, req, res, next) {
assert.equal(err.message, 'foo');
done();
});
@@ -145,59 +229,59 @@ describe('Router', function(){
router.handle({ url: '/foo', method: 'GET' }, {}, done);
});
it('should handle throwing inside routes with params', function(done) {
it('should handle throwing inside routes with params', function (done) {
var router = new Router();
router.get('/foo/:id', function(req, res, next){
router.get('/foo/:id', function () {
throw new Error('foo');
});
router.use(function(req, res, next){
router.use(function (req, res, next) {
assert(false);
});
router.use(function(err, req, res, next){
router.use(function (err, req, res, next) {
assert.equal(err.message, 'foo');
done();
});
router.handle({ url: '/foo/2', method: 'GET' }, {}, function() {});
router.handle({ url: '/foo/2', method: 'GET' }, {}, function () { });
});
it('should handle throwing in handler after async param', function(done) {
it('should handle throwing in handler after async param', function (done) {
var router = new Router();
router.param('user', function(req, res, next, val){
process.nextTick(function(){
router.param('user', function (req, res, next, val) {
process.nextTick(function () {
req.user = val;
next();
});
});
router.use('/:user', function(req, res, next){
router.use('/:user', function (req, res, next) {
throw new Error('oh no!');
});
router.use(function(err, req, res, next){
router.use(function (err, req, res, next) {
assert.equal(err.message, 'oh no!');
done();
});
router.handle({ url: '/bob', method: 'GET' }, {}, function() {});
router.handle({ url: '/bob', method: 'GET' }, {}, function () { });
});
it('should handle throwing inside error handlers', function(done) {
it('should handle throwing inside error handlers', function (done) {
var router = new Router();
router.use(function(req, res, next){
router.use(function (req, res, next) {
throw new Error('boom!');
});
router.use(function(err, req, res, next){
router.use(function (err, req, res, next) {
throw new Error('oops');
});
router.use(function(err, req, res, next){
router.use(function (err, req, res, next) {
assert.equal(err.message, 'oops');
done();
});
@@ -328,73 +412,55 @@ describe('Router', function(){
});
})
describe('.all', function() {
it('should support using .all to capture all http verbs', function(done){
describe('.all', function () {
it('should support using .all to capture all http verbs', function (done) {
var router = new Router();
var count = 0;
router.all('/foo', function(){ count++; });
router.all('/foo', function () { count++; });
var url = '/foo?bar=baz';
methods.forEach(function testMethod(method) {
router.handle({ url: url, method: method }, {}, function() {});
router.handle({ url: url, method: method }, {}, function () { });
});
assert.equal(count, methods.length);
done();
})
it('should be called for any URL when "*"', function (done) {
var cb = after(4, done)
var router = new Router()
function no () {
throw new Error('should not be called')
}
router.all('*', function (req, res) {
res.end()
})
router.handle({ url: '/', method: 'GET' }, { end: cb }, no)
router.handle({ url: '/foo', method: 'GET' }, { end: cb }, no)
router.handle({ url: 'foo', method: 'GET' }, { end: cb }, no)
router.handle({ url: '*', method: 'GET' }, { end: cb }, no)
})
})
describe('.use', function() {
describe('.use', function () {
it('should require middleware', function () {
var router = new Router()
assert.throws(function () { router.use('/') }, /requires a middleware function/)
assert.throws(function () { router.use('/') }, /argument handler is required/)
})
it('should reject string as middleware', function () {
var router = new Router()
assert.throws(function () { router.use('/', 'foo') }, /requires a middleware function but got a string/)
assert.throws(function () { router.use('/', 'foo') }, /argument handler must be a function/)
})
it('should reject number as middleware', function () {
var router = new Router()
assert.throws(function () { router.use('/', 42) }, /requires a middleware function but got a number/)
assert.throws(function () { router.use('/', 42) }, /argument handler must be a function/)
})
it('should reject null as middleware', function () {
var router = new Router()
assert.throws(function () { router.use('/', null) }, /requires a middleware function but got a Null/)
assert.throws(function () { router.use('/', null) }, /argument handler must be a function/)
})
it('should reject Date as middleware', function () {
var router = new Router()
assert.throws(function () { router.use('/', new Date()) }, /requires a middleware function but got a Date/)
assert.throws(function () { router.use('/', new Date()) }, /argument handler must be a function/)
})
it('should be called for any URL', function (done) {
var cb = after(4, done)
var router = new Router()
function no () {
function no() {
throw new Error('should not be called')
}
@@ -408,39 +474,49 @@ describe('Router', function(){
router.handle({ url: '*', method: 'GET' }, { end: cb }, no)
})
it('should accept array of middleware', function(done){
it('should accept array of middleware', function (done) {
var count = 0;
var router = new Router();
function fn1(req, res, next){
function fn1(req, res, next) {
assert.equal(++count, 1);
next();
}
function fn2(req, res, next){
function fn2(req, res, next) {
assert.equal(++count, 2);
next();
}
router.use([fn1, fn2], function(req, res){
router.use([fn1, fn2], function (req, res) {
assert.equal(++count, 3);
done();
});
router.handle({ url: '/foo', method: 'GET' }, {}, function(){});
router.handle({ url: '/foo', method: 'GET' }, {}, function () { });
})
})
describe('.param', function() {
it('should call param function when routing VERBS', function(done) {
describe('.param', function () {
it('should require function', function () {
var router = new Router();
assert.throws(router.param.bind(router, 'id'), /argument fn is required/);
});
it('should reject non-function', function () {
var router = new Router();
assert.throws(router.param.bind(router, 'id', 42), /argument fn must be a function/);
});
it('should call param function when routing VERBS', function (done) {
var router = new Router();
router.param('id', function(req, res, next, id) {
router.param('id', function (req, res, next, id) {
assert.equal(id, '123');
next();
});
router.get('/foo/:id/bar', function(req, res, next) {
router.get('/foo/:id/bar', function (req, res, next) {
assert.equal(req.params.id, '123');
next();
});
@@ -448,15 +524,15 @@ describe('Router', function(){
router.handle({ url: '/foo/123/bar', method: 'get' }, {}, done);
});
it('should call param function when routing middleware', function(done) {
it('should call param function when routing middleware', function (done) {
var router = new Router();
router.param('id', function(req, res, next, id) {
router.param('id', function (req, res, next, id) {
assert.equal(id, '123');
next();
});
router.use('/foo/:id/bar', function(req, res, next) {
router.use('/foo/:id/bar', function (req, res, next) {
assert.equal(req.params.id, '123');
assert.equal(req.url, '/baz');
next();
@@ -465,17 +541,17 @@ describe('Router', function(){
router.handle({ url: '/foo/123/bar/baz', method: 'get' }, {}, done);
});
it('should only call once per request', function(done) {
it('should only call once per request', function (done) {
var count = 0;
var req = { url: '/foo/bob/bar', method: 'get' };
var router = new Router();
var sub = new Router();
sub.get('/bar', function(req, res, next) {
sub.get('/bar', function (req, res, next) {
next();
});
router.param('user', function(req, res, next, user) {
router.param('user', function (req, res, next, user) {
count++;
req.user = user;
next();
@@ -484,7 +560,7 @@ describe('Router', function(){
router.use('/foo/:user/', new Router());
router.use('/foo/:user/', sub);
router.handle(req, {}, function(err) {
router.handle(req, {}, function (err) {
if (err) return done(err);
assert.equal(count, 1);
assert.equal(req.user, 'bob');
@@ -492,17 +568,17 @@ describe('Router', function(){
});
});
it('should call when values differ', function(done) {
it('should call when values differ', function (done) {
var count = 0;
var req = { url: '/foo/bob/bar', method: 'get' };
var router = new Router();
var sub = new Router();
sub.get('/bar', function(req, res, next) {
sub.get('/bar', function (req, res, next) {
next();
});
router.param('user', function(req, res, next, user) {
router.param('user', function (req, res, next, user) {
count++;
req.user = user;
next();
@@ -511,7 +587,7 @@ describe('Router', function(){
router.use('/foo/:user/', new Router());
router.use('/:user/bob/', sub);
router.handle(req, {}, function(err) {
router.handle(req, {}, function (err) {
if (err) return done(err);
assert.equal(count, 2);
assert.equal(req.user, 'foo');
@@ -520,20 +596,20 @@ describe('Router', function(){
});
});
describe('parallel requests', function() {
it('should not mix requests', function(done) {
describe('parallel requests', function () {
it('should not mix requests', function (done) {
var req1 = { url: '/foo/50/bar', method: 'get' };
var req2 = { url: '/foo/10/bar', method: 'get' };
var router = new Router();
var sub = new Router();
var cb = after(2, done)
done = after(2, done);
sub.get('/bar', function(req, res, next) {
sub.get('/bar', function (req, res, next) {
next();
});
router.param('ms', function(req, res, next, ms) {
router.param('ms', function (req, res, next, ms) {
ms = parseInt(ms, 10);
req.ms = ms;
setTimeout(next, ms);
@@ -542,18 +618,18 @@ describe('Router', function(){
router.use('/foo/:ms/', new Router());
router.use('/foo/:ms/', sub);
router.handle(req1, {}, function(err) {
router.handle(req1, {}, function (err) {
assert.ifError(err);
assert.equal(req1.ms, 50);
assert.equal(req1.originalUrl, '/foo/50/bar');
done();
cb()
});
router.handle(req2, {}, function(err) {
router.handle(req2, {}, function (err) {
assert.ifError(err);
assert.equal(req2.ms, 10);
assert.equal(req2.originalUrl, '/foo/10/bar');
done();
cb()
});
});
});

View File

@@ -22,7 +22,7 @@ describe('auth', function(){
.expect(200, /<form/, done)
})
it('should display login error', function(done){
it('should display login error for bad user', function (done) {
request(app)
.post('/login')
.type('urlencoded')
@@ -36,6 +36,21 @@ describe('auth', function(){
.expect(200, /Authentication failed/, done)
})
})
it('should display login error for bad password', function (done) {
request(app)
.post('/login')
.type('urlencoded')
.send('username=tj&password=nogood')
.expect('Location', '/login')
.expect(302, function (err, res) {
if (err) return done(err)
request(app)
.get('/login')
.set('Cookie', getCookie(res))
.expect(200, /Authentication failed/, done)
})
})
})
describe('GET /logout',function(){

View File

@@ -36,4 +36,12 @@ describe('downloads', function(){
.expect(404, done)
})
})
describe('GET /files/../index.js', function () {
it('should respond with 403', function (done) {
request(app)
.get('/files/../index.js')
.expect(403, done)
})
})
})

View File

@@ -0,0 +1,21 @@
var app = require('../../examples/hello-world')
var request = require('supertest')
describe('hello-world', function () {
describe('GET /', function () {
it('should respond with hello world', function (done) {
request(app)
.get('/')
.expect(200, 'Hello World', done)
})
})
describe('GET /missing', function () {
it('should respond with 404', function (done) {
request(app)
.get('/missing')
.expect(404, done)
})
})
})

View File

@@ -1,29 +1,32 @@
'use strict'
var after = require('after')
var express = require('../')
, request = require('supertest');
describe('app.all()', function(){
it('should add a router per method', function(done){
var app = express();
var cb = after(2, done)
app.all('/tobi', function(req, res){
res.end(req.method);
});
request(app)
.put('/tobi')
.expect('PUT', function(){
request(app)
.put('/tobi')
.expect(200, 'PUT', cb)
request(app)
.get('/tobi')
.expect('GET', done);
});
.expect(200, 'GET', cb)
})
it('should run the callback for a method just once', function(done){
var app = express()
, n = 0;
app.all('/*', function(req, res, next){
app.all('/*splat', function(req, res, next){
if (n++) return done(new Error('DELETE called several times'));
next();
});

View File

@@ -1,17 +0,0 @@
var express = require('../')
, request = require('supertest');
describe('app.del()', function(){
it('should alias app.delete()', function(done){
var app = express();
app.del('/tobi', function(req, res){
res.end('deleted tobi!');
});
request(app)
.del('/tobi')
.expect('deleted tobi!', done);
})
})

View File

@@ -1,7 +1,9 @@
'use strict'
var assert = require('node:assert')
var express = require('../')
, fs = require('fs');
var path = require('path')
, fs = require('node:fs');
var path = require('node:path')
function render(path, options, fn) {
fs.readFile(path, 'utf8', function(err, str){
@@ -22,16 +24,16 @@ describe('app', function(){
app.render('user.html', function(err, str){
if (err) return done(err);
str.should.equal('<p>tobi</p>');
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
it('should throw when the callback is missing', function(){
var app = express();
(function(){
assert.throws(function () {
app.engine('.html', null);
}).should.throw('callback function required');
}, /callback function required/)
})
it('should work without leading "."', function(done){
@@ -43,7 +45,7 @@ describe('app', function(){
app.render('user.html', function(err, str){
if (err) return done(err);
str.should.equal('<p>tobi</p>');
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
@@ -58,7 +60,7 @@ describe('app', function(){
app.render('user', function(err, str){
if (err) return done(err);
str.should.equal('<p>tobi</p>');
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
@@ -73,7 +75,7 @@ describe('app', function(){
app.render('user', function(err, str){
if (err) return done(err);
str.should.equal('<p>tobi</p>');
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})

View File

@@ -1,7 +1,8 @@
'use strict'
var express = require('../');
var request = require('supertest');
var assert = require('assert');
var assert = require('node:assert');
describe('HEAD', function(){
it('should default to GET', function(done){
@@ -46,23 +47,20 @@ describe('HEAD', function(){
describe('app.head()', function(){
it('should override', function(done){
var app = express()
, called;
app.head('/tobi', function(req, res){
called = true;
res.end('');
res.header('x-method', 'head')
res.end()
});
app.get('/tobi', function(req, res){
assert(0, 'should not call GET');
res.header('x-method', 'get')
res.send('tobi');
});
request(app)
.head('/tobi')
.expect(200, function(){
assert(called);
done();
});
.head('/tobi')
.expect('x-method', 'head')
.expect(200, done)
})
})

View File

@@ -1,5 +1,6 @@
'use strict'
var assert = require('assert')
var assert = require('node:assert')
var express = require('..')
var request = require('supertest')
@@ -32,8 +33,8 @@ describe('app.parent', function(){
blog.use('/admin', blogAdmin);
assert(!app.parent, 'app.parent');
blog.parent.should.equal(app);
blogAdmin.parent.should.equal(blog);
assert.strictEqual(blog.parent, app)
assert.strictEqual(blogAdmin.parent, blog)
})
})
@@ -48,22 +49,10 @@ describe('app.mountpath', function(){
app.use(fallback);
blog.use('/admin', admin);
admin.mountpath.should.equal('/admin');
app.mountpath.should.equal('/');
blog.mountpath.should.equal('/blog');
fallback.mountpath.should.equal('/');
})
})
describe('app.router', function(){
it('should throw with notice', function(done){
var app = express()
try {
app.router;
} catch(err) {
done();
}
assert.strictEqual(admin.mountpath, '/admin')
assert.strictEqual(app.mountpath, '/')
assert.strictEqual(blog.mountpath, '/blog')
assert.strictEqual(fallback.mountpath, '/')
})
})
@@ -76,35 +65,56 @@ describe('app.path()', function(){
app.use('/blog', blog);
blog.use('/admin', blogAdmin);
app.path().should.equal('');
blog.path().should.equal('/blog');
blogAdmin.path().should.equal('/blog/admin');
assert.strictEqual(app.path(), '')
assert.strictEqual(blog.path(), '/blog')
assert.strictEqual(blogAdmin.path(), '/blog/admin')
})
})
describe('in development', function(){
before(function () {
this.env = process.env.NODE_ENV
process.env.NODE_ENV = 'development'
})
after(function () {
process.env.NODE_ENV = this.env
})
it('should disable "view cache"', function(){
process.env.NODE_ENV = 'development';
var app = express();
app.enabled('view cache').should.be.false()
process.env.NODE_ENV = 'test';
assert.ok(!app.enabled('view cache'))
})
})
describe('in production', function(){
before(function () {
this.env = process.env.NODE_ENV
process.env.NODE_ENV = 'production'
})
after(function () {
process.env.NODE_ENV = this.env
})
it('should enable "view cache"', function(){
process.env.NODE_ENV = 'production';
var app = express();
app.enabled('view cache').should.be.true()
process.env.NODE_ENV = 'test';
assert.ok(app.enabled('view cache'))
})
})
describe('without NODE_ENV', function(){
before(function () {
this.env = process.env.NODE_ENV
process.env.NODE_ENV = ''
})
after(function () {
process.env.NODE_ENV = this.env
})
it('should default to development', function(){
process.env.NODE_ENV = '';
var app = express();
app.get('env').should.equal('development');
process.env.NODE_ENV = 'test';
assert.strictEqual(app.get('env'), 'development')
})
})

View File

@@ -1,13 +1,27 @@
'use strict'
var express = require('../')
var assert = require('node:assert')
describe('app.listen()', function(){
it('should wrap with an HTTP server', function(done){
var app = express();
var server = app.listen(9999, function(){
server.close();
done();
var server = app.listen(0, function () {
server.close(done)
});
})
it('should callback on HTTP server errors', function (done) {
var app1 = express()
var app2 = express()
var server1 = app1.listen(0, function (err) {
assert(!err)
app2.listen(server1.address().port, function (err) {
assert(err.code === 'EADDRINUSE')
server1.close()
done()
})
})
})
})

View File

@@ -1,26 +1,26 @@
'use strict'
var assert = require('node:assert')
var express = require('../')
describe('app', function(){
describe('.locals(obj)', function(){
it('should merge locals', function(){
var app = express();
Object.keys(app.locals).should.eql(['settings']);
app.locals.user = 'tobi';
app.locals.age = 2;
Object.keys(app.locals).should.eql(['settings', 'user', 'age']);
app.locals.user.should.equal('tobi');
app.locals.age.should.equal(2);
describe('.locals', function () {
it('should default object with null prototype', function () {
var app = express()
assert.ok(app.locals)
assert.strictEqual(typeof app.locals, 'object')
assert.strictEqual(Object.getPrototypeOf(app.locals), null)
})
})
describe('.locals.settings', function(){
it('should expose app settings', function(){
var app = express();
app.set('title', 'House of Manny');
var obj = app.locals.settings;
obj.should.have.property('env', 'test');
obj.should.have.property('title', 'House of Manny');
describe('.settings', function () {
it('should contain app settings ', function () {
var app = express()
app.set('title', 'Express')
assert.ok(app.locals.settings)
assert.strictEqual(typeof app.locals.settings, 'object')
assert.strictEqual(app.locals.settings, app.settings)
assert.strictEqual(app.locals.settings.title, 'Express')
})
})
})
})

View File

@@ -1,3 +1,4 @@
'use strict'
var express = require('../')
, request = require('supertest');
@@ -6,28 +7,28 @@ describe('OPTIONS', function(){
it('should default to the routes defined', function(done){
var app = express();
app.del('/', function(){});
app.post('/', function(){});
app.get('/users', function(req, res){});
app.put('/users', function(req, res){});
request(app)
.options('/users')
.expect('Allow', 'GET,HEAD,PUT')
.expect(200, 'GET,HEAD,PUT', done);
.expect('Allow', 'GET, HEAD, PUT')
.expect(200, 'GET, HEAD, PUT', done);
})
it('should only include each method once', function(done){
var app = express();
app.del('/', function(){});
app.delete('/', function(){});
app.get('/users', function(req, res){});
app.put('/users', function(req, res){});
app.get('/users', function(req, res){});
request(app)
.options('/users')
.expect('Allow', 'GET,HEAD,PUT')
.expect(200, 'GET,HEAD,PUT', done);
.expect('Allow', 'GET, HEAD, PUT')
.expect(200, 'GET, HEAD, PUT', done);
})
it('should not be affected by app.all', function(done){
@@ -44,8 +45,8 @@ describe('OPTIONS', function(){
request(app)
.options('/users')
.expect('x-hit', '1')
.expect('Allow', 'GET,HEAD,PUT')
.expect(200, 'GET,HEAD,PUT', done);
.expect('Allow', 'GET, HEAD, PUT')
.expect(200, 'GET, HEAD, PUT', done);
})
it('should not respond if the path is not defined', function(done){
@@ -68,8 +69,8 @@ describe('OPTIONS', function(){
request(app)
.options('/other')
.expect('Allow', 'GET,HEAD')
.expect(200, 'GET,HEAD', done);
.expect('Allow', 'GET, HEAD')
.expect(200, 'GET, HEAD', done);
})
describe('when error occurs in response handler', function () {

View File

@@ -1,49 +1,9 @@
'use strict'
var express = require('../')
, request = require('supertest');
describe('app', function(){
describe('.param(fn)', function(){
it('should map app.param(name, ...) logic', function(done){
var app = express();
app.param(function(name, regexp){
if (Object.prototype.toString.call(regexp) === '[object RegExp]') { // See #1557
return function(req, res, next, val){
var captures;
if (captures = regexp.exec(String(val))) {
req.params[name] = captures[1];
next();
} else {
next('route');
}
}
}
})
app.param(':name', /^([a-zA-Z]+)$/);
app.get('/user/:name', function(req, res){
res.send(req.params.name);
});
request(app)
.get('/user/tj')
.expect(200, 'tj', function (err) {
if (err) return done(err)
request(app)
.get('/user/123')
.expect(404, done);
});
})
it('should fail if not given fn', function(){
var app = express();
app.param.bind(app, ':name', 'bob').should.throw();
})
})
describe('.param(names, fn)', function(){
it('should map the array', function(done){
var app = express();
@@ -57,24 +17,22 @@ describe('app', function(){
app.get('/post/:id', function(req, res){
var id = req.params.id;
id.should.be.a.Number()
res.send('' + id);
res.send((typeof id) + ':' + id)
});
app.get('/user/:uid', function(req, res){
var id = req.params.id;
id.should.be.a.Number()
res.send('' + id);
res.send((typeof id) + ':' + id)
});
request(app)
.get('/user/123')
.expect(200, '123', function (err) {
if (err) return done(err)
request(app)
.get('/post/123')
.expect('123', done);
})
.get('/user/123')
.expect(200, 'number:123', function (err) {
if (err) return done(err)
request(app)
.get('/post/123')
.expect('number:123', done)
})
})
})
@@ -91,13 +49,12 @@ describe('app', function(){
app.get('/user/:id', function(req, res){
var id = req.params.id;
id.should.be.a.Number()
res.send('' + id);
res.send((typeof id) + ':' + id)
});
request(app)
.get('/user/123')
.expect('123', done);
.get('/user/123')
.expect(200, 'number:123', done)
})
it('should only call once per request', function(done) {
@@ -167,7 +124,7 @@ describe('app', function(){
app.get('/:user', function(req, res, next) {
next('route');
});
app.get('/:user', function(req, res, next) {
app.get('/:user', function (req, res) {
res.send(req.params.user);
});
@@ -188,11 +145,11 @@ describe('app', function(){
next(new Error('invalid invocation'))
});
app.post('/:user', function(req, res, next) {
app.post('/:user', function (req, res) {
res.send(req.params.user);
});
app.get('/:thing', function(req, res, next) {
app.get('/:thing', function (req, res) {
res.send(req.thing);
});

View File

@@ -1,7 +1,8 @@
'use strict'
var assert = require('assert')
var assert = require('node:assert')
var express = require('..');
var path = require('path')
var path = require('node:path')
var tmpl = require('./support/tmpl');
describe('app', function(){
@@ -13,7 +14,7 @@ describe('app', function(){
app.render(path.join(__dirname, 'fixtures', 'user.tmpl'), function (err, str) {
if (err) return done(err);
str.should.equal('<p>tobi</p>');
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
@@ -26,7 +27,7 @@ describe('app', function(){
app.render(path.join(__dirname, 'fixtures', 'user'), function (err, str) {
if (err) return done(err);
str.should.equal('<p>tobi</p>');
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
@@ -39,7 +40,7 @@ describe('app', function(){
app.render('user.tmpl', function (err, str) {
if (err) return done(err);
str.should.equal('<p>tobi</p>');
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
@@ -52,7 +53,7 @@ describe('app', function(){
app.render('blog/post', function (err, str) {
if (err) return done(err);
str.should.equal('<h1>blog post</h1>');
assert.strictEqual(str, '<h1>blog post</h1>')
done();
})
})
@@ -72,8 +73,8 @@ describe('app', function(){
app.set('view', View);
app.render('something', function(err, str){
err.should.be.ok()
err.message.should.equal('err!');
assert.ok(err)
assert.strictEqual(err.message, 'err!')
done();
})
})
@@ -113,7 +114,7 @@ describe('app', function(){
app.render('email.tmpl', function (err, str) {
if (err) return done(err);
str.should.equal('<p>This is an email</p>');
assert.strictEqual(str, '<p>This is an email</p>')
done();
})
})
@@ -128,7 +129,7 @@ describe('app', function(){
app.render('email', function(err, str){
if (err) return done(err);
str.should.equal('<p>This is an email</p>');
assert.strictEqual(str, '<p>This is an email</p>')
done();
})
})
@@ -143,7 +144,7 @@ describe('app', function(){
app.render('user.tmpl', function (err, str) {
if (err) return done(err);
str.should.equal('<p>tobi</p>');
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
@@ -161,7 +162,7 @@ describe('app', function(){
app.render('user.tmpl', function (err, str) {
if (err) return done(err);
str.should.equal('<span>tobi</span>');
assert.strictEqual(str, '<span>tobi</span>')
done();
})
})
@@ -178,7 +179,7 @@ describe('app', function(){
app.render('name.tmpl', function (err, str) {
if (err) return done(err);
str.should.equal('<p>tobi</p>');
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
@@ -219,7 +220,7 @@ describe('app', function(){
app.render('something', function(err, str){
if (err) return done(err);
str.should.equal('abstract engine');
assert.strictEqual(str, 'abstract engine')
done();
})
})
@@ -245,12 +246,12 @@ describe('app', function(){
app.render('something', function(err, str){
if (err) return done(err);
count.should.equal(1);
str.should.equal('abstract engine');
assert.strictEqual(count, 1)
assert.strictEqual(str, 'abstract engine')
app.render('something', function(err, str){
if (err) return done(err);
count.should.equal(2);
str.should.equal('abstract engine');
assert.strictEqual(count, 2)
assert.strictEqual(str, 'abstract engine')
done();
})
})
@@ -275,12 +276,12 @@ describe('app', function(){
app.render('something', function(err, str){
if (err) return done(err);
count.should.equal(1);
str.should.equal('abstract engine');
assert.strictEqual(count, 1)
assert.strictEqual(str, 'abstract engine')
app.render('something', function(err, str){
if (err) return done(err);
count.should.equal(1);
str.should.equal('abstract engine');
assert.strictEqual(count, 1)
assert.strictEqual(str, 'abstract engine')
done();
})
})
@@ -298,7 +299,7 @@ describe('app', function(){
app.render('user.tmpl', { user: user }, function (err, str) {
if (err) return done(err);
str.should.equal('<p>tobi</p>');
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
@@ -311,7 +312,7 @@ describe('app', function(){
app.render('user.tmpl', {}, function (err, str) {
if (err) return done(err);
str.should.equal('<p>tobi</p>');
assert.strictEqual(str, '<p>tobi</p>')
done();
})
})
@@ -325,7 +326,7 @@ describe('app', function(){
app.render('user.tmpl', { user: jane }, function (err, str) {
if (err) return done(err);
str.should.equal('<p>jane</p>');
assert.strictEqual(str, '<p>jane</p>')
done();
})
})
@@ -350,12 +351,12 @@ describe('app', function(){
app.render('something', {cache: true}, function(err, str){
if (err) return done(err);
count.should.equal(1);
str.should.equal('abstract engine');
assert.strictEqual(count, 1)
assert.strictEqual(str, 'abstract engine')
app.render('something', {cache: true}, function(err, str){
if (err) return done(err);
count.should.equal(1);
str.should.equal('abstract engine');
assert.strictEqual(count, 1)
assert.strictEqual(str, 'abstract engine')
done();
})
})

View File

@@ -1,4 +1,6 @@
'use strict'
var after = require('after')
var express = require('../')
, request = require('supertest');
@@ -8,7 +10,7 @@ describe('app', function(){
var app = express();
app.request.querystring = function(){
return require('url').parse(this.url).query;
return require('node:url').parse(this.url).query;
};
app.use(function(req, res){
@@ -19,5 +21,123 @@ describe('app', function(){
.get('/foo?name=tobi')
.expect('name=tobi', done);
})
it('should only extend for the referenced app', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.request.foobar = function () {
return 'tobi'
}
app1.get('/', function (req, res) {
res.send(req.foobar())
})
app2.get('/', function (req, res) {
res.send(req.foobar())
})
request(app1)
.get('/')
.expect(200, 'tobi', cb)
request(app2)
.get('/')
.expect(500, /(?:not a function|has no method)/, cb)
})
it('should inherit to sub apps', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.request.foobar = function () {
return 'tobi'
}
app1.use('/sub', app2)
app1.get('/', function (req, res) {
res.send(req.foobar())
})
app2.get('/', function (req, res) {
res.send(req.foobar())
})
request(app1)
.get('/')
.expect(200, 'tobi', cb)
request(app1)
.get('/sub')
.expect(200, 'tobi', cb)
})
it('should allow sub app to override', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.request.foobar = function () {
return 'tobi'
}
app2.request.foobar = function () {
return 'loki'
}
app1.use('/sub', app2)
app1.get('/', function (req, res) {
res.send(req.foobar())
})
app2.get('/', function (req, res) {
res.send(req.foobar())
})
request(app1)
.get('/')
.expect(200, 'tobi', cb)
request(app1)
.get('/sub')
.expect(200, 'loki', cb)
})
it('should not pollute parent app', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.request.foobar = function () {
return 'tobi'
}
app2.request.foobar = function () {
return 'loki'
}
app1.use('/sub', app2)
app1.get('/sub/foo', function (req, res) {
res.send(req.foobar())
})
app2.get('/', function (req, res) {
res.send(req.foobar())
})
request(app1)
.get('/sub')
.expect(200, 'loki', cb)
request(app1)
.get('/sub/foo')
.expect(200, 'tobi', cb)
})
})
})

View File

@@ -1,4 +1,6 @@
'use strict'
var after = require('after')
var express = require('../')
, request = require('supertest');
@@ -20,25 +22,122 @@ describe('app', function(){
.expect('HEY', done);
})
it('should not be influenced by other app protos', function(done){
var app = express()
, app2 = express();
it('should only extend for the referenced app', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app.response.shout = function(str){
this.send(str.toUpperCase());
};
app1.response.shout = function (str) {
this.send(str.toUpperCase())
}
app2.response.shout = function(str){
this.send(str);
};
app1.get('/', function (req, res) {
res.shout('foo')
})
app.use(function(req, res){
res.shout('hey');
});
app2.get('/', function (req, res) {
res.shout('foo')
})
request(app)
.get('/')
.expect('HEY', done);
request(app1)
.get('/')
.expect(200, 'FOO', cb)
request(app2)
.get('/')
.expect(500, /(?:not a function|has no method)/, cb)
})
it('should inherit to sub apps', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.response.shout = function (str) {
this.send(str.toUpperCase())
}
app1.use('/sub', app2)
app1.get('/', function (req, res) {
res.shout('foo')
})
app2.get('/', function (req, res) {
res.shout('foo')
})
request(app1)
.get('/')
.expect(200, 'FOO', cb)
request(app1)
.get('/sub')
.expect(200, 'FOO', cb)
})
it('should allow sub app to override', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.response.shout = function (str) {
this.send(str.toUpperCase())
}
app2.response.shout = function (str) {
this.send(str + '!')
}
app1.use('/sub', app2)
app1.get('/', function (req, res) {
res.shout('foo')
})
app2.get('/', function (req, res) {
res.shout('foo')
})
request(app1)
.get('/')
.expect(200, 'FOO', cb)
request(app1)
.get('/sub')
.expect(200, 'foo!', cb)
})
it('should not pollute parent app', function (done) {
var app1 = express()
var app2 = express()
var cb = after(2, done)
app1.response.shout = function (str) {
this.send(str.toUpperCase())
}
app2.response.shout = function (str) {
this.send(str + '!')
}
app1.use('/sub', app2)
app1.get('/sub/foo', function (req, res) {
res.shout('foo')
})
app2.get('/', function (req, res) {
res.shout('foo')
})
request(app1)
.get('/sub')
.expect(200, 'foo!', cb)
request(app1)
.get('/sub/foo')
.expect(200, 'FOO', cb)
})
})
})

Some files were not shown because too many files have changed in this diff Show More