diff --git a/src/content/api/4x/api/application/index.mdx b/src/content/api/4x/api/application/index.mdx
index ac97e72765..3be84862c7 100644
--- a/src/content/api/4x/api/application/index.mdx
+++ b/src/content/api/4x/api/application/index.mdx
@@ -697,6 +697,21 @@ However, the other methods listed above work in exactly the same way.
To route methods that translate to invalid JavaScript variable names, use the bracket notation. For example, `app['m-search']('/', function ...`.
+```js ins={10}
+app.get('/', function (req, res) {
+ res.send('GET request to homepage');
+});
+
+app.post('/', function (req, res) {
+ res.send('POST request to homepage');
+});
+
+// methods that are invalid JavaScript variable names use bracket notation
+app['m-search']('/', function (req, res) {
+ res.send('M-SEARCH request to homepage');
+});
+```
+
The `app.get()` function is automatically called for the HTTP `HEAD` method in addition to the
@@ -1127,7 +1142,9 @@ app.get('title'); // "My Site"
The following table lists application settings.
-Note that sub-apps will:
+
+
+Sub-apps will:
- Not inherit the value of settings that have a default value. You must set the value in the sub-app.
- Inherit the value of settings with no default value; these are explicitly noted in the table below.
@@ -1135,10 +1152,18 @@ Note that sub-apps will:
Exceptions: Sub-apps will inherit the value of `trust proxy` even though it has a default value (for backward-compatibility);
Sub-apps will not inherit the value of `view cache` in production (when `NODE_ENV` is "production").
+
+
- Enable case sensitivity. When enabled, "/Foo" and "/foo" are different routes. When disabled, "/Foo" and "/foo" are treated the same. **NOTE**: Sub-apps will inherit the value of this setting.
+ Enable case sensitivity. When enabled, "/Foo" and "/foo" are different routes. When disabled, "/Foo" and "/foo" are treated the same.
+
+
+
+ Sub-apps will inherit the value of this setting.
+
+
Environment mode. Be sure to set to "production" in a production environment; see [Production best practices: performance and reliability](/advanced/best-practice-performance#things-to-do-in-your-environment--setup).
@@ -1150,38 +1175,89 @@ Sub-apps will not inherit the value of `view cache` in production (when `NODE_EN
Specifies the default JSONP callback name.
- Enable escaping JSON responses from the `res.json`, `res.jsonp`, and `res.send` APIs. This will escape the characters `<`, `>`, and `&` as Unicode escape sequences in JSON. The purpose of this is to assist with [mitigating certain types of persistent XSS attacks](https://blog.mozilla.org/security/2017/07/18/web-service-audits-firefox-accounts/) when clients sniff responses for HTML. **NOTE**: Sub-apps will inherit the value of this setting.
+ Enable escaping JSON responses from the `res.json`, `res.jsonp`, and `res.send` APIs. This will escape the characters `<`, `>`, and `&` as Unicode escape sequences in JSON. The purpose of this is to assist with [mitigating certain types of persistent XSS attacks](https://blog.mozilla.org/security/2017/07/18/web-service-audits-firefox-accounts/) when clients sniff responses for HTML.
+
+
+
+ Sub-apps will inherit the value of this setting.
+
+
- The ['replacer' argument used by `JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter). **NOTE**: Sub-apps will inherit the value of this setting.
+ The ['replacer' argument used by `JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter).
+
+
+
+ Sub-apps will inherit the value of this setting.
+
+
- The ['space' argument used by `JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_space_parameter). This is typically set to the number of spaces to use to indent prettified JSON. **NOTE**: Sub-apps will inherit the value of this setting.
+ The ['space' argument used by `JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_space_parameter). This is typically set to the number of spaces to use to indent prettified JSON.
+
+
+
+ Sub-apps will inherit the value of this setting.
+
+
Disable query parsing by setting the value to `false`, or set the query parser to use either "simple" or "extended" or a custom query string parsing function. The simple query parser is based on Node's native query parser, [querystring](https://nodejs.org/api/querystring.html). The extended query parser is based on [qs](https://www.npmjs.com/package/qs). A custom query string parsing function will receive the complete query string, and must return an object of query keys and their values.
- Enable strict routing. When enabled, the router treats "/foo" and "/foo/" as different. Otherwise, the router treats "/foo" and "/foo/" as the same. **NOTE**: Sub-apps will inherit the value of this setting.
+ Enable strict routing. When enabled, the router treats "/foo" and "/foo/" as different. Otherwise, the router treats "/foo" and "/foo/" as the same.
+
+
+
+ Sub-apps will inherit the value of this setting.
+
+
The number of dot-separated parts of the host to remove to access subdomain.
- Indicates the app is behind a front-facing proxy, and to use the `X-Forwarded-*` headers to determine the connection and the IP address of the client. NOTE: `X-Forwarded-*` headers are easily spoofed and the detected IP addresses are unreliable. When enabled, Express attempts to determine the IP address of the client connected through the front-facing proxy, or series of proxies. The `req.ips` property, then contains an array of IP addresses the client is connected through. To enable it, use the values described in the trust proxy options table below. The `trust proxy` setting is implemented using the [proxy-addr](https://www.npmjs.com/package/proxy-addr) package. For more information, see its documentation. **NOTE**: Sub-apps _will_ inherit the value of this setting, even though it has a default value.
+ Indicates the app is behind a front-facing proxy, and to use the `X-Forwarded-*` headers to determine the connection and the IP address of the client.
+
+
+
+ `X-Forwarded-*` headers are easily spoofed and the detected IP addresses are unreliable.
+
+
+
+ When enabled, Express attempts to determine the IP address of the client connected through the front-facing proxy, or series of proxies. The `req.ips` property, then contains an array of IP addresses the client is connected through. To enable it, use the values described in the trust proxy options table below. The `trust proxy` setting is implemented using the [proxy-addr](https://www.npmjs.com/package/proxy-addr) package. For more information, see its documentation.
+
+
+
+ Sub-apps _will_ inherit the value of this setting, even though it has a default value.
+
+
-
+
A directory or an array of directories for the application's views. If an array, the views are looked up in the order they occur in the array.
- Enables view template compilation caching. **NOTE**: Sub-apps will not inherit the value of this setting in production (when `NODE_ENV` is "production").
+ Enables view template compilation caching.
+
+
+
+ Sub-apps will not inherit the value of this setting in production (when `NODE_ENV` is "production").
+
+
- The default engine extension to use when omitted. **NOTE**: Sub-apps will inherit the value of this setting.
+ The default engine extension to use when omitted.
+
+
+
+ Sub-apps will inherit the value of this setting.
+
+
Enables the "X-Powered-By: Express" HTTP header.
+
@@ -1239,7 +1315,11 @@ app.set('trust proxy', function (ip) {
#### Options for `etag` setting
-**NOTE**: These settings apply only to dynamic files, not static files. The `express.static` middleware ignores these settings.
+
+
+These settings apply only to dynamic files, not static files. The `express.static` middleware ignores these settings.
+
+
The ETag functionality is implemented using the [etag](https://www.npmjs.com/package/etag) package. For more information, see its documentation.
@@ -1305,7 +1385,6 @@ app.use(function (req, res, next) {
```
-**NOTE**
Sub-apps will:
diff --git a/src/content/api/4x/api/express/index.mdx b/src/content/api/4x/api/express/index.mdx
index 295a4e99ea..8ee01d7c36 100644
--- a/src/content/api/4x/api/express/index.mdx
+++ b/src/content/api/4x/api/express/index.mdx
@@ -89,6 +89,33 @@ may not be a function and instead a string or other user-input.
+```cjs title="index.cjs" ins={5}
+var express = require('express');
+var app = express();
+
+// parse requests with a Content-Type of application/json
+app.use(express.json());
+
+app.post('/profile', function (req, res) {
+ console.dir(req.body);
+ res.json(req.body);
+});
+```
+
+```mjs title="index.mjs" ins={6}
+import express from 'express';
+
+const app = express();
+
+// parse requests with a Content-Type of application/json
+app.use(express.json());
+
+app.post('/profile', (req, res) => {
+ console.dir(req.body);
+ res.json(req.body);
+});
+```
+
### express.raw()
@@ -148,6 +175,33 @@ Testing that `req.body` is a `Buffer` before calling buffer methods is recommend
+```cjs title="index.cjs" ins={5}
+var express = require('express');
+var app = express();
+
+// parse requests with a Content-Type of application/octet-stream into a Buffer
+app.use(express.raw());
+
+app.post('/upload', function (req, res) {
+ console.dir(Buffer.isBuffer(req.body)); // => true
+ res.send('received ' + req.body.length + ' bytes');
+});
+```
+
+```mjs title="index.mjs" ins={6}
+import express from 'express';
+
+const app = express();
+
+// parse requests with a Content-Type of application/octet-stream into a Buffer
+app.use(express.raw());
+
+app.post('/upload', (req, res) => {
+ console.dir(Buffer.isBuffer(req.body)); // => true
+ res.send(`received ${req.body.length} bytes`);
+});
+```
+
### express.Router()
@@ -194,7 +248,13 @@ For more information, see [Router](/api/router/).
[dotfiles](#dotfiles) below.
- Enable or disable etag generation. NOTE: `express.static` always sends weak ETags.
+ Enable or disable etag generation.
+
+
+
+ `express.static` always sends weak ETags.
+
+
Sets file extension fallbacks: If a file is not found, search for files with the specified
@@ -302,7 +362,10 @@ Arguments:
Here is an example of using the `express.static` middleware function with an elaborate options object:
-```js
+```cjs title="index.cjs" ins={16}
+var express = require('express');
+var app = express();
+
var options = {
dotfiles: 'ignore',
etag: false,
@@ -318,6 +381,26 @@ var options = {
app.use(express.static('public', options));
```
+```mjs title="index.mjs" ins={17}
+import express from 'express';
+
+const app = express();
+
+const options = {
+ dotfiles: 'ignore',
+ etag: false,
+ extensions: ['htm', 'html'],
+ index: false,
+ maxAge: '1d',
+ redirect: false,
+ setHeaders: (res, path, stat) => {
+ res.set('x-timestamp', Date.now());
+ },
+};
+
+app.use(express.static('public', options));
+```
+
### express.text()
@@ -381,6 +464,33 @@ Testing that `req.body` is a string before calling string methods is recommended
+```cjs title="index.cjs" ins={5}
+var express = require('express');
+var app = express();
+
+// parse requests with a Content-Type of text/plain into a string
+app.use(express.text());
+
+app.post('/', function (req, res) {
+ console.dir(typeof req.body); // => 'string'
+ res.send(req.body);
+});
+```
+
+```mjs title="index.mjs" ins={6}
+import express from 'express';
+
+const app = express();
+
+// parse requests with a Content-Type of text/plain into a string
+app.use(express.text());
+
+app.post('/', (req, res) => {
+ console.dir(typeof req.body); // => 'string'
+ res.send(req.body);
+});
+```
+
### express.urlencoded()
@@ -457,3 +567,30 @@ fail in multiple ways, for example `foo` may not be there or may not be a string
may not be a function and instead a string or other user-input.
+
+```cjs title="index.cjs" ins={5}
+var express = require('express');
+var app = express();
+
+// parse requests with a Content-Type of application/x-www-form-urlencoded
+app.use(express.urlencoded({ extended: true }));
+
+app.post('/profile', function (req, res) {
+ console.dir(req.body);
+ res.json(req.body);
+});
+```
+
+```mjs title="index.mjs" ins={6}
+import express from 'express';
+
+const app = express();
+
+// parse requests with a Content-Type of application/x-www-form-urlencoded
+app.use(express.urlencoded({ extended: true }));
+
+app.post('/profile', (req, res) => {
+ console.dir(req.body);
+ res.json(req.body);
+});
+```
diff --git a/src/content/api/4x/api/request/index.mdx b/src/content/api/4x/api/request/index.mdx
index 860c57d20d..a20725bf14 100644
--- a/src/content/api/4x/api/request/index.mdx
+++ b/src/content/api/4x/api/request/index.mdx
@@ -247,6 +247,17 @@ empty array. This header can be set by the client or by the proxy.
For example, if `X-Forwarded-For` is `client, proxy1, proxy2`, `req.ips` would be
`["client", "proxy1", "proxy2"]`, where `proxy2` is the furthest downstream.
+```js
+// normal request, or `trust proxy` disabled (the default)
+console.dir(req.ips);
+// => []
+
+// app.set('trust proxy', true) and
+// request header `X-Forwarded-For: client, proxy1, proxy2`
+console.dir(req.ips);
+// => ['client', 'proxy1', 'proxy2']
+```
+
### req.method
@@ -254,6 +265,14 @@ For example, if `X-Forwarded-For` is `client, proxy1, proxy2`, `req.ips` would b
Contains a string corresponding to the HTTP method of the request:
`GET`, `POST`, `PUT`, and so on.
+```js
+app.use(function (req, res, next) {
+ console.dir(req.method);
+ // => 'GET'
+ next();
+});
+```
+
### req.originalUrl
@@ -400,6 +419,14 @@ Check out the [query parser application setting](/api/application/#application-s
This property holds a reference to the [response object](/api/response)
that relates to this request object.
+```js
+app.get('/', function (req, res) {
+ console.dir(req.res === res);
+ // => true
+ res.send('OK');
+});
+```
+
### req.route
@@ -563,6 +590,15 @@ Returns the first accepted charset of the specified character sets,
based on the request's `Accept-Charset` HTTP header field.
If none of the specified charsets is accepted, returns `false`.
+```js
+// Accept-Charset: utf-8, iso-8859-1;q=0.5
+req.acceptsCharsets('utf-8', 'iso-8859-1');
+// => 'utf-8'
+
+req.acceptsCharsets('us-ascii');
+// => false
+```
+
For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).
### req.acceptsEncodings()
@@ -579,6 +615,15 @@ Returns the first accepted encoding of the specified encodings,
based on the request's `Accept-Encoding` HTTP header field.
If none of the specified encodings is accepted, returns `false`.
+```js
+// Accept-Encoding: gzip, deflate
+req.acceptsEncodings('gzip', 'deflate');
+// => 'gzip'
+
+req.acceptsEncodings('br');
+// => false
+```
+
For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).
### req.acceptsLanguages()
@@ -600,6 +645,15 @@ If no `lang` argument is given, then `req.acceptsLanguages()`
returns all languages from the HTTP `Accept-Language` header
as an `Array`.
+```js
+// Accept-Language: en;q=0.8, es
+req.acceptsLanguages('en', 'es');
+// => 'es'
+
+req.acceptsLanguages();
+// => ['es', 'en']
+```
+
For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).
Express (4.x) source: [request.js line 179](https://github.com/expressjs/express/blob/4.x/lib/request.js#L179)
diff --git a/src/content/api/4x/api/response/index.mdx b/src/content/api/4x/api/response/index.mdx
index ae82a0f406..dba01d7761 100644
--- a/src/content/api/4x/api/response/index.mdx
+++ b/src/content/api/4x/api/response/index.mdx
@@ -42,6 +42,15 @@ This property holds a reference to the instance of the Express application that
`res.app` is identical to the [req.app](/api/request/#reqapp) property in the request object.
+```js
+app.get('/', function (req, res) {
+ console.dir(res.app.get('view engine'));
+ console.dir(res.app === req.app);
+ // => true
+ res.send('OK');
+});
+```
+
### res.headersSent
@@ -95,6 +104,14 @@ app.use(function (req, res, next) {
This property holds a reference to the [request object](/api/request/)
that relates to this response object.
+```js
+app.get('/', function (req, res) {
+ console.dir(res.req === req);
+ // => true
+ res.send('OK');
+});
+```
+
## Methods
### res.append()
diff --git a/src/content/api/4x/api/router/index.mdx b/src/content/api/4x/api/router/index.mdx
index a2ca3c839a..e6a169d2c9 100644
--- a/src/content/api/4x/api/router/index.mdx
+++ b/src/content/api/4x/api/router/index.mdx
@@ -65,6 +65,33 @@ app.use('/calendar', router);
+Creates a new router object.
+
+```cjs title="index.cjs" ins={2}
+var express = require('express');
+var router = express.Router({ caseSensitive: true, strict: true });
+
+router.get('/events', function (req, res) {
+ res.send('events');
+});
+
+// mount the router on an app
+app.use('/calendar', router);
+```
+
+```mjs title="index.mjs" ins={3}
+import express from 'express';
+
+const router = express.Router({ caseSensitive: true, strict: true });
+
+router.get('/events', (req, res) => {
+ res.send('events');
+});
+
+// mount the router on an app
+app.use('/calendar', router);
+```
+
### router.all()
@@ -533,10 +560,16 @@ router.use(express.static(path.join(__dirname, 'uploads')));
The `router.use()` method also supports named parameters so that your mount points
for other routers can benefit from preloading using named parameters.
-**NOTE**: Although these middleware functions are added via a particular router, _when_
+
+
+Although these middleware functions are added via a particular router, _when_
they run is defined by the path they are attached to (not the router). Therefore,
middleware added via one router may run for other routers if its routes
-match. For example, this code shows two different routers mounted on the same path:
+match.
+
+
+
+For example, this code shows two different routers mounted on the same path:
```js
var authRouter = express.Router();
diff --git a/src/content/api/5x/api/application/index.mdx b/src/content/api/5x/api/application/index.mdx
index c03f08506c..c5c78a444f 100644
--- a/src/content/api/5x/api/application/index.mdx
+++ b/src/content/api/5x/api/application/index.mdx
@@ -204,7 +204,6 @@ For more information, see [Router](/api/router/).
The `mount` event is fired on a sub-app, when it is mounted on a parent app. The parent app is passed to the callback function.
-**NOTE**
Sub-apps will:
@@ -753,6 +752,21 @@ However, the other methods listed above work in exactly the same way.
To route methods that translate to invalid JavaScript variable names, use the bracket notation. For example, `app['m-search']('/', function ...`.
+```js ins={10}
+app.get('/', (req, res) => {
+ res.send('GET request to homepage');
+});
+
+app.post('/', (req, res) => {
+ res.send('POST request to homepage');
+});
+
+// methods that are invalid JavaScript variable names use bracket notation
+app['m-search']('/', (req, res) => {
+ res.send('M-SEARCH request to homepage');
+});
+```
+
The `app.get()` function is automatically called for the HTTP `HEAD` method in addition to the
@@ -1070,7 +1084,9 @@ app.get('title'); // "My Site"
The following table lists application settings.
-Note that sub-apps will:
+
+
+Sub-apps will:
- Not inherit the value of settings that have a default value. You must set the value in the sub-app.
- Inherit the value of settings with no default value; these are explicitly noted in the table below.
@@ -1078,10 +1094,18 @@ Note that sub-apps will:
Exceptions: Sub-apps will inherit the value of `trust proxy` even though it has a default value (for backward-compatibility);
Sub-apps will not inherit the value of `view cache` in production (when `NODE_ENV` is "production").
+
+
- Enable case sensitivity. When enabled, "/Foo" and "/foo" are different routes. When disabled, "/Foo" and "/foo" are treated the same. **NOTE**: Sub-apps will inherit the value of this setting.
+ Enable case sensitivity. When enabled, "/Foo" and "/foo" are different routes. When disabled, "/Foo" and "/foo" are treated the same.
+
+
+
+ Sub-apps will inherit the value of this setting.
+
+
Environment mode. Be sure to set to "production" in a production environment; see [Production best practices: performance and reliability](/advanced/best-practice-performance#things-to-do-in-your-environment--setup).
@@ -1093,38 +1117,89 @@ Sub-apps will not inherit the value of `view cache` in production (when `NODE_EN
Specifies the default JSONP callback name.
- Enable escaping JSON responses from the `res.json`, `res.jsonp`, and `res.send` APIs. This will escape the characters `<`, `>`, and `&` as Unicode escape sequences in JSON. The purpose of this is to assist with [mitigating certain types of persistent XSS attacks](https://blog.mozilla.org/security/2017/07/18/web-service-audits-firefox-accounts/) when clients sniff responses for HTML. **NOTE**: Sub-apps will inherit the value of this setting.
+ Enable escaping JSON responses from the `res.json`, `res.jsonp`, and `res.send` APIs. This will escape the characters `<`, `>`, and `&` as Unicode escape sequences in JSON. The purpose of this is to assist with [mitigating certain types of persistent XSS attacks](https://blog.mozilla.org/security/2017/07/18/web-service-audits-firefox-accounts/) when clients sniff responses for HTML.
+
+
+
+ Sub-apps will inherit the value of this setting.
+
+
- The ['replacer' argument used by `JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter). **NOTE**: Sub-apps will inherit the value of this setting.
+ The ['replacer' argument used by `JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter).
+
+
+
+ Sub-apps will inherit the value of this setting.
+
+
- The ['space' argument used by `JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_space_parameter). This is typically set to the number of spaces to use to indent prettified JSON. **NOTE**: Sub-apps will inherit the value of this setting.
+ The ['space' argument used by `JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_space_parameter). This is typically set to the number of spaces to use to indent prettified JSON.
+
+
+
+ Sub-apps will inherit the value of this setting.
+
+
Disable query parsing by setting the value to `false`, or set the query parser to use either "simple" or "extended" or a custom query string parsing function. The simple query parser is based on Node's native query parser, [querystring](https://nodejs.org/api/querystring.html). The extended query parser is based on [qs](https://www.npmjs.com/package/qs). A custom query string parsing function will receive the complete query string, and must return an object of query keys and their values.
- Enable strict routing. When enabled, the router treats "/foo" and "/foo/" as different. Otherwise, the router treats "/foo" and "/foo/" as the same. **NOTE**: Sub-apps will inherit the value of this setting.
+ Enable strict routing. When enabled, the router treats "/foo" and "/foo/" as different. Otherwise, the router treats "/foo" and "/foo/" as the same.
+
+
+
+ Sub-apps will inherit the value of this setting.
+
+
The number of dot-separated parts of the host to remove to access subdomain.
- Indicates the app is behind a front-facing proxy, and to use the `X-Forwarded-*` headers to determine the connection and the IP address of the client. NOTE: `X-Forwarded-*` headers are easily spoofed and the detected IP addresses are unreliable. When enabled, Express attempts to determine the IP address of the client connected through the front-facing proxy, or series of proxies. The `req.ips` property, then contains an array of IP addresses the client is connected through. To enable it, use the values described in the trust proxy options table below. The `trust proxy` setting is implemented using the [proxy-addr](https://www.npmjs.com/package/proxy-addr) package. For more information, see its documentation. **NOTE**: Sub-apps _will_ inherit the value of this setting, even though it has a default value.
+ Indicates the app is behind a front-facing proxy, and to use the `X-Forwarded-*` headers to determine the connection and the IP address of the client.
+
+
+
+ `X-Forwarded-*` headers are easily spoofed and the detected IP addresses are unreliable.
+
+
+
+ When enabled, Express attempts to determine the IP address of the client connected through the front-facing proxy, or series of proxies. The `req.ips` property, then contains an array of IP addresses the client is connected through. To enable it, use the values described in the trust proxy options table below. The `trust proxy` setting is implemented using the [proxy-addr](https://www.npmjs.com/package/proxy-addr) package. For more information, see its documentation.
+
+
+
+ Sub-apps _will_ inherit the value of this setting, even though it has a default value.
+
+
-
+
A directory or an array of directories for the application's views. If an array, the views are looked up in the order they occur in the array.
- Enables view template compilation caching. **NOTE**: Sub-apps will not inherit the value of this setting in production (when `NODE_ENV` is "production").
+ Enables view template compilation caching.
+
+
+
+ Sub-apps will not inherit the value of this setting in production (when `NODE_ENV` is "production").
+
+
- The default engine extension to use when omitted. **NOTE**: Sub-apps will inherit the value of this setting.
+ The default engine extension to use when omitted.
+
+
+
+ Sub-apps will inherit the value of this setting.
+
+
Enables the "X-Powered-By: Express" HTTP header.
+
@@ -1182,7 +1257,11 @@ app.set('trust proxy', (ip) => {
#### Options for `etag` setting
-**NOTE**: These settings apply only to dynamic files, not static files. The `express.static` middleware ignores these settings.
+
+
+These settings apply only to dynamic files, not static files. The `express.static` middleware ignores these settings.
+
+
The ETag functionality is implemented using the [etag](https://www.npmjs.com/package/etag) package. For more information, see its documentation.
@@ -1248,7 +1327,6 @@ app.use((req, res, next) => {
```
-**NOTE**
Sub-apps will:
diff --git a/src/content/api/5x/api/express/index.mdx b/src/content/api/5x/api/express/index.mdx
index a4976b4d44..36adbe9419 100644
--- a/src/content/api/5x/api/express/index.mdx
+++ b/src/content/api/5x/api/express/index.mdx
@@ -96,6 +96,33 @@ may not be a function and instead a string or other user-input.
+```cjs title="index.cjs" ins={5}
+const express = require('express');
+const app = express();
+
+// parse requests with a Content-Type of application/json
+app.use(express.json());
+
+app.post('/profile', (req, res) => {
+ console.dir(req.body);
+ res.json(req.body);
+});
+```
+
+```mjs title="index.mjs" ins={6}
+import express from 'express';
+
+const app = express();
+
+// parse requests with a Content-Type of application/json
+app.use(express.json());
+
+app.post('/profile', (req, res) => {
+ console.dir(req.body);
+ res.json(req.body);
+});
+```
+
### express.raw()
@@ -155,6 +182,33 @@ Testing that `req.body` is a `Buffer` before calling buffer methods is recommend
+```cjs title="index.cjs" ins={5}
+const express = require('express');
+const app = express();
+
+// parse requests with a Content-Type of application/octet-stream into a Buffer
+app.use(express.raw());
+
+app.post('/upload', (req, res) => {
+ console.dir(Buffer.isBuffer(req.body)); // => true
+ res.send(`received ${req.body.length} bytes`);
+});
+```
+
+```mjs title="index.mjs" ins={6}
+import express from 'express';
+
+const app = express();
+
+// parse requests with a Content-Type of application/octet-stream into a Buffer
+app.use(express.raw());
+
+app.post('/upload', (req, res) => {
+ console.dir(Buffer.isBuffer(req.body)); // => true
+ res.send(`received ${req.body.length} bytes`);
+});
+```
+
### express.Router()
@@ -201,7 +255,13 @@ For more information, see [Router](/api/router/).
[dotfiles](#dotfiles) below.
- Enable or disable etag generation. NOTE: `express.static` always sends weak ETags.
+ Enable or disable etag generation.
+
+
+
+ `express.static` always sends weak ETags.
+
+
Sets file extension fallbacks: If a file is not found, search for files with the specified
@@ -253,7 +313,7 @@ It serves static files and is based on [serve-static](/resources/middleware/serv
-NOTE: For best results, [use a reverse
+For best results, [use a reverse
proxy](/advanced/best-practice-performance#use-a-reverse-proxy) cache to improve performance of
serving static assets.
@@ -308,7 +368,30 @@ Arguments:
Here is an example of using the `express.static` middleware function with an elaborate options object:
-```js
+```cjs title="index.cjs" ins={16}
+const express = require('express');
+const app = express();
+
+const options = {
+ dotfiles: 'ignore',
+ etag: false,
+ extensions: ['htm', 'html'],
+ index: false,
+ maxAge: '1d',
+ redirect: false,
+ setHeaders(res, path, stat) {
+ res.set('x-timestamp', Date.now());
+ },
+};
+
+app.use(express.static('public', options));
+```
+
+```mjs title="index.mjs" ins={17}
+import express from 'express';
+
+const app = express();
+
const options = {
dotfiles: 'ignore',
etag: false,
@@ -387,6 +470,33 @@ Testing that `req.body` is a string before calling string methods is recommended
+```cjs title="index.cjs" ins={5}
+const express = require('express');
+const app = express();
+
+// parse requests with a Content-Type of text/plain into a string
+app.use(express.text());
+
+app.post('/', (req, res) => {
+ console.dir(typeof req.body); // => 'string'
+ res.send(req.body);
+});
+```
+
+```mjs title="index.mjs" ins={6}
+import express from 'express';
+
+const app = express();
+
+// parse requests with a Content-Type of text/plain into a string
+app.use(express.text());
+
+app.post('/', (req, res) => {
+ console.dir(typeof req.body); // => 'string'
+ res.send(req.body);
+});
+```
+
### express.urlencoded()
@@ -474,3 +584,30 @@ fail in multiple ways, for example `foo` may not be there or may not be a string
may not be a function and instead a string or other user-input.
+
+```cjs title="index.cjs" ins={5}
+const express = require('express');
+const app = express();
+
+// parse requests with a Content-Type of application/x-www-form-urlencoded
+app.use(express.urlencoded({ extended: true }));
+
+app.post('/profile', (req, res) => {
+ console.dir(req.body);
+ res.json(req.body);
+});
+```
+
+```mjs title="index.mjs" ins={6}
+import express from 'express';
+
+const app = express();
+
+// parse requests with a Content-Type of application/x-www-form-urlencoded
+app.use(express.urlencoded({ extended: true }));
+
+app.post('/profile', (req, res) => {
+ console.dir(req.body);
+ res.json(req.body);
+});
+```
diff --git a/src/content/api/5x/api/request/index.mdx b/src/content/api/5x/api/request/index.mdx
index ba6f2f6c77..a5a007fb0d 100644
--- a/src/content/api/5x/api/request/index.mdx
+++ b/src/content/api/5x/api/request/index.mdx
@@ -256,6 +256,17 @@ empty array. This header can be set by the client or by the proxy.
For example, if `X-Forwarded-For` is `client, proxy1, proxy2`, `req.ips` would be
`["client", "proxy1", "proxy2"]`, where `proxy2` is the furthest downstream.
+```js
+// normal request, or `trust proxy` disabled (the default)
+console.dir(req.ips);
+// => []
+
+// app.set('trust proxy', true) and
+// request header `X-Forwarded-For: client, proxy1, proxy2`
+console.dir(req.ips);
+// => ['client', 'proxy1', 'proxy2']
+```
+
### req.method
@@ -263,6 +274,14 @@ For example, if `X-Forwarded-For` is `client, proxy1, proxy2`, `req.ips` would b
Contains a string corresponding to the HTTP method of the request:
`GET`, `POST`, `PUT`, and so on.
+```js
+app.use((req, res, next) => {
+ console.dir(req.method);
+ // => 'GET'
+ next();
+});
+```
+
### req.originalUrl
@@ -423,6 +442,14 @@ Check out the [query parser application setting](/api/application/#application-s
This property holds a reference to the [response object](/api/response)
that relates to this request object.
+```js
+app.get('/', (req, res) => {
+ console.dir(req.res === res);
+ // => true
+ res.send('OK');
+});
+```
+
### req.route
@@ -593,6 +620,15 @@ Returns the first accepted charset of the specified character sets,
based on the request's `Accept-Charset` HTTP header field.
If none of the specified charsets is accepted, returns `false`.
+```js
+// Accept-Charset: utf-8, iso-8859-1;q=0.5
+req.acceptsCharsets('utf-8', 'iso-8859-1');
+// => 'utf-8'
+
+req.acceptsCharsets('us-ascii');
+// => false
+```
+
For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).
### req.acceptsEncodings()
@@ -609,6 +645,15 @@ Returns the first accepted encoding of the specified encodings,
based on the request's `Accept-Encoding` HTTP header field.
If none of the specified encodings is accepted, returns `false`.
+```js
+// Accept-Encoding: gzip, deflate
+req.acceptsEncodings('gzip', 'deflate');
+// => 'gzip'
+
+req.acceptsEncodings('br');
+// => false
+```
+
For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).
### req.acceptsLanguages()
@@ -630,6 +675,15 @@ If no `lang` argument is given, then `req.acceptsLanguages()`
returns all languages from the HTTP `Accept-Language` header
as an `Array`.
+```js
+// Accept-Language: en;q=0.8, es
+req.acceptsLanguages('en', 'es');
+// => 'es'
+
+req.acceptsLanguages();
+// => ['es', 'en']
+```
+
For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts).
Express (5.x) source: [request.js line 172](https://github.com/expressjs/express/blob/v5.1.0/lib/request.js#L172)
diff --git a/src/content/api/5x/api/response/index.mdx b/src/content/api/5x/api/response/index.mdx
index c6421e9777..7f2e3b4e09 100644
--- a/src/content/api/5x/api/response/index.mdx
+++ b/src/content/api/5x/api/response/index.mdx
@@ -42,6 +42,15 @@ This property holds a reference to the instance of the Express application that
`res.app` is identical to the [req.app](/api/request/#reqapp) property in the request object.
+```js
+app.get('/', (req, res) => {
+ console.dir(res.app.get('view engine'));
+ console.dir(res.app === req.app);
+ // => true
+ res.send('OK');
+});
+```
+
### res.headersSent
@@ -95,6 +104,14 @@ app.use((req, res, next) => {
This property holds a reference to the [request object](/api/request/)
that relates to this response object.
+```js
+app.get('/', (req, res) => {
+ console.dir(res.req === req);
+ // => true
+ res.send('OK');
+});
+```
+
## Methods
### res.append()
diff --git a/src/content/api/5x/api/router/index.mdx b/src/content/api/5x/api/router/index.mdx
index bb9b1e25be..7fd7c55ab6 100644
--- a/src/content/api/5x/api/router/index.mdx
+++ b/src/content/api/5x/api/router/index.mdx
@@ -65,6 +65,33 @@ app.use('/calendar', router);
+Creates a new router object.
+
+```cjs title="index.cjs" ins={2}
+const express = require('express');
+const router = express.Router({ caseSensitive: true, strict: true });
+
+router.get('/events', (req, res) => {
+ res.send('events');
+});
+
+// mount the router on an app
+app.use('/calendar', router);
+```
+
+```mjs title="index.mjs" ins={3}
+import express from 'express';
+
+const router = express.Router({ caseSensitive: true, strict: true });
+
+router.get('/events', (req, res) => {
+ res.send('events');
+});
+
+// mount the router on an app
+app.use('/calendar', router);
+```
+
### router.all()
@@ -460,10 +487,16 @@ app.use(express.static(path.join(__dirname, 'uploads')));
The `router.use()` method also supports named parameters so that your mount points
for other routers can benefit from preloading using named parameters.
-**NOTE**: Although these middleware functions are added via a particular router, _when_
+
+
+Although these middleware functions are added via a particular router, _when_
they run is defined by the path they are attached to (not the router). Therefore,
middleware added via one router may run for other routers if its routes
-match. For example, this code shows two different routers mounted on the same path:
+match.
+
+
+
+For example, this code shows two different routers mounted on the same path:
```js
const authRouter = express.Router();