diff --git a/.github/scripts/get-contributing.sh b/.github/scripts/get-contributing.sh deleted file mode 100755 index 0722a7c500..0000000000 --- a/.github/scripts/get-contributing.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/bash - -DEST="../../en/resources/contributing.md" - -# This script replaces the contents of a section with the contents from -# the annotated source address. - -level='' -src='' -while IFS= read -r line; do - if [[ -n "$src" ]] && [[ "$line" != '#'* || "$line" == "$level"'#'* ]]; then - continue - fi - - src='' - if [[ "$line" == '#'* ]]; then - title=${line##*\#} - level="${line:0:$((${#line} - ${#title}))}" - elif [[ "$line" == ' - A documentação da API está em andamento. Para obter informações sobre o que há no lançamento, consulte o histórico de lançamentos do Express. -

- - \ No newline at end of file diff --git a/_includes/announcement/announcement-ru.md b/_includes/announcement/announcement-ru.md deleted file mode 100644 index be09ad7def..0000000000 --- a/_includes/announcement/announcement-ru.md +++ /dev/null @@ -1,16 +0,0 @@ - diff --git a/_includes/announcement/announcement-sk.md b/_includes/announcement/announcement-sk.md deleted file mode 100644 index be09ad7def..0000000000 --- a/_includes/announcement/announcement-sk.md +++ /dev/null @@ -1,16 +0,0 @@ - diff --git a/_includes/announcement/announcement-th.md b/_includes/announcement/announcement-th.md deleted file mode 100644 index 0f95e9559a..0000000000 --- a/_includes/announcement/announcement-th.md +++ /dev/null @@ -1,8 +0,0 @@ - diff --git a/_includes/announcement/announcement-tr.md b/_includes/announcement/announcement-tr.md deleted file mode 100644 index 8cc71cd958..0000000000 --- a/_includes/announcement/announcement-tr.md +++ /dev/null @@ -1,8 +0,0 @@ - diff --git a/_includes/announcement/announcement-uk.md b/_includes/announcement/announcement-uk.md deleted file mode 100644 index be09ad7def..0000000000 --- a/_includes/announcement/announcement-uk.md +++ /dev/null @@ -1,16 +0,0 @@ - diff --git a/_includes/announcement/announcement-uz.md b/_includes/announcement/announcement-uz.md deleted file mode 100644 index 57df38161a..0000000000 --- a/_includes/announcement/announcement-uz.md +++ /dev/null @@ -1,8 +0,0 @@ - diff --git a/_includes/announcement/announcement-zh-cn.md b/_includes/announcement/announcement-zh-cn.md deleted file mode 100644 index be09ad7def..0000000000 --- a/_includes/announcement/announcement-zh-cn.md +++ /dev/null @@ -1,16 +0,0 @@ - diff --git a/_includes/announcement/announcement-zh-tw.md b/_includes/announcement/announcement-zh-tw.md deleted file mode 100644 index be09ad7def..0000000000 --- a/_includes/announcement/announcement-zh-tw.md +++ /dev/null @@ -1,16 +0,0 @@ - diff --git a/_includes/api/en/3x/app-VERB.md b/_includes/api/en/3x/app-VERB.md deleted file mode 100644 index 6e9b0d2759..0000000000 --- a/_includes/api/en/3x/app-VERB.md +++ /dev/null @@ -1,57 +0,0 @@ -

app.VERB(path, [callback...], callback)

- -The `app.VERB()` methods provide the routing functionality -in Express, where VERB is one of the HTTP verbs, such -as `app.post()`. Multiple callbacks may be given, all are treated -equally, and behave just like middleware, with the one exception that -these callbacks may invoke `next('route')` to bypass the -remaining route callback(s). This mechanism can be used to perform pre-conditions -on a route then pass control to subsequent routes when there is no reason to proceed -with the route matched. - -The following snippet illustrates the most simple route definition possible. Express -translates the path strings to regular expressions, used internally to match incoming requests. -Query strings are not considered when peforming these matches, for example "GET /" -would match the following route, as would "GET /?name=tobi". - -```js -app.get('/', function (req, res) { - res.send('hello world') -}) -``` - -Regular expressions may also be used, and can be useful -if you have very specific restraints, for example the following -would match "GET /commits/71dbb9c" as well as "GET /commits/71dbb9c..4c084f9". - -```js -app.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function (req, res) { - var from = req.params[0] - var to = req.params[1] || 'HEAD' - res.send('commit range ' + from + '..' + to) -}) -``` - -Several callbacks may also be passed, useful for re-using middleware -that load resources, perform validations, etc. - -```js -app.get('/user/:id', user.load, function () { - // ... -}) -``` - -These callbacks may be passed within arrays as well, these arrays are -simply flattened when passed: - -```js -var middleware = [loadForum, loadThread] - -app.get('/forum/:fid/thread/:tid', middleware, function () { - // ... -}) - -app.post('/forum/:fid/thread/:tid', middleware, function () { - // ... -}) -``` diff --git a/_includes/api/en/3x/app-all.md b/_includes/api/en/3x/app-all.md deleted file mode 100644 index 6b3a1e99f5..0000000000 --- a/_includes/api/en/3x/app-all.md +++ /dev/null @@ -1,32 +0,0 @@ -

app.all(path, [callback...], callback)

- -This method functions just like the `app.VERB()` methods, -however it matches all HTTP verbs. - -This method is extremely useful for -mapping "global" logic for specific path prefixes or arbitrary matches. -For example if you placed the following route at the top of all other -route definitions, it would require that all routes from that point on -would require authentication, and automatically load a user. Keep in mind -that these callbacks do not have to act as end points, `loadUser` -can perform a task, then `next()` to continue matching subsequent -routes. - -```js -app.all('*', requireAuthentication, loadUser) -``` - -Or the equivalent: - -```js -app.all('*', requireAuthentication) -app.all('*', loadUser) -``` - -Another great example of this is white-listed "global" functionality. Here -the example is much like before, however only restricting paths prefixed with -"/api": - -```js -app.all('/api/*', requireAuthentication) -``` diff --git a/_includes/api/en/3x/app-configure.md b/_includes/api/en/3x/app-configure.md deleted file mode 100644 index 19029170e0..0000000000 --- a/_includes/api/en/3x/app-configure.md +++ /dev/null @@ -1,40 +0,0 @@ -

app.configure([env], callback)

- -Conditionally invoke `callback` when `env` matches `app.get('env')`, -aka `process.env.NODE_ENV`. This method remains for legacy reasons, and is effectively -an `if` statement as illustrated in the following snippets. These functions are not -required in order to use `app.set()` and other configuration methods. - -```js -// all environments -app.configure(function () { - app.set('title', 'My Application') -}) - -// development only -app.configure('development', function () { - app.set('db uri', 'localhost/dev') -}) - -// production only -app.configure('production', function () { - app.set('db uri', 'n.n.n.n/prod') -}) -``` - -Is effectively sugar for: - -```js -// all environments -app.set('title', 'My Application') - -// development only -if (app.get('env') === 'development') { - app.set('db uri', 'localhost/dev') -} - -// production only -if (app.get('env') === 'production') { - app.set('db uri', 'n.n.n.n/prod') -} -``` diff --git a/_includes/api/en/3x/app-disable.md b/_includes/api/en/3x/app-disable.md deleted file mode 100644 index a3525d8543..0000000000 --- a/_includes/api/en/3x/app-disable.md +++ /dev/null @@ -1,9 +0,0 @@ -

app.disable(name)

- -Set setting `name` to `false`. - -```js -app.disable('trust proxy') -app.get('trust proxy') -// => false -``` diff --git a/_includes/api/en/3x/app-disabled.md b/_includes/api/en/3x/app-disabled.md deleted file mode 100644 index f2438f1c66..0000000000 --- a/_includes/api/en/3x/app-disabled.md +++ /dev/null @@ -1,12 +0,0 @@ -

app.disabled(name)

- -Check if setting `name` is disabled. - -```js -app.disabled('trust proxy') -// => true - -app.enable('trust proxy') -app.disabled('trust proxy') -// => false -``` diff --git a/_includes/api/en/3x/app-enable.md b/_includes/api/en/3x/app-enable.md deleted file mode 100644 index 926806ec1f..0000000000 --- a/_includes/api/en/3x/app-enable.md +++ /dev/null @@ -1,9 +0,0 @@ -

app.enable(name)

- -Set setting `name` to `true`. - -```js -app.enable('trust proxy') -app.get('trust proxy') -// => true -``` diff --git a/_includes/api/en/3x/app-enabled.md b/_includes/api/en/3x/app-enabled.md deleted file mode 100644 index b485780286..0000000000 --- a/_includes/api/en/3x/app-enabled.md +++ /dev/null @@ -1,12 +0,0 @@ -

app.enabled(name)

- -Check if setting `name` is enabled. - -```js -app.enabled('trust proxy') -// => false - -app.enable('trust proxy') -app.enabled('trust proxy') -// => true -``` diff --git a/_includes/api/en/3x/app-engine.md b/_includes/api/en/3x/app-engine.md deleted file mode 100644 index fcdfd7c9d9..0000000000 --- a/_includes/api/en/3x/app-engine.md +++ /dev/null @@ -1,39 +0,0 @@ -

app.engine(ext, callback)

- -Register the given template engine `callback` as `ext` - -By default will `require()` the engine based on the -file extension. For example if you try to render -a "foo.jade" file Express will invoke the following internally, -and cache the `require()` on subsequent calls to increase -performance. - -```js -app.engine('jade', require('jade').__express) -``` - -For engines that do not provide `.__express` out of the box - -or if you wish to "map" a different extension to the template engine -you may use this method. For example mapping the EJS template engine to -".html" files: - -```js -app.engine('html', require('ejs').renderFile) -``` - -In this case EJS provides a `.renderFile()` method with -the same signature that Express expects: `(path, options, callback)`, -though note that it aliases this method as `ejs.__express` internally -so if you're using ".ejs" extensions you dont need to do anything. - -Some template engines do not follow this convention, the -consolidate.js -library was created to map all of node's popular template -engines to follow this convention, thus allowing them to -work seemlessly within Express. - -```js -var engines = require('consolidate') -app.engine('haml', engines.haml) -app.engine('html', engines.hogan) -``` diff --git a/_includes/api/en/3x/app-get.md b/_includes/api/en/3x/app-get.md deleted file mode 100644 index 15b908a1cc..0000000000 --- a/_includes/api/en/3x/app-get.md +++ /dev/null @@ -1,12 +0,0 @@ -

app.get(name)

- -Get setting `name` value. - -```js -app.get('title') -// => undefined - -app.set('title', 'My Site') -app.get('title') -// => "My Site" -``` diff --git a/_includes/api/en/3x/app-listen.md b/_includes/api/en/3x/app-listen.md deleted file mode 100644 index f2349f0b54..0000000000 --- a/_includes/api/en/3x/app-listen.md +++ /dev/null @@ -1,36 +0,0 @@ -

app.listen()

- -Bind and listen for connections on the given host and port, -this method is identical to node's http.Server#listen(). - -```js -var express = require('express') -var app = express() -app.listen(3000) -``` - -The `app` returned by `express()` is in fact a JavaScript -`Function`, designed to be passed to node's http servers as a callback -to handle requests. This allows you to provide both HTTP and HTTPS versions of -your app with the same codebase easily, as the app does not inherit from these, -it is simply a callback: - -```js -var express = require('express') -var https = require('https') -var http = require('http') -var app = express() - -http.createServer(app).listen(80) -https.createServer(options, app).listen(443) -``` - -The `app.listen()` method is simply a convenience method defined as, -if you wish to use HTTPS or provide both, use the technique above. - -```js -app.listen = function () { - var server = http.createServer(this) - return server.listen.apply(server, arguments) -} -``` diff --git a/_includes/api/en/3x/app-locals.md b/_includes/api/en/3x/app-locals.md deleted file mode 100644 index d35421160e..0000000000 --- a/_includes/api/en/3x/app-locals.md +++ /dev/null @@ -1,47 +0,0 @@ -

app.locals

- -Application local variables are provided to all templates -rendered within the application. This is useful for providing -helper functions to templates, as well as app-level data. - -```js -app.locals.title = 'My App' -app.locals.strftime = require('strftime') -``` - -The `app.locals` object is a JavaScript `Function`, -which when invoked with an object will merge properties into itself, providing -a simple way to expose existing objects as local variables. - -```js -app.locals({ - title: 'My App', - phone: '1-250-858-9990', - email: 'me@myapp.com' -}) - -console.log(app.locals.title) -// => 'My App' - -console.log(app.locals.email) -// => 'me@myapp.com' -``` - -A consequence of the `app.locals` Object being ultimately a Javascript Function Object is that you must not reuse existing (native) named properties for your own variable names, such as `name, apply, bind, call, arguments, length, constructor`. - -```js -app.locals({ name: 'My App' }) - -console.log(app.locals.name) -// => return 'app.locals' in place of 'My App' (app.locals is a Function !) -// => if name's variable is used in a template, a ReferenceError will be returned. -``` - -The full list of native named properties can be found in many specifications. The JavaScript specification introduced original properties, some of which still recognized by modern engines, and the EcmaScript specification then built on it and normalized the set of properties, adding new ones and removing deprecated ones. Check out properties for Functions and Objects if interested. - -By default Express exposes only a single app-level local variable, `settings`. - -```js -app.set('title', 'My App') -// use settings.title in a view -``` diff --git a/_includes/api/en/3x/app-param.md b/_includes/api/en/3x/app-param.md deleted file mode 100644 index 72d9fd507b..0000000000 --- a/_includes/api/en/3x/app-param.md +++ /dev/null @@ -1,70 +0,0 @@ -

app.param([name], callback)

- -Map logic to route parameters. For example when `:user` -is present in a route path you may map user loading logic to automatically -provide `req.user` to the route, or perform validations -on the parameter input. - -The following snippet illustrates how the `callback` -is much like middleware, thus supporting async operations, however -providing the additional value of the parameter, here named as `id`. -An attempt to load the user is then performed, assigning `req.user`, -otherwise passing an error to `next(err)`. - -```js -app.param('user', function (req, res, next, id) { - User.find(id, function (err, user) { - if (err) { - next(err) - } else if (user) { - req.user = user - next() - } else { - next(new Error('failed to load user')) - } - }) -}) -``` - -Alternatively you may pass only a `callback`, in which -case you have the opportunity to alter the `app.param()` API. -For example the express-params -defines the following callback which allows you to restrict parameters to a given -regular expression. - -This example is a bit more advanced, checking if the second argument is a regular -expression, returning the callback which acts much like the "user" param example. - -```js -app.param(function (name, fn) { - if (fn instanceof RegExp) { - return function (req, res, next, val) { - var captures - if ((captures = fn.exec(String(val)))) { - req.params[name] = captures - next() - } else { - next('route') - } - } - } -}) -``` - -The method could now be used to effectively validate parameters, or also -parse them to provide capture groups: - -```js -app.param('id', /^\d+$/) - -app.get('/user/:id', function (req, res) { - res.send('user ' + req.params.id) -}) - -app.param('range', /^(\w+)\.\.(\w+)?$/) - -app.get('/range/:range', function (req, res) { - var range = req.params.range - res.send('from ' + range[1] + ' to ' + range[2]) -}) -``` diff --git a/_includes/api/en/3x/app-render.md b/_includes/api/en/3x/app-render.md deleted file mode 100644 index 0b1ced84c8..0000000000 --- a/_includes/api/en/3x/app-render.md +++ /dev/null @@ -1,15 +0,0 @@ -

app.render(view, [options], callback)

- -Render a `view` with a callback responding with -the rendered string. This is the app-level variant of `res.render()`, -and otherwise behaves the same way. - -```js -app.render('email', function (err, html) { - // ... -}) - -app.render('email', { name: 'Tobi' }, function (err, html) { - // ... -}) -``` diff --git a/_includes/api/en/3x/app-routes.md b/_includes/api/en/3x/app-routes.md deleted file mode 100644 index aff28f6967..0000000000 --- a/_includes/api/en/3x/app-routes.md +++ /dev/null @@ -1,29 +0,0 @@ -

app.routes

- -The `app.routes` object houses all of the routes defined mapped -by the associated HTTP verb. This object may be used for introspection capabilities, -for example Express uses this internally not only for routing but to provide default -OPTIONS behaviour unless `app.options()` is used. Your application -or framework may also remove routes by simply by removing them from this object. - -The output of `console.log(app.routes)`: - -``` -{ get: - [ { path: '/', - method: 'get', - callbacks: [Object], - keys: [], - regexp: /^\/\/?$/i }, - { path: '/user/:id', - method: 'get', - callbacks: [Object], - keys: [{ name: 'id', optional: false }], - regexp: /^\/user\/(?:([^\/]+?))\/?$/i } ], - delete: - [ { path: '/user/:id', - method: 'delete', - callbacks: [Object], - keys: [Object], - regexp: /^\/user\/(?:([^\/]+?))\/?$/i } ] } -``` diff --git a/_includes/api/en/3x/app-set.md b/_includes/api/en/3x/app-set.md deleted file mode 100644 index 8991774208..0000000000 --- a/_includes/api/en/3x/app-set.md +++ /dev/null @@ -1,9 +0,0 @@ -

app.set(name, value)

- -Assigns setting `name` to `value`. - -```js -app.set('title', 'My Site') -app.get('title') -// => "My Site" -``` diff --git a/_includes/api/en/3x/app-settings.md b/_includes/api/en/3x/app-settings.md deleted file mode 100644 index 71c7848d1e..0000000000 --- a/_includes/api/en/3x/app-settings.md +++ /dev/null @@ -1,15 +0,0 @@ -

settings

- -The following settings are provided to alter how Express will behave: - -* `env` Environment mode, defaults to process.env.NODE_ENV or "development" -* `trust proxy` Enables reverse proxy support, disabled by default -* `jsonp callback name` Changes the default callback name of ?callback= -* `json replacer` JSON replacer callback, null by default -* `json spaces` JSON response spaces for formatting, defaults to 2 in development, 0 in production -* `case sensitive routing` Enable case sensitivity, disabled by default, treating "/Foo" and "/foo" as the same -* `strict routing` Enable strict routing, by default "/foo" and "/foo/" are treated the same by the router -* `view cache` Enables view template compilation caching, enabled in production by default -* `view engine` The default engine extension to use when omitted -* `views` The view directory path, defaulting to "process.cwd() + '/views'" - diff --git a/_includes/api/en/3x/app-use.md b/_includes/api/en/3x/app-use.md deleted file mode 100644 index ceba45f66c..0000000000 --- a/_includes/api/en/3x/app-use.md +++ /dev/null @@ -1,89 +0,0 @@ -

app.use([path], function)

- -Use the given middleware `function`, with optional mount `path`, -defaulting to "/". - -```js -var express = require('express') -var app = express() - -// simple logger -app.use(function (req, res, next) { - console.log('%s %s', req.method, req.url) - next() -}) - -// respond -app.use(function (req, res, next) { - res.send('Hello World') -}) - -app.listen(3000) -``` - -The "mount" path is stripped and is not visible -to the middleware `function`. The main effect of this feature is that -mounted middleware may operate without code changes regardless of its "prefix" -pathname. - -
-A route will match any path that follows its path immediately with either a "`/`" or a "`.`". For example: `app.use('/apple', ...)` will match _/apple_, _/apple/images_, _/apple/images/news_, _/apple.html_, _/apple.html.txt_, and so on. -
- -Here's a concrete example, take the typical use-case of serving files in ./public -using the `express.static()` middleware: - -```js -// GET /javascripts/jquery.js -// GET /style.css -// GET /favicon.ico -app.use(express.static(path.join(__dirname, 'public'))) -``` - -Say for example you wanted to prefix all static files with "/static", you could -use the "mounting" feature to support this. Mounted middleware functions are _not_ -invoked unless the `req.url` contains this prefix, at which point -it is stripped when the function is invoked. This affects this function only, -subsequent middleware will see `req.url` with "/static" included -unless they are mounted as well. - -```js -// GET /static/javascripts/jquery.js -// GET /static/style.css -// GET /static/favicon.ico -app.use('/static', express.static(path.join(__dirname, 'public'))) -``` - -The order of which middleware are "defined" using `app.use()` is -very important, they are invoked sequentially, thus this defines middleware -precedence. For example usually `express.logger()` is the very -first middleware you would use, logging every request: - -```js -app.use(express.logger()) -app.use(express.static(path.join(__dirname, 'public'))) -app.use(function (req, res) { - res.send('Hello') -}) -``` - -Now suppose you wanted to ignore logging requests for static files, but to -continue logging routes and middleware defined after `logger()`, -you would simply move `static()` above: - -```js -app.use(express.static(path.join(__dirname, 'public'))) -app.use(express.logger()) -app.use(function (req, res) { - res.send('Hello') -}) -``` - -Another concrete example would be serving files from multiple directories, -giving precedence to "./public" over the others: - -```js -app.use(express.static(path.join(__dirname, 'public'))) -app.use(express.static(path.join(__dirname, 'files'))) -app.use(express.static(path.join(__dirname, 'uploads'))) -``` diff --git a/_includes/api/en/3x/app.md b/_includes/api/en/3x/app.md deleted file mode 100644 index 0d15c491a8..0000000000 --- a/_includes/api/en/3x/app.md +++ /dev/null @@ -1,69 +0,0 @@ -

Application

- -
- {% include api/en/3x/app-set.md %} -
- -
- {% include api/en/3x/app-get.md %} -
- -
- {% include api/en/3x/app-enable.md %} -
- -
- {% include api/en/3x/app-disable.md %} -
- -
- {% include api/en/3x/app-enabled.md %} -
- -
- {% include api/en/3x/app-disabled.md %} -
- -
- {% include api/en/3x/app-configure.md %} -
- -
- {% include api/en/3x/app-use.md %} -
- -
- {% include api/en/3x/app-settings.md %} -
- -
- {% include api/en/3x/app-engine.md %} -
- -
- {% include api/en/3x/app-param.md %} -
- -
- {% include api/en/3x/app-VERB.md %} -
- -
- {% include api/en/3x/app-all.md %} -
- -
- {% include api/en/3x/app-locals.md %} -
- -
- {% include api/en/3x/app-render.md %} -
- -
- {% include api/en/3x/app-routes.md %} -
- -
- {% include api/en/3x/app-listen.md %} -
diff --git a/_includes/api/en/3x/express.md b/_includes/api/en/3x/express.md deleted file mode 100644 index 195683b30d..0000000000 --- a/_includes/api/en/3x/express.md +++ /dev/null @@ -1,14 +0,0 @@ -

express()

- -Creates an Express application. The `express()` function is a top-level function exported by the _express_ module. - -```js -var express = require('express') -var app = express() - -app.get('/', function (req, res) { - res.send('hello world') -}) - -app.listen(3000) -``` diff --git a/_includes/api/en/3x/menu.md b/_includes/api/en/3x/menu.md deleted file mode 100644 index 34acd41b14..0000000000 --- a/_includes/api/en/3x/menu.md +++ /dev/null @@ -1,161 +0,0 @@ - diff --git a/_includes/api/en/3x/middleware.md b/_includes/api/en/3x/middleware.md deleted file mode 100644 index 001790acc9..0000000000 --- a/_includes/api/en/3x/middleware.md +++ /dev/null @@ -1,29 +0,0 @@ -

Middleware

- -
- {% include api/en/3x/mw-basicAuth.md %} -
- -
- {% include api/en/3x/mw-bodyParser.md %} -
- -
- {% include api/en/3x/mw-compress.md %} -
- -
- {% include api/en/3x/mw-cookieParser.md %} -
- -
- {% include api/en/3x/mw-cookieSession.md %} -
- -
- {% include api/en/3x/mw-csrf.md %} -
- -
- {% include api/en/3x/mw-directory.md %} -
diff --git a/_includes/api/en/3x/mw-basicAuth.md b/_includes/api/en/3x/mw-basicAuth.md deleted file mode 100644 index b5c2879c6a..0000000000 --- a/_includes/api/en/3x/mw-basicAuth.md +++ /dev/null @@ -1,27 +0,0 @@ -

basicAuth()

- -Basic Authentication middleware, populating `req.user` -with the username. - -Simple username and password: - -```js -app.use(express.basicAuth('username', 'password')) -``` - -Callback verification: - -```js -app.use(express.basicAuth(function (user, pass) { - return user === 'tj' && pass === 'wahoo' -})) -``` - -Async callback verification, accepting `fn(err, user)`, -in this case `req.user` will be the user object passed. - -```js -app.use(express.basicAuth(function (user, pass, fn) { - User.authenticate({ user: user, pass: pass }, fn) -})) -``` diff --git a/_includes/api/en/3x/mw-bodyParser.md b/_includes/api/en/3x/mw-bodyParser.md deleted file mode 100644 index 0052443b17..0000000000 --- a/_includes/api/en/3x/mw-bodyParser.md +++ /dev/null @@ -1,27 +0,0 @@ -

bodyParser()

- -Request body parsing middleware supporting JSON, urlencoded, -and multipart requests. This middleware is simply a wrapper -for the `json()`, `urlencoded()`, and -`multipart()` middleware. - -```js -app.use(express.bodyParser()) - -// is equivalent to: -app.use(express.json()) -app.use(express.urlencoded()) -app.use(express.multipart()) -``` - -For security sake, it's better to disable file upload if your application -doesn't need it. To do this, use only the needed middleware, i.e. don't use -the `bodyParser` and `multipart()` middleware: - -```js -app.use(express.json()) -app.use(express.urlencoded()) -``` - -If your application needs file upload you should set up -a strategy for dealing with those files. diff --git a/_includes/api/en/3x/mw-compress.md b/_includes/api/en/3x/mw-compress.md deleted file mode 100644 index 3221859c02..0000000000 --- a/_includes/api/en/3x/mw-compress.md +++ /dev/null @@ -1,12 +0,0 @@ -

compress()

- -Compress response data with gzip / deflate. This middleware -should be placed "high" within the stack to ensure all -responses may be compressed. - -```js -app.use(express.logger()) -app.use(express.compress()) -app.use(express.methodOverride()) -app.use(express.bodyParser()) -``` diff --git a/_includes/api/en/3x/mw-cookieParser.md b/_includes/api/en/3x/mw-cookieParser.md deleted file mode 100644 index 32b5c28e2e..0000000000 --- a/_includes/api/en/3x/mw-cookieParser.md +++ /dev/null @@ -1,10 +0,0 @@ -

cookieParser()

- -Parses the Cookie header field and populates `req.cookies` -with an object keyed by the cookie names. Optionally you may enabled -signed cookie support by passing a `secret` string. - -```js -app.use(express.cookieParser()) -app.use(express.cookieParser('some secret')) -``` diff --git a/_includes/api/en/3x/mw-cookieSession.md b/_includes/api/en/3x/mw-cookieSession.md deleted file mode 100644 index 5daecf0bfe..0000000000 --- a/_includes/api/en/3x/mw-cookieSession.md +++ /dev/null @@ -1,19 +0,0 @@ -

cookieSession()

- -Provides cookie-based sessions, and populates `req.session`. -This middleware takes the following options: - -* `key` cookie name defaulting to `connect.sess` -* `secret` prevents cookie tampering -* `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` -* `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - -```js -app.use(express.cookieSession()) -``` - -To clear a cookie simply assign the session to null before responding: - -```js -req.session = null -``` diff --git a/_includes/api/en/3x/mw-csrf.md b/_includes/api/en/3x/mw-csrf.md deleted file mode 100644 index beacfe56b2..0000000000 --- a/_includes/api/en/3x/mw-csrf.md +++ /dev/null @@ -1,15 +0,0 @@ -

csrf()

- -CSRF protection middleware. - -By default this middleware generates a token named "_csrf" -which should be added to requests which mutate -state, within a hidden form field, query-string etc. This -token is validated against `req.csrfToken()`. - -The default `value` function checks `req.body` generated -by the `bodyParser()` middleware, `req.query` generated -by `query()`, and the "X-CSRF-Token" header field. - -This middleware requires session support, thus should be added -somewhere below `session()`. diff --git a/_includes/api/en/3x/mw-directory.md b/_includes/api/en/3x/mw-directory.md deleted file mode 100644 index b2e785489d..0000000000 --- a/_includes/api/en/3x/mw-directory.md +++ /dev/null @@ -1,16 +0,0 @@ -

directory()

- -Directory serving middleware, serves the given `path`. -This middleware may be paired with `static()` to serve -files, providing a full-featured file browser. - -```js -app.use(express.directory('public')) -app.use(express.static('public')) -``` - -This middleware accepts the following options: - -* `hidden` display hidden (dot) files. Defaults to false. -* `icons` display icons. Defaults to false. -* `filter` Apply this filter function to files. Defaults to false. diff --git a/_includes/api/en/3x/req-accepted.md b/_includes/api/en/3x/req-accepted.md deleted file mode 100644 index 04d664dafd..0000000000 --- a/_includes/api/en/3x/req-accepted.md +++ /dev/null @@ -1,14 +0,0 @@ -

req.accepted

- -Return an array of Accepted media types ordered from highest quality to lowest. - -``` -[ { value: 'application/json', - quality: 1, - type: 'application', - subtype: 'json' }, - { value: 'text/html', - quality: 0.5, - type: 'text', - subtype: 'html' } ] -``` diff --git a/_includes/api/en/3x/req-acceptedCharsets.md b/_includes/api/en/3x/req-acceptedCharsets.md deleted file mode 100644 index fb4cca0c74..0000000000 --- a/_includes/api/en/3x/req-acceptedCharsets.md +++ /dev/null @@ -1,8 +0,0 @@ -

req.acceptedCharsets

- -Return an array of Accepted charsets ordered from highest quality to lowest. - -``` -Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8 -// => ['unicode-1-1', 'iso-8859-5'] -``` diff --git a/_includes/api/en/3x/req-acceptedLanguages.md b/_includes/api/en/3x/req-acceptedLanguages.md deleted file mode 100644 index 42c5494e89..0000000000 --- a/_includes/api/en/3x/req-acceptedLanguages.md +++ /dev/null @@ -1,8 +0,0 @@ -

req.acceptedLanguages

- -Return an array of Accepted languages ordered from highest quality to lowest. - -``` -Accept-Language: en;q=.5, en-us -// => ['en-us', 'en'] -``` diff --git a/_includes/api/en/3x/req-accepts.md b/_includes/api/en/3x/req-accepts.md deleted file mode 100644 index aac9440ad6..0000000000 --- a/_includes/api/en/3x/req-accepts.md +++ /dev/null @@ -1,36 +0,0 @@ -

req.accepts(types)

- -Check if the given `types` are acceptable, returning -the best match when true, otherwise `undefined` - in which -case you should respond with 406 "Not Acceptable". - -The `type` value may be a single mime type string -such as "application/json", the extension name -such as "json", a comma-delimited list or an array. When a list -or array is given the best match, if any is returned. - -```js -// Accept: text/html -req.accepts('html') -// => "html" - -// Accept: text/*, application/json -req.accepts('html') -// => "html" -req.accepts('text/html') -// => "text/html" -req.accepts('json, text') -// => "json" -req.accepts('application/json') -// => "application/json" - -// Accept: text/*, application/json -req.accepts('image/png') -req.accepts('png') -// => undefined - -// Accept: text/*;q=.5, application/json -req.accepts(['html', 'json']) -req.accepts('html, json') -// => "json" -``` diff --git a/_includes/api/en/3x/req-acceptsCharset.md b/_includes/api/en/3x/req-acceptsCharset.md deleted file mode 100644 index 99e8e16a43..0000000000 --- a/_includes/api/en/3x/req-acceptsCharset.md +++ /dev/null @@ -1,3 +0,0 @@ -

req.acceptsCharset(charset)

- -Check if the given `charset` are acceptable. diff --git a/_includes/api/en/3x/req-acceptsLanguage.md b/_includes/api/en/3x/req-acceptsLanguage.md deleted file mode 100644 index a640dd308e..0000000000 --- a/_includes/api/en/3x/req-acceptsLanguage.md +++ /dev/null @@ -1,3 +0,0 @@ -

req.acceptsLanguage(lang)

- -Check if the given `lang` are acceptable. diff --git a/_includes/api/en/3x/req-body.md b/_includes/api/en/3x/req-body.md deleted file mode 100644 index dfed5c3eff..0000000000 --- a/_includes/api/en/3x/req-body.md +++ /dev/null @@ -1,19 +0,0 @@ -

req.body

- -This property is an object containing the parsed request body. This feature -is provided by the `bodyParser()` middleware, though other body -parsing middleware may follow this convention as well. This property -defaults to `{}` when `bodyParser()` is used. - -```js -// POST user[name]=tobi&user[email]=tobi@learnboost.com -console.log(req.body.user.name) -// => "tobi" - -console.log(req.body.user.email) -// => "tobi@learnboost.com" - -// POST { "name": "tobi" } -console.log(req.body.name) -// => "tobi" -``` diff --git a/_includes/api/en/3x/req-cookies.md b/_includes/api/en/3x/req-cookies.md deleted file mode 100644 index 66ad363ace..0000000000 --- a/_includes/api/en/3x/req-cookies.md +++ /dev/null @@ -1,11 +0,0 @@ -

req.cookies

- -This object requires the `cookieParser()` middleware for use. -It contains cookies sent by the user-agent. If no cookies are sent, it -defaults to `{}`. - -```js -// Cookie: name=tj -console.log(req.cookies.name) -// => "tj" -``` diff --git a/_includes/api/en/3x/req-files.md b/_includes/api/en/3x/req-files.md deleted file mode 100644 index 98331fbd48..0000000000 --- a/_includes/api/en/3x/req-files.md +++ /dev/null @@ -1,45 +0,0 @@ -

req.files

- -This property is an object of the files uploaded. This feature -is provided by the `bodyParser()` middleware, though other body -parsing middleware may follow this convention as well. This property -defaults to `{}` when `bodyParser()` is used. - -For example if a file field was named "image", -and a file was uploaded, `req.files.image` would contain -the following `File` object: - -``` -{ size: 74643, - path: '/tmp/8ef9c52abe857867fd0a4e9a819d1876', - name: 'edge.png', - type: 'image/png', - hash: false, - lastModifiedDate: Thu Aug 09 2012 20:07:51 GMT-0700 (PDT), - _writeStream: - { path: '/tmp/8ef9c52abe857867fd0a4e9a819d1876', - fd: 13, - writable: false, - flags: 'w', - encoding: 'binary', - mode: 438, - bytesWritten: 74643, - busy: false, - _queue: [], - _open: [Function], - drainable: true }, - length: [Getter], - filename: [Getter], - mime: [Getter] } -``` - -The `bodyParser()` middleware utilizes the -node-formidable -module internally, and accepts the same options. An example of this -is the `keepExtensions` formidable option, defaulting to false -which in this case gives you the filename "/tmp/8ef9c52abe857867fd0a4e9a819d1876" void of -the ".png" extension. To enable this, and others you may pass them to `bodyParser()`: - -```js -app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/my/files' })) -``` diff --git a/_includes/api/en/3x/req-fresh.md b/_includes/api/en/3x/req-fresh.md deleted file mode 100644 index 6b4e6e5832..0000000000 --- a/_includes/api/en/3x/req-fresh.md +++ /dev/null @@ -1,9 +0,0 @@ -

req.fresh

- -Check if the request is fresh - aka Last-Modified and/or the ETag still match, -indicating that the resource is "fresh". - -```js -console.dir(req.fresh) -// => true -``` diff --git a/_includes/api/en/3x/req-header.md b/_includes/api/en/3x/req-header.md deleted file mode 100644 index e186dbdcd9..0000000000 --- a/_includes/api/en/3x/req-header.md +++ /dev/null @@ -1,16 +0,0 @@ -

req.get(field)

- -Get the case-insensitive request header `field`. The "Referrer" and "Referer" fields are interchangeable. - -```js -req.get('Content-Type') -// => "text/plain" - -req.get('content-type') -// => "text/plain" - -req.get('Something') -// => undefined -``` - -p Aliased as `req.header(field)`. diff --git a/_includes/api/en/3x/req-host.md b/_includes/api/en/3x/req-host.md deleted file mode 100644 index d24fdfe1c4..0000000000 --- a/_includes/api/en/3x/req-host.md +++ /dev/null @@ -1,9 +0,0 @@ -

req.host

- -Returns the hostname from the "Host" header field (void of portno). - -```js -// Host: "example.com:3000" -console.dir(req.host) -// => 'example.com' -``` diff --git a/_includes/api/en/3x/req-ip.md b/_includes/api/en/3x/req-ip.md deleted file mode 100644 index 1de60fabf3..0000000000 --- a/_includes/api/en/3x/req-ip.md +++ /dev/null @@ -1,9 +0,0 @@ -

req.ip

- -Return the remote address, or when "trust proxy" -is enabled - the upstream address. - -```js -console.dir(req.ip) -// => '127.0.0.1' -``` diff --git a/_includes/api/en/3x/req-ips.md b/_includes/api/en/3x/req-ips.md deleted file mode 100644 index 7b139a29a6..0000000000 --- a/_includes/api/en/3x/req-ips.md +++ /dev/null @@ -1,10 +0,0 @@ -

req.ips

- -When "trust proxy" is `true`, parse -the "X-Forwarded-For" ip address list -and return an array, otherwise an empty -array is returned. - -For example if the value were "client, proxy1, proxy2" -you would receive the array `["client", "proxy1", "proxy2"]` -where "proxy2" is the furthest down-stream. diff --git a/_includes/api/en/3x/req-is.md b/_includes/api/en/3x/req-is.md deleted file mode 100644 index aa93c425cb..0000000000 --- a/_includes/api/en/3x/req-is.md +++ /dev/null @@ -1,21 +0,0 @@ -

req.is(type)

- -Check if the incoming request contains the "Content-Type" -header field, and it matches the give mime `type`. - -```js -// With Content-Type: text/html; charset=utf-8 -req.is('html') -req.is('text/html') -req.is('text/*') -// => true - -// When Content-Type is application/json -req.is('json') -req.is('application/json') -req.is('application/*') -// => true - -req.is('html') -// => false -``` diff --git a/_includes/api/en/3x/req-originalUrl.md b/_includes/api/en/3x/req-originalUrl.md deleted file mode 100644 index d209148d87..0000000000 --- a/_includes/api/en/3x/req-originalUrl.md +++ /dev/null @@ -1,13 +0,0 @@ -

req.originalUrl

- -This property is much like `req.url`, however it retains -the original request url, allowing you to rewrite `req.url` -freely for internal routing purposes. For example the "mounting" feature -of app.use() will rewrite `req.url` to -strip the mount point. - -```js -// GET /search?q=something -console.log(req.originalUrl) -// => "/search?q=something" -``` diff --git a/_includes/api/en/3x/req-param.md b/_includes/api/en/3x/req-param.md deleted file mode 100644 index 5aaa22f80a..0000000000 --- a/_includes/api/en/3x/req-param.md +++ /dev/null @@ -1,27 +0,0 @@ -

req.param(name)

- -Return the value of param `name` when present. - -```js -// ?name=tobi -req.param('name') -// => "tobi" - -// POST name=tobi -req.param('name') -// => "tobi" - -// /user/tobi for /user/:name -req.param('name') -// => "tobi" -``` - -Lookup is performed in the following order: - -* `req.params` -* `req.body` -* `req.query` - -Direct access to `req.body`, `req.params`, -and `req.query` should be favoured for clarity - unless -you truly accept input from each object. diff --git a/_includes/api/en/3x/req-params.md b/_includes/api/en/3x/req-params.md deleted file mode 100644 index 408f8ef8b6..0000000000 --- a/_includes/api/en/3x/req-params.md +++ /dev/null @@ -1,22 +0,0 @@ -

req.params

- -This property is an array containing properties mapped to the named route "parameters". -For example if you have the route `/user/:name`, then the "name" property -is available to you as `req.params.name`. This object defaults to `{}`. - -```js -// GET /user/tj -console.dir(req.params.name) -// => 'tj' -``` - -When a regular expression is used for the route definition, capture groups -are provided in the array using `req.params[N]`, where `N` -is the nth capture group. This rule is applied to unnamed wild-card matches -with string routes such as `/file/*`: - -```js -// GET /file/javascripts/jquery.js -console.dir(req.params[0]) -// => 'javascripts/jquery.js' -``` diff --git a/_includes/api/en/3x/req-path.md b/_includes/api/en/3x/req-path.md deleted file mode 100644 index 52f7ace8e4..0000000000 --- a/_includes/api/en/3x/req-path.md +++ /dev/null @@ -1,9 +0,0 @@ -

req.path

- -Returns the request URL pathname. - -```js -// example.com/users?sort=desc -console.dir(req.path) -// => '/users' -``` diff --git a/_includes/api/en/3x/req-protocol.md b/_includes/api/en/3x/req-protocol.md deleted file mode 100644 index 1090ab51cc..0000000000 --- a/_includes/api/en/3x/req-protocol.md +++ /dev/null @@ -1,13 +0,0 @@ -

req.protocol

- -Return the protocol string "http" or "https" -when requested with TLS. When the "trust proxy" -setting is enabled the "X-Forwarded-Proto" header -field will be trusted. If you're running behind -a reverse proxy that supplies https for you this -may be enabled. - -```js -console.dir(req.protocol) -// => 'http' -``` diff --git a/_includes/api/en/3x/req-query.md b/_includes/api/en/3x/req-query.md deleted file mode 100644 index 17c8a1dda8..0000000000 --- a/_includes/api/en/3x/req-query.md +++ /dev/null @@ -1,20 +0,0 @@ -

req.query

- -This property is an object containing the parsed query-string, -defaulting to `{}`. - -```js -// GET /search?q=tobi+ferret -console.dir(req.query.q) -// => 'tobi ferret' - -// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse -console.dir(req.query.order) -// => 'desc' - -console.dir(req.query.shoe.color) -// => 'blue' - -console.dir(req.query.shoe.type) -// => 'converse' -``` diff --git a/_includes/api/en/3x/req-res.md b/_includes/api/en/3x/req-res.md deleted file mode 100644 index b6f30a3aa0..0000000000 --- a/_includes/api/en/3x/req-res.md +++ /dev/null @@ -1,4 +0,0 @@ -

req.res

- -This property holds a reference to the response object -that relates to this request object. diff --git a/_includes/api/en/3x/req-route.md b/_includes/api/en/3x/req-route.md deleted file mode 100644 index bbb59f2de8..0000000000 --- a/_includes/api/en/3x/req-route.md +++ /dev/null @@ -1,22 +0,0 @@ -

req.route

- -The currently matched `Route` containing -several properties such as the route's original path -string, the regexp generated, and so on. - -```js -app.get('/user/:id?', function (req, res) { - console.dir(req.route) -}) -``` - -Example output from the previous snippet: - -``` -{ path: '/user/:id?', - method: 'get', - callbacks: [ [Function] ], - keys: [ { name: 'id', optional: true } ], - regexp: /^\/user(?:\/([^\/]+?))?\/?$/i, - params: [ id: '12' ] } -``` diff --git a/_includes/api/en/3x/req-secure.md b/_includes/api/en/3x/req-secure.md deleted file mode 100644 index d78bc954a0..0000000000 --- a/_includes/api/en/3x/req-secure.md +++ /dev/null @@ -1,8 +0,0 @@ -

req.secure

- -Check if a TLS connection is established. This is a short-hand for: - -```js -console.dir(req.protocol === 'https') -// => true -``` diff --git a/_includes/api/en/3x/req-signedCookies.md b/_includes/api/en/3x/req-signedCookies.md deleted file mode 100644 index a60f16061a..0000000000 --- a/_includes/api/en/3x/req-signedCookies.md +++ /dev/null @@ -1,15 +0,0 @@ -

req.signedCookies

- -This object requires the `cookieParser(secret)` middleware for use. -It contains signed cookies sent by the user-agent, unsigned and ready for use. -Signed cookies reside in a different object to show developer intent; otherwise, -a malicious attack could be placed on `req.cookie` values (which are easy to spoof). -Note that signing a cookie does not make it "hidden" or encrypted; this simply -prevents tampering (because the secret used to sign is private). If no signed -cookies are sent, it defaults to `{}`. - -```js -// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3 -console.dir(req.signedCookies.user) -// => 'tobi' -``` diff --git a/_includes/api/en/3x/req-stale.md b/_includes/api/en/3x/req-stale.md deleted file mode 100644 index c41d3df8c7..0000000000 --- a/_includes/api/en/3x/req-stale.md +++ /dev/null @@ -1,9 +0,0 @@ -

req.stale

- -Check if the request is stale - aka Last-Modified and/or the ETag do not match, -indicating that the resource is "stale". - -```js -console.dir(req.stale) -// => true -``` diff --git a/_includes/api/en/3x/req-subdomains.md b/_includes/api/en/3x/req-subdomains.md deleted file mode 100644 index 5b405ac6e2..0000000000 --- a/_includes/api/en/3x/req-subdomains.md +++ /dev/null @@ -1,9 +0,0 @@ -

req.subdomains

- -Return subdomains as an array. - -```js -// Host: "tobi.ferrets.example.com" -console.dir(req.subdomains) -// => ['ferrets', 'tobi'] -``` diff --git a/_includes/api/en/3x/req-xhr.md b/_includes/api/en/3x/req-xhr.md deleted file mode 100644 index 05c8a4b30f..0000000000 --- a/_includes/api/en/3x/req-xhr.md +++ /dev/null @@ -1,9 +0,0 @@ -

req.xhr

- -Check if the request was issued with the "X-Requested-With" -header field set to "XMLHttpRequest" (jQuery etc). - -```js -console.dir(req.xhr) -// => true -``` diff --git a/_includes/api/en/3x/req.md b/_includes/api/en/3x/req.md deleted file mode 100644 index 115d5dd721..0000000000 --- a/_includes/api/en/3x/req.md +++ /dev/null @@ -1,116 +0,0 @@ -

Request

- -The `req` object is an enhanced version of Node's own request object -and supports all [built-in fields and methods](https://nodejs.org/api/http.html#http_class_http_incomingmessage). - -
- {% include api/en/3x/req-params.md %} -
- -
- {% include api/en/3x/req-query.md %} -
- -
- {% include api/en/3x/req-body.md %} -
- -
- {% include api/en/3x/req-files.md %} -
- -
- {% include api/en/3x/req-param.md %} -
- -
- {% include api/en/3x/req-route.md %} -
- -
- {% include api/en/3x/req-cookies.md %} -
- -
- {% include api/en/3x/req-signedCookies.md %} -
- -
- {% include api/en/3x/req-header.md %} -
- -
- {% include api/en/3x/req-accepts.md %} -
- -
- {% include api/en/3x/req-accepted.md %} -
- -
- {% include api/en/3x/req-is.md %} -
- -
- {% include api/en/3x/req-ip.md %} -
- -
- {% include api/en/3x/req-ips.md %} -
- -
- {% include api/en/3x/req-path.md %} -
- -
- {% include api/en/3x/req-host.md %} -
- -
- {% include api/en/3x/req-fresh.md %} -
- -
- {% include api/en/3x/req-stale.md %} -
- -
- {% include api/en/3x/req-xhr.md %} -
- -
- {% include api/en/3x/req-protocol.md %} -
- -
- {% include api/en/3x/req-secure.md %} -
- -
- {% include api/en/3x/req-subdomains.md %} -
- -
- {% include api/en/3x/req-originalUrl.md %} -
- -
- {% include api/en/3x/req-acceptedLanguages.md %} -
- -
- {% include api/en/3x/req-acceptedCharsets.md %} -
- -
- {% include api/en/3x/req-acceptsCharset.md %} -
- -
- {% include api/en/3x/req-acceptsLanguage.md %} -
- -
- {% include api/en/3x/req-res.md %} -
diff --git a/_includes/api/en/3x/res-attachment.md b/_includes/api/en/3x/res-attachment.md deleted file mode 100644 index d52e3bba6f..0000000000 --- a/_includes/api/en/3x/res-attachment.md +++ /dev/null @@ -1,15 +0,0 @@ -

res.attachment([filename])

- -Sets the Content-Disposition header field to "attachment". If -a `filename` is given then the Content-Type will be -automatically set based on the extname via `res.type()`, -and the Content-Disposition's "filename=" parameter will be set. - -```js -res.attachment() -// Content-Disposition: attachment - -res.attachment('path/to/logo.png') -// Content-Disposition: attachment; filename="logo.png" -// Content-Type: image/png -``` diff --git a/_includes/api/en/3x/res-charset.md b/_includes/api/en/3x/res-charset.md deleted file mode 100644 index 07d0a35e95..0000000000 --- a/_includes/api/en/3x/res-charset.md +++ /dev/null @@ -1,9 +0,0 @@ -

res.charset

- -Assign the charset. Defaults to "utf-8". - -```js -res.charset = 'value' -res.send('

some html

') -// => Content-Type: text/html; charset=value -``` diff --git a/_includes/api/en/3x/res-clearCookie.md b/_includes/api/en/3x/res-clearCookie.md deleted file mode 100644 index afb139628d..0000000000 --- a/_includes/api/en/3x/res-clearCookie.md +++ /dev/null @@ -1,8 +0,0 @@ -

res.clearCookie(name, [options])

- -Clear cookie `name`. The `path` option defaults to "/". - -```js -res.cookie('name', 'tobi', { path: '/admin' }) -res.clearCookie('name', { path: '/admin' }) -``` diff --git a/_includes/api/en/3x/res-cookie.md b/_includes/api/en/3x/res-cookie.md deleted file mode 100644 index 5f6eb0186c..0000000000 --- a/_includes/api/en/3x/res-cookie.md +++ /dev/null @@ -1,37 +0,0 @@ -

res.cookie(name, value, [options])

- -Set cookie `name` to `value`, which may be a string or object converted to JSON. The `path` -option defaults to "/". - -```js -res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true }) -res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }) -``` - -The `maxAge` option is a convenience option for setting "expires" -relative to the current time in milliseconds. The following is equivalent to -the previous example. - -```js -res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) -``` - -An object may be passed which is then serialized as JSON, which is -automatically parsed by the `bodyParser()` middleware. - -```js -res.cookie('cart', { items: [1, 2, 3] }) -res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 }) -``` - -Signed cookies are also supported through this method. Simply -pass the `signed` option. When given `res.cookie()` -will use the secret passed to `express.cookieParser(secret)` -to sign the value. - -```js -res.cookie('name', 'tobi', { signed: true }) -``` - -Later you may access this value through the req.signedCookie -object. diff --git a/_includes/api/en/3x/res-download.md b/_includes/api/en/3x/res-download.md deleted file mode 100644 index 43d48f769d..0000000000 --- a/_includes/api/en/3x/res-download.md +++ /dev/null @@ -1,26 +0,0 @@ -

res.download(path, [filename], [fn])

- -Transfer the file at `path` as an "attachment", -typically browsers will prompt the user for download. The -Content-Disposition "filename=" parameter, aka the one -that will appear in the brower dialog is set to `path` -by default, however you may provide an override `filename`. - -When an error has ocurred or transfer is complete the optional -callback `fn` is invoked. This method uses res.sendfile() -to transfer the file. - -```js -res.download('/report-12345.pdf') - -res.download('/report-12345.pdf', 'report.pdf') - -res.download('/report-12345.pdf', 'report.pdf', function (err) { - if (err) { - // handle error, keep in mind the response may be partially-sent - // so check res.headerSent - } else { - // decrement a download credit etc - } -}) -``` diff --git a/_includes/api/en/3x/res-format.md b/_includes/api/en/3x/res-format.md deleted file mode 100644 index 5092c626a1..0000000000 --- a/_includes/api/en/3x/res-format.md +++ /dev/null @@ -1,52 +0,0 @@ -

res.format(object)

- -Performs content-negotiation on the request Accept header -field when present. This method uses `req.accepted`, an array of -acceptable types ordered by their quality values, otherwise the -first callback is invoked. When no match is performed the server -responds with 406 "Not Acceptable", or invokes the `default` -callback. - -The Content-Type is set for you when a callback is selected, -however you may alter this within the callback using `res.set()` -or `res.type()` etcetera. - -The following example would respond with `{ "message": "hey" }` -when the Accept header field is set to "application/json" or "*/json", -however if "*/*" is given then "hey" will be the response. - -```js -res.format({ - 'text/plain': function () { - res.send('hey') - }, - - 'text/html': function () { - res.send('

hey

') - }, - - 'application/json': function () { - res.send({ message: 'hey' }) - } -}) -``` - -In addition to canonicalized MIME types you may also -use extnames mapped to these types, providing a slightly -less verbose implementation: - -```js -res.format({ - text: function () { - res.send('hey') - }, - - html: function () { - res.send('

hey

') - }, - - json: function () { - res.send({ message: 'hey' }) - } -}) -``` diff --git a/_includes/api/en/3x/res-get.md b/_includes/api/en/3x/res-get.md deleted file mode 100644 index 2dbf992020..0000000000 --- a/_includes/api/en/3x/res-get.md +++ /dev/null @@ -1,8 +0,0 @@ -

res.get(field)

- -Get the case-insensitive response header `field`. - -```js -res.get('Content-Type') -// => "text/plain" -``` diff --git a/_includes/api/en/3x/res-json.md b/_includes/api/en/3x/res-json.md deleted file mode 100644 index d13bb2ab0b..0000000000 --- a/_includes/api/en/3x/res-json.md +++ /dev/null @@ -1,13 +0,0 @@ -

res.json([status|body], [body])

- -Send a JSON response. This method is identical -to `res.send()` when an object or -array is passed, however it may be used for -explicit JSON conversion of non-objects (null, undefined, etc), -though these are technically not valid JSON. - -```js -res.json(null) -res.json({ user: 'tobi' }) -res.json(500, { error: 'message' }) -``` diff --git a/_includes/api/en/3x/res-jsonp.md b/_includes/api/en/3x/res-jsonp.md deleted file mode 100644 index 5340c4487d..0000000000 --- a/_includes/api/en/3x/res-jsonp.md +++ /dev/null @@ -1,33 +0,0 @@ -

res.jsonp([status|body], [body])

- -Send a JSON response with JSONP support. This method is identical -to `res.json()` however opts-in to JSONP callback -support. - -```js -res.jsonp(null) -// => null - -res.jsonp({ user: 'tobi' }) -// => { "user": "tobi" } - -res.jsonp(500, { error: 'message' }) -// => { "error": "message" } -``` - -By default the JSONP callback name is simply `callback`, -however you may alter this with the jsonp callback name -setting. The following are some examples of JSONP responses using the same -code: - -```js -// ?callback=foo -res.jsonp({ user: 'tobi' }) -// => foo({ "user": "tobi" }) - -app.set('jsonp callback name', 'cb') - -// ?cb=foo -res.jsonp(500, { error: 'message' }) -// => foo({ "error": "message" }) -``` diff --git a/_includes/api/en/3x/res-links.md b/_includes/api/en/3x/res-links.md deleted file mode 100644 index 2b8c734b24..0000000000 --- a/_includes/api/en/3x/res-links.md +++ /dev/null @@ -1,17 +0,0 @@ - - -Join the given `links` to populate the "Link" response header field. - -```js -res.links({ - next: 'http://api.example.com/users?page=2', - last: 'http://api.example.com/users?page=5' -}) -``` - -p yields: - -``` -Link: rel="next", - rel="last" -``` diff --git a/_includes/api/en/3x/res-locals.md b/_includes/api/en/3x/res-locals.md deleted file mode 100644 index 5c6dbfbf95..0000000000 --- a/_includes/api/en/3x/res-locals.md +++ /dev/null @@ -1,16 +0,0 @@ -

res.locals

- -Response local variables are scoped to the request, thus only -available to the view(s) rendered during that request / response -cycle, if any. Otherwise this API is identical to app.locals. - -This object is useful for exposing request-level information such as the -request pathname, authenticated user, user settings etcetera. - -```js -app.use(function (req, res, next) { - res.locals.user = req.user - res.locals.authenticated = !req.user.anonymous - next() -}) -``` diff --git a/_includes/api/en/3x/res-location.md b/_includes/api/en/3x/res-location.md deleted file mode 100644 index 60b59db930..0000000000 --- a/_includes/api/en/3x/res-location.md +++ /dev/null @@ -1,21 +0,0 @@ -

res.location

- -Set the location header. - -```js -res.location('/foo/bar') -res.location('foo/bar') -res.location('http://example.com') -res.location('../login') -res.location('back') -``` - -You can use the same kind of `urls` as in `res.redirect()`. - -For example, if your application is mounted at `/blog`, -the following would set the `location` header to -`/blog/admin`: - -```js -res.location('admin') -``` diff --git a/_includes/api/en/3x/res-redirect.md b/_includes/api/en/3x/res-redirect.md deleted file mode 100644 index dc87d689c2..0000000000 --- a/_includes/api/en/3x/res-redirect.md +++ /dev/null @@ -1,51 +0,0 @@ -

res.redirect([status], url)

- -Redirect to the given `url` with optional `status` code -defaulting to 302 "Found". - -```js -res.redirect('/foo/bar') -res.redirect('http://example.com') -res.redirect(301, 'http://example.com') -res.redirect('../login') -``` - -Express supports a few forms of redirection, first being -a fully qualified URI for redirecting to a different site: - -```js -res.redirect('http://google.com') -``` - -The second form is the pathname-relative redirect, for example -if you were on `http://example.com/admin/post/new`, the -following redirect to `/admin` would land you at `http://example.com/admin`: - -```js -res.redirect('/admin') -``` - -This next redirect is relative to the `mount` point of the application. For example -if you have a blog application mounted at `/blog`, ideally it has no knowledge of -where it was mounted, so where a redirect of `/admin/post/new` would simply give you -`http://example.com/admin/post/new`, the following mount-relative redirect would give -you `http://example.com/blog/admin/post/new`: - -```js -res.redirect('admin/post/new') -``` - -Pathname relative redirects are also possible. If you were -on `http://example.com/admin/post/new`, the following redirect -would land you at `http//example.com/admin/post`: - -```js -res.redirect('..') -``` - -The final special-case is a `back` redirect, redirecting back to -the Referer (or Referrer), defaulting to `/` when missing. - -```js -res.redirect('back') -``` diff --git a/_includes/api/en/3x/res-render.md b/_includes/api/en/3x/res-render.md deleted file mode 100644 index e87cba9f3e..0000000000 --- a/_includes/api/en/3x/res-render.md +++ /dev/null @@ -1,16 +0,0 @@ -

res.render(view, [locals], callback)

- -Render a `view` with a callback responding with -the rendered string. When an error occurs `next(err)` -is invoked internally. When a callback is provided both the possible error -and rendered string are passed, and no automated response is performed. - -```js -res.render('index', function (err, html) { - // ... -}) - -res.render('user', { name: 'Tobi' }, function (err, html) { - // ... -}) -``` diff --git a/_includes/api/en/3x/res-req.md b/_includes/api/en/3x/res-req.md deleted file mode 100644 index 6c0236cdc1..0000000000 --- a/_includes/api/en/3x/res-req.md +++ /dev/null @@ -1,4 +0,0 @@ -

res.req

- -This property holds a reference to the request object -that relates to this response object. diff --git a/_includes/api/en/3x/res-send.md b/_includes/api/en/3x/res-send.md deleted file mode 100644 index 75903b13cb..0000000000 --- a/_includes/api/en/3x/res-send.md +++ /dev/null @@ -1,53 +0,0 @@ -

res.send([body|status], [body])

- -Send a response. - -```js -res.send(Buffer.from('whoop')) -res.send({ some: 'json' }) -res.send('

some html

') -res.send(404, 'Sorry, we cannot find that!') -res.send(500, { error: 'something blew up' }) -res.send(200) -``` - -This method performs a myriad of -useful tasks for simple non-streaming responses such -as automatically assigning the Content-Length unless -previously defined and providing automatic HEAD and -HTTP cache freshness support. - -When a `Buffer` is given -the Content-Type is set to "application/octet-stream" -unless previously defined as shown below: - -```js -res.set('Content-Type', 'text/html') -res.send(Buffer.from('

some html

')) -``` - -When a `String` is given the -Content-Type is set defaulted to "text/html": - -```js -res.send('

some html

') -``` - -When an `Array` or `Object` is -given Express will respond with the JSON representation: - -```js -res.send({ user: 'tobi' }) -res.send([1, 2, 3]) -``` - -Finally when a `Number` is given without -any of the previously mentioned bodies, then a response -body string is assigned for you. For example 200 will -respond will the text "OK", and 404 "Not Found" and so on. - -```js -res.send(200) -res.send(404) -res.send(500) -``` diff --git a/_includes/api/en/3x/res-sendfile.md b/_includes/api/en/3x/res-sendfile.md deleted file mode 100644 index 0580a98b48..0000000000 --- a/_includes/api/en/3x/res-sendfile.md +++ /dev/null @@ -1,30 +0,0 @@ -

res.sendfile(path, [options], [fn]])

- -Transfer the file at the given `path`. - -Automatically defaults the Content-Type response header field based -on the filename's extension. The callback `fn(err)` is -invoked when the transfer is complete or when an error occurs. - -Options: - -* `maxAge` in milliseconds defaulting to 0 -* `root` root directory for relative filenames - -This method provides fine-grained support for file serving -as illustrated in the following example: - -```js -app.get('/user/:uid/photos/:file', function (req, res) { - var uid = req.params.uid - var 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.') - } - }) -}) -``` diff --git a/_includes/api/en/3x/res-set.md b/_includes/api/en/3x/res-set.md deleted file mode 100644 index 76ca5086b1..0000000000 --- a/_includes/api/en/3x/res-set.md +++ /dev/null @@ -1,15 +0,0 @@ -

res.set(field, [value])

- -Set header `field` to `value`, or pass an object to set multiple fields at once. - -```js -res.set('Content-Type', 'text/plain') - -res.set({ - 'Content-Type': 'text/plain', - 'Content-Length': '123', - ETag: '12345' -}) -``` - -Aliased as `res.header(field, [value])`. diff --git a/_includes/api/en/3x/res-status.md b/_includes/api/en/3x/res-status.md deleted file mode 100644 index 3be23e5138..0000000000 --- a/_includes/api/en/3x/res-status.md +++ /dev/null @@ -1,7 +0,0 @@ -

res.status(code)

- -Chainable alias of node's `res.statusCode=`. - -```js -res.status(404).sendfile('path/to/404.png') -``` diff --git a/_includes/api/en/3x/res-type.md b/_includes/api/en/3x/res-type.md deleted file mode 100644 index d686d65105..0000000000 --- a/_includes/api/en/3x/res-type.md +++ /dev/null @@ -1,15 +0,0 @@ -

res.type(type)

- -Sets the Content-Type to the mime lookup of `type`, -or when "/" is present the Content-Type is simply set to this -literal value. - -```js -res.type('.html') -res.type('html') -res.type('json') -res.type('application/json') -res.type('png') -``` - -p Aliased as `res.contentType(type)`. diff --git a/_includes/api/en/3x/res.md b/_includes/api/en/3x/res.md deleted file mode 100644 index b56f9fb7d6..0000000000 --- a/_includes/api/en/3x/res.md +++ /dev/null @@ -1,84 +0,0 @@ -

Response

- -The `res` object is an enhanced version of Node's own response object -and supports all [built-in fields and methods](https://nodejs.org/api/http.html#http_class_http_serverresponse). - -
- {% include api/en/3x/res-status.md %} -
- -
- {% include api/en/3x/res-set.md %} -
- -
- {% include api/en/3x/res-get.md %} -
- -
- {% include api/en/3x/res-cookie.md %} -
- -
- {% include api/en/3x/res-clearCookie.md %} -
- -
- {% include api/en/3x/res-redirect.md %} -
- -
- {% include api/en/3x/res-location.md %} -
- -
- {% include api/en/3x/res-charset.md %} -
- -
- {% include api/en/3x/res-send.md %} -
- -
- {% include api/en/3x/res-json.md %} -
- -
- {% include api/en/3x/res-jsonp.md %} -
- -
- {% include api/en/3x/res-type.md %} -
- -
- {% include api/en/3x/res-format.md %} -
- -
- {% include api/en/3x/res-attachment.md %} -
- -
- {% include api/en/3x/res-sendfile.md %} -
- -
- {% include api/en/3x/res-download.md %} -
- -
- {% include api/en/3x/res-links.md %} -
- -
- {% include api/en/3x/res-locals.md %} -
- -
- {% include api/en/3x/res-render.md %} -
- -
- {% include api/en/3x/res-req.md %} -
diff --git a/_includes/api/en/4x/app-METHOD.md b/_includes/api/en/4x/app-METHOD.md deleted file mode 100644 index 94c82a246f..0000000000 --- a/_includes/api/en/4x/app-METHOD.md +++ /dev/null @@ -1,62 +0,0 @@ -

app.METHOD(path, callback [, callback ...])

- -Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET, -PUT, POST, and so on, in lowercase. Thus, the actual methods are `app.get()`, -`app.post()`, `app.put()`, and so on. See [Routing methods](#routing-methods) below for the complete list. - -{% include api/en/4x/routing-args.html %} - -#### Routing methods - -Express supports the following routing methods corresponding to the HTTP methods of the same names: - - - - - - - -
-* `checkout` -* `copy` -* `delete` -* `get` -* `head` -* `lock` -* `merge` -* `mkactivity` - -* `mkcol` -* `move` -* `m-search` -* `notify` -* `options` -* `patch` -* `post` - -* `purge` -* `put` -* `report` -* `search` -* `subscribe` -* `trace` -* `unlock` -* `unsubscribe` -
- -The API documentation has explicit entries only for the most popular HTTP methods `app.get()`, -`app.post()`, `app.put()`, and `app.delete()`. -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 ...`. - -
- The `app.get()` function is automatically called for the HTTP `HEAD` method in addition to the `GET` - method if `app.head()` was not called for the path before `app.get()`. -
- -The method, `app.all()`, is not derived from any HTTP method and loads middleware at -the specified path for _all_ HTTP request methods. -For more information, see [app.all](#app.all). - -For more information on routing, see the [routing guide](/{{page.lang}}/guide/routing.html). diff --git a/_includes/api/en/4x/app-all.md b/_includes/api/en/4x/app-all.md deleted file mode 100644 index 2939bd6f07..0000000000 --- a/_includes/api/en/4x/app-all.md +++ /dev/null @@ -1,44 +0,0 @@ -

app.all(path, callback [, callback ...])

- -This method is like the standard [app.METHOD()](#app.METHOD) methods, -except it matches all HTTP verbs. - -{% include api/en/4x/routing-args.html %} - -#### Examples - -The following callback is executed for requests to `/secret` whether using -GET, POST, PUT, DELETE, or any other HTTP request method: - -```js -app.all('/secret', function (req, res, next) { - console.log('Accessing the secret section ...') - next() // pass control to the next handler -}) -``` - -The `app.all()` method is useful for mapping "global" logic for specific path prefixes or arbitrary matches. For example, if you put the following at the top of all other -route definitions, it requires that all routes from that point on -require authentication, and automatically load a user. Keep in mind -that these callbacks do not have to act as end-points: `loadUser` -can perform a task, then call `next()` to continue matching subsequent -routes. - -```js -app.all('*', requireAuthentication, loadUser) -``` - -Or the equivalent: - -```js -app.all('*', requireAuthentication) -app.all('*', loadUser) -``` - -Another example is white-listed "global" functionality. -The example is similar to the ones above, but it only restricts paths that start with -"/api": - -```js -app.all('/api/*', requireAuthentication) -``` diff --git a/_includes/api/en/4x/app-delete-method.md b/_includes/api/en/4x/app-delete-method.md deleted file mode 100644 index 0d9e5cbcc0..0000000000 --- a/_includes/api/en/4x/app-delete-method.md +++ /dev/null @@ -1,14 +0,0 @@ -

app.delete(path, callback [, callback ...])

- -Routes HTTP DELETE requests to the specified path with the specified callback functions. -For more information, see the [routing guide](/{{page.lang}}/guide/routing.html). - -{% include api/en/4x/routing-args.html %} - -#### Example - -```js -app.delete('/', function (req, res) { - res.send('DELETE request to homepage') -}) -``` diff --git a/_includes/api/en/4x/app-disable.md b/_includes/api/en/4x/app-disable.md deleted file mode 100644 index 08bbcf11ba..0000000000 --- a/_includes/api/en/4x/app-disable.md +++ /dev/null @@ -1,12 +0,0 @@ -

app.disable(name)

- -Sets the Boolean setting `name` to `false`, where `name` is one of the properties from the [app settings table](#app.settings.table). -Calling `app.set('foo', false)` for a Boolean property is the same as calling `app.disable('foo')`. - -For example: - -```js -app.disable('trust proxy') -app.get('trust proxy') -// => false -``` diff --git a/_includes/api/en/4x/app-disabled.md b/_includes/api/en/4x/app-disabled.md deleted file mode 100644 index 370048fde6..0000000000 --- a/_includes/api/en/4x/app-disabled.md +++ /dev/null @@ -1,13 +0,0 @@ -

app.disabled(name)

- -Returns `true` if the Boolean setting `name` is disabled (`false`), where `name` is one of the properties from -the [app settings table](#app.settings.table). - -```js -app.disabled('trust proxy') -// => true - -app.enable('trust proxy') -app.disabled('trust proxy') -// => false -``` diff --git a/_includes/api/en/4x/app-enable.md b/_includes/api/en/4x/app-enable.md deleted file mode 100644 index 1152335a4c..0000000000 --- a/_includes/api/en/4x/app-enable.md +++ /dev/null @@ -1,10 +0,0 @@ -

app.enable(name)

- -Sets the Boolean setting `name` to `true`, where `name` is one of the properties from the [app settings table](#app.settings.table). -Calling `app.set('foo', true)` for a Boolean property is the same as calling `app.enable('foo')`. - -```js -app.enable('trust proxy') -app.get('trust proxy') -// => true -``` diff --git a/_includes/api/en/4x/app-enabled.md b/_includes/api/en/4x/app-enabled.md deleted file mode 100644 index ad9b17aa89..0000000000 --- a/_includes/api/en/4x/app-enabled.md +++ /dev/null @@ -1,13 +0,0 @@ -

app.enabled(name)

- -Returns `true` if the setting `name` is enabled (`true`), where `name` is one of the -properties from the [app settings table](#app.settings.table). - -```js -app.enabled('trust proxy') -// => false - -app.enable('trust proxy') -app.enabled('trust proxy') -// => true -``` diff --git a/_includes/api/en/4x/app-engine.md b/_includes/api/en/4x/app-engine.md deleted file mode 100644 index 4906a254f1..0000000000 --- a/_includes/api/en/4x/app-engine.md +++ /dev/null @@ -1,36 +0,0 @@ -

app.engine(ext, callback)

- -Registers the given template engine `callback` as `ext`. - -By default, Express will `require()` the engine based on the file extension. -For example, if you try to render a "foo.pug" file, Express invokes the -following internally, and caches the `require()` on subsequent calls to increase -performance. - -```js -app.engine('pug', require('pug').__express) -``` - -Use this method for engines that do not provide `.__express` out of the box, -or if you wish to "map" a different extension to the template engine. - -For example, to map the EJS template engine to ".html" files: - -```js -app.engine('html', require('ejs').renderFile) -``` - -In this case, EJS provides a `.renderFile()` method with -the same signature that Express expects: `(path, options, callback)`, -though note that it aliases this method as `ejs.__express` internally -so if you're using ".ejs" extensions you don't need to do anything. - -Some template engines do not follow this convention. The -[consolidate.js](https://github.com/tj/consolidate.js) library maps Node template engines to follow this convention, -so they work seamlessly with Express. - -```js -var engines = require('consolidate') -app.engine('haml', engines.haml) -app.engine('html', engines.hogan) -``` diff --git a/_includes/api/en/4x/app-get-method.md b/_includes/api/en/4x/app-get-method.md deleted file mode 100644 index 37c61c342c..0000000000 --- a/_includes/api/en/4x/app-get-method.md +++ /dev/null @@ -1,15 +0,0 @@ -

app.get(path, callback [, callback ...])

- -Routes HTTP GET requests to the specified path with the specified callback functions. - -{% include api/en/4x/routing-args.html %} - -For more information, see the [routing guide](/{{page.lang}}/guide/routing.html). - -#### Example - -```js -app.get('/', function (req, res) { - res.send('GET request to homepage') -}) -``` diff --git a/_includes/api/en/4x/app-get.md b/_includes/api/en/4x/app-get.md deleted file mode 100644 index c93ef34d70..0000000000 --- a/_includes/api/en/4x/app-get.md +++ /dev/null @@ -1,13 +0,0 @@ -

app.get(name)

- -Returns the value of `name` app setting, where `name` is one of the strings in the -[app settings table](#app.settings.table). For example: - -```js -app.get('title') -// => undefined - -app.set('title', 'My Site') -app.get('title') -// => "My Site" -``` diff --git a/_includes/api/en/4x/app-listen.md b/_includes/api/en/4x/app-listen.md deleted file mode 100644 index 26bde4121b..0000000000 --- a/_includes/api/en/4x/app-listen.md +++ /dev/null @@ -1,53 +0,0 @@ -

app.listen(path, [callback])

- -Starts a UNIX socket and listens for connections on the given path. -This method is identical to Node's [http.Server.listen()](https://nodejs.org/api/http.html#http_server_listen). - -```js -var express = require('express') -var app = express() -app.listen('/tmp/sock') -``` - -

app.listen([port[, host[, backlog]]][, callback])

- -Binds and listens for connections on the specified host and port. -This method is identical to Node's [http.Server.listen()](https://nodejs.org/api/http.html#http_server_listen). - -If port is omitted or is 0, the operating system will assign an arbitrary unused -port, which is useful for cases like automated tasks (tests, etc.). - -```js -var express = require('express') -var app = express() -app.listen(3000) -``` - -The `app` returned by `express()` is in fact a JavaScript -`Function`, designed to be passed to Node's HTTP servers as a callback -to handle requests. This makes it easy to provide both HTTP and HTTPS versions of -your app with the same code base, as the app does not inherit from these -(it is simply a callback): - -```js -var express = require('express') -var https = require('https') -var http = require('http') -var app = express() - -http.createServer(app).listen(80) -https.createServer(options, app).listen(443) -``` - -The `app.listen()` method returns an [http.Server](https://nodejs.org/api/http.html#http_class_http_server) object and (for HTTP) is a convenience method for the following: - -```js -app.listen = function () { - var server = http.createServer(this) - return server.listen.apply(server, arguments) -} -``` - -{% include admonitions/note.html content="All the forms of Node's -[http.Server.listen()](https://nodejs.org/api/http.html#http_server_listen) -method are in fact actually supported." %} diff --git a/_includes/api/en/4x/app-locals.md b/_includes/api/en/4x/app-locals.md deleted file mode 100644 index 178d640054..0000000000 --- a/_includes/api/en/4x/app-locals.md +++ /dev/null @@ -1,34 +0,0 @@ -

app.locals

- -The `app.locals` object has properties that are local variables within the application, -and will be available in templates rendered with [res.render](#res.render). - -
-The `locals` object is used by view engines to render a response. The object -keys may be particularly sensitive and should not contain user-controlled -input, as it may affect the operation of the view engine or provide a path to -cross-site scripting. Consult the documentation for the used view engine for -additional considerations. -
- -```js -console.dir(app.locals.title) -// => 'My App' - -console.dir(app.locals.email) -// => 'me@myapp.com' -``` - -Once set, the value of `app.locals` properties persist throughout the life of the application, -in contrast with [res.locals](#res.locals) properties that -are valid only for the lifetime of the request. - -You can access local variables in templates rendered within the application. -This is useful for providing helper functions to templates, as well as application-level data. -Local variables are available in middleware via `req.app.locals` (see [req.app](#req.app)) - -```js -app.locals.title = 'My App' -app.locals.strftime = require('strftime') -app.locals.email = 'me@myapp.com' -``` diff --git a/_includes/api/en/4x/app-mountpath.md b/_includes/api/en/4x/app-mountpath.md deleted file mode 100644 index 2ccdd57202..0000000000 --- a/_includes/api/en/4x/app-mountpath.md +++ /dev/null @@ -1,45 +0,0 @@ -

app.mountpath

- -The `app.mountpath` property contains one or more path patterns on which a sub-app was mounted. - -
- A sub-app is an instance of `express` that may be used for handling the request to a route. -
- -```js -var express = require('express') - -var app = express() // the main app -var admin = express() // the sub app - -admin.get('/', function (req, res) { - console.log(admin.mountpath) // /admin - res.send('Admin Homepage') -}) - -app.use('/admin', admin) // mount the sub app -``` - -It is similar to the [baseUrl](#req.baseUrl) property of the `req` object, except `req.baseUrl` -returns the matched URL path, instead of the matched patterns. - -If a sub-app is mounted on multiple path patterns, `app.mountpath` returns the list of -patterns it is mounted on, as shown in the following example. - -```js -var admin = express() - -admin.get('/', function (req, res) { - console.dir(admin.mountpath) // [ '/adm*n', '/manager' ] - res.send('Admin Homepage') -}) - -var secret = express() -secret.get('/', function (req, res) { - console.log(secret.mountpath) // /secr*t - res.send('Admin Secret') -}) - -admin.use('/secr*t', secret) // load the 'secret' router on '/secr*t', on the 'admin' sub app -app.use(['/adm*n', '/manager'], admin) // load the 'admin' router on '/adm*n' and '/manager', on the parent app -``` diff --git a/_includes/api/en/4x/app-onmount.md b/_includes/api/en/4x/app-onmount.md deleted file mode 100644 index 8275cf19b3..0000000000 --- a/_includes/api/en/4x/app-onmount.md +++ /dev/null @@ -1,29 +0,0 @@ -

app.on('mount', callback(parent))

- -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: - -* 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. - -For details, see [Application settings](/en/4x/api.html#app.settings.table). -
- -```js -var admin = express() - -admin.on('mount', function (parent) { - console.log('Admin Mounted') - console.log(parent) // refers to the parent app -}) - -admin.get('/', function (req, res) { - res.send('Admin Homepage') -}) - -app.use('/admin', admin) -``` diff --git a/_includes/api/en/4x/app-param.md b/_includes/api/en/4x/app-param.md deleted file mode 100644 index 2b0d8bf2aa..0000000000 --- a/_includes/api/en/4x/app-param.md +++ /dev/null @@ -1,154 +0,0 @@ -

app.param([name], callback)

- -Add callback triggers to [route parameters](/{{ page.lang }}/guide/routing.html#route-parameters), where `name` is the name of the parameter or an array of them, and `callback` is the callback function. The parameters of the callback function are the request object, the response object, the next middleware, the value of the parameter and the name of the parameter, in that order. - -If `name` is an array, the `callback` trigger is registered for each parameter declared in it, in the order in which they are declared. Furthermore, for each declared parameter except the last one, a call to `next` inside the callback will call the callback for the next declared parameter. For the last parameter, a call to `next` will call the next middleware in place for the route currently being processed, just like it would if `name` were just a string. - -For example, when `:user` is present in a route path, you may map user loading logic to automatically provide `req.user` to the route, or perform validations on the parameter input. - -```js -app.param('user', function (req, res, next, id) { - // try to get the user details from the User model and attach it to the request object - User.find(id, function (err, user) { - if (err) { - next(err) - } else if (user) { - req.user = user - next() - } else { - next(new Error('failed to load user')) - } - }) -}) -``` - -Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers, nor are they triggered for route parameters inherited from parent routers. Hence, param callbacks defined on `app` will be triggered only by route parameters defined on `app` routes. - -All param callbacks will be called before any handler of any route in which the param occurs, and they will each be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples. - -```js -app.param('id', function (req, res, next, id) { - console.log('CALLED ONLY ONCE') - next() -}) - -app.get('/user/:id', function (req, res, next) { - console.log('although this matches') - next() -}) - -app.get('/user/:id', function (req, res) { - console.log('and this matches too') - res.end() -}) -``` - -On `GET /user/42`, the following is printed: - -``` -CALLED ONLY ONCE -although this matches -and this matches too -``` - -```js -app.param(['id', 'page'], function (req, res, next, value) { - console.log('CALLED ONLY ONCE with', value) - next() -}) - -app.get('/user/:id/:page', function (req, res, next) { - console.log('although this matches') - next() -}) - -app.get('/user/:id/:page', function (req, res) { - console.log('and this matches too') - res.end() -}) -``` - -On `GET /user/42/3`, the following is printed: - -``` -CALLED ONLY ONCE with 42 -CALLED ONLY ONCE with 3 -although this matches -and this matches too -``` - -
-The following section describes `app.param(callback)`, which is deprecated as of v4.11.0. -
- -The behavior of the `app.param(name, callback)` method can be altered entirely by passing only a function to `app.param()`. This function is a custom implementation of how `app.param(name, callback)` should behave - it accepts two parameters and must return a middleware. - -The first parameter of this function is the name of the URL parameter that should be captured, the second parameter can be any JavaScript object which might be used for returning the middleware implementation. - -The middleware returned by the function decides the behavior of what happens when a URL parameter is captured. - -In this example, the `app.param(name, callback)` signature is modified to `app.param(name, accessId)`. Instead of accepting a name and a callback, `app.param()` will now accept a name and a number. - -```js -var express = require('express') -var app = express() - -// customizing the behavior of app.param() -app.param(function (param, option) { - return function (req, res, next, val) { - if (val === option) { - next() - } else { - next('route') - } - } -}) - -// using the customized app.param() -app.param('id', 1337) - -// route to trigger the capture -app.get('/user/:id', function (req, res) { - res.send('OK') -}) - -app.listen(3000, function () { - console.log('Ready') -}) -``` - -In this example, the `app.param(name, callback)` signature remains the same, but instead of a middleware callback, a custom data type checking function has been defined to validate the data type of the user id. - -```js -app.param(function (param, validator) { - return function (req, res, next, val) { - if (validator(val)) { - next() - } else { - next('route') - } - } -}) - -app.param('id', function (candidate) { - return !isNaN(parseFloat(candidate)) && isFinite(candidate) -}) -``` - -
-The '`.`' character can't be used to capture a character in your capturing regexp. For example you can't use `'/user-.+/'` to capture `'users-gami'`, use `[\\s\\S]` or `[\\w\\W]` instead (as in `'/user-[\\s\\S]+/'`. - -Examples: - -```js -// captures '1-a_6' but not '543-azser-sder' -router.get('/[0-9]+-[[\\w]]*', function (req, res, next) { next() }) - -// captures '1-a_6' and '543-az(ser"-sder' but not '5-a s' -router.get('/[0-9]+-[[\\S]]*', function (req, res, next) { next() }) - -// captures all (equivalent to '.*') -router.get('[[\\s\\S]]*', function (req, res, next) { next() }) -``` - -
diff --git a/_includes/api/en/4x/app-path.md b/_includes/api/en/4x/app-path.md deleted file mode 100644 index 6dd12d3d2d..0000000000 --- a/_includes/api/en/4x/app-path.md +++ /dev/null @@ -1,19 +0,0 @@ -

app.path()

- -Returns the canonical path of the app, a string. - -```js -var app = express() -var blog = express() -var blogAdmin = express() - -app.use('/blog', blog) -blog.use('/admin', blogAdmin) - -console.dir(app.path()) // '' -console.dir(blog.path()) // '/blog' -console.dir(blogAdmin.path()) // '/blog/admin' -``` - -The behavior of this method can become very complicated in complex cases of mounted apps: -it is usually better to use [req.baseUrl](#req.baseUrl) to get the canonical path of the app. diff --git a/_includes/api/en/4x/app-post-method.md b/_includes/api/en/4x/app-post-method.md deleted file mode 100644 index 2ccb9ce81a..0000000000 --- a/_includes/api/en/4x/app-post-method.md +++ /dev/null @@ -1,14 +0,0 @@ -

app.post(path, callback [, callback ...])

- -Routes HTTP POST requests to the specified path with the specified callback functions. -For more information, see the [routing guide](/{{page.lang}}/guide/routing.html). - -{% include api/en/4x/routing-args.html %} - -#### Example - -```js -app.post('/', function (req, res) { - res.send('POST request to homepage') -}) -``` diff --git a/_includes/api/en/4x/app-put-method.md b/_includes/api/en/4x/app-put-method.md deleted file mode 100644 index 3d4d62c9fc..0000000000 --- a/_includes/api/en/4x/app-put-method.md +++ /dev/null @@ -1,13 +0,0 @@ -

app.put(path, callback [, callback ...])

- -Routes HTTP PUT requests to the specified path with the specified callback functions. - -{% include api/en/4x/routing-args.html %} - -#### Example - -```js -app.put('/', function (req, res) { - res.send('PUT request to homepage') -}) -``` diff --git a/_includes/api/en/4x/app-render.md b/_includes/api/en/4x/app-render.md deleted file mode 100644 index 8e35207ebd..0000000000 --- a/_includes/api/en/4x/app-render.md +++ /dev/null @@ -1,39 +0,0 @@ -

app.render(view, [locals], callback)

- -Returns the rendered HTML of a view via the `callback` function. It accepts an optional parameter -that is an object containing local variables for the view. It is like [res.render()](#res.render), -except it cannot send the rendered view to the client on its own. - -
-Think of `app.render()` as a utility function for generating rendered view strings. -Internally `res.render()` uses `app.render()` to render views. -
- -
-The `view` argument performs file system operations like reading a file from -disk and evaluating Node.js modules, and as so for security reasons should not -contain input from the end-user. -
- -
-The `locals` object is used by view engines to render a response. The object -keys may be particularly sensitive and should not contain user-controlled -input, as it may affect the operation of the view engine or provide a path to -cross-site scripting. Consult the documentation for the used view engine for -additional considerations. -
- -
-The local variable `cache` is reserved for enabling view cache. Set it to `true`, if you want to -cache view during development; view caching is enabled in production by default. -
- -```js -app.render('email', function (err, html) { - // ... -}) - -app.render('email', { name: 'Tobi' }, function (err, html) { - // ... -}) -``` diff --git a/_includes/api/en/4x/app-route.md b/_includes/api/en/4x/app-route.md deleted file mode 100644 index 60a339b2e9..0000000000 --- a/_includes/api/en/4x/app-route.md +++ /dev/null @@ -1,20 +0,0 @@ -

app.route(path)

- -Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. -Use `app.route()` to avoid duplicate route names (and thus typo errors). - -```js -var app = express() - -app.route('/events') - .all(function (req, res, next) { - // runs for all HTTP verbs first - // think of it as route specific middleware! - }) - .get(function (req, res, next) { - res.json({}) - }) - .post(function (req, res, next) { - // maybe add a new event... - }) -``` diff --git a/_includes/api/en/4x/app-set.md b/_includes/api/en/4x/app-set.md deleted file mode 100644 index 4215749fe8..0000000000 --- a/_includes/api/en/4x/app-set.md +++ /dev/null @@ -1,20 +0,0 @@ -

app.set(name, value)

- -Assigns setting `name` to `value`. You may store any value that you want, -but certain names can be used to configure the behavior of the server. These -special names are listed in the [app settings table](#app.settings.table). - -Calling `app.set('foo', true)` for a Boolean property is the same as calling -`app.enable('foo')`. Similarly, calling `app.set('foo', false)` for a Boolean -property is the same as calling `app.disable('foo')`. - -Retrieve the value of a setting with [`app.get()`](#app.get). - -```js -app.set('title', 'My Site') -app.get('title') // "My Site" -``` - -

Application Settings

- -{% include api/en/4x/app-settings.md %} diff --git a/_includes/api/en/4x/app-settings.md b/_includes/api/en/4x/app-settings.md deleted file mode 100644 index 3565364408..0000000000 --- a/_includes/api/en/4x/app-settings.md +++ /dev/null @@ -1,318 +0,0 @@ -The following table lists application settings. - -Note that 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. - -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"). - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyTypeDescriptionDefault
- `case sensitive routing` - Boolean

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.

-
N/A (undefined) -
- `env` - String - Environment mode. Be sure to set to "production" in a production environment; see [Production best practices: performance and reliability](/{{page.lang}}/advanced/best-practice-performance.html#env). - - `process.env.NODE_ENV` (`NODE_ENV` environment variable) or "development" if `NODE_ENV` is not set. -
- `etag` - Varied - Set the ETag response header. For possible values, see the [`etag` options table](#etag.options.table). - - [More about the HTTP ETag header](http://en.wikipedia.org/wiki/HTTP_ETag). - - `weak` -
- `jsonp callback name` - StringSpecifies the default JSONP callback name. - "callback" -
- `json escape` - Boolean - 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 it 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.

-
N/A (undefined)
- `json replacer` - VariedThe 'replacer' argument used by `JSON.stringify`. -

NOTE: Sub-apps will inherit the value of this setting.

-
N/A (undefined) -
- `json spaces` - VariedThe 'space' argument used by `JSON.stringify`. -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.

-
N/A (undefined)
- `query parser` - Varied -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](http://nodejs.org/api/querystring.html). - -The extended query parser is based on [qs](https://www.npmjs.org/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. - "extended"
- `strict routing` - Boolean

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.

-
N/A (undefined)
- `subdomain offset` - NumberThe number of dot-separated parts of the host to remove to access subdomain.2
- `trust proxy` - Varied - 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. -

- The `trust proxy` setting is implemented using the 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. -

-
- `false` (disabled) -
- `views` - String or ArrayA 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. - `process.cwd() + '/views'` -
- `view cache` - Boolean

Enables view template compilation caching.

-

NOTE: Sub-apps will not inherit the value of this setting in production (when `NODE_ENV` is "production").

-
- `true` in production, otherwise undefined. -
- `view engine` - StringThe default engine extension to use when omitted. -

NOTE: Sub-apps will inherit the value of this setting.

-
N/A (undefined)
- `x-powered-by` - BooleanEnables the "X-Powered-By: Express" HTTP header. - `true` -
- -
Options for `trust proxy` setting
- -

- Read [Express behind proxies](/{{page.lang}}/guide/behind-proxies.html) for more - information. -

- - - - - - - - - - - - - - - - - - - - - -
TypeValue
Boolean - If `true`, the client's IP address is understood as the left-most entry in the `X-Forwarded-*` header. - - If `false`, the app is understood as directly facing the Internet and the client's IP address is derived from `req.connection.remoteAddress`. This is the default setting. -
String
String containing comma-separated values
Array of strings
- An IP address, subnet, or an array of IP addresses, and subnets to trust. Pre-configured subnet names are: - - * loopback - `127.0.0.1/8`, `::1/128` - * linklocal - `169.254.0.0/16`, `fe80::/10` - * uniquelocal - `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `fc00::/7` - - Set IP addresses in any of the following ways: - -Specify a single subnet: - -```js -app.set('trust proxy', 'loopback') -``` - -Specify a subnet and an address: - -```js -app.set('trust proxy', 'loopback, 123.123.123.123') -``` - -Specify multiple subnets as CSV: - -```js -app.set('trust proxy', 'loopback, linklocal, uniquelocal') -``` - -Specify multiple subnets as an array: - -```js -app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) -``` - - When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client's IP address. -
Number - Trust the nth hop from the front-facing proxy server as the client. -
Function - Custom trust implementation. Use this only if you know what you are doing. - -```js -app.set('trust proxy', function (ip) { - if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // trusted IPs - else return false -}) -``` -
- -
Options for `etag` setting
- -

-**NOTE**: These settings apply only to dynamic files, not static files. -The [express.static](#express.static) middleware ignores these settings. -

- -

- The ETag functionality is implemented using the - [etag](https://www.npmjs.org/package/etag) package. - For more information, see its documentation. -

- - - - - - - - - - - - - - - - - -
TypeValue
Boolean - `true` enables weak ETag. This is the default setting.
- `false` disables ETag altogether. -
String - If "strong", enables strong ETag.
- If "weak", enables weak ETag. -
FunctionCustom ETag function implementation. Use this only if you know what you are doing. - -```js -app.set('etag', function (body, encoding) { - return generateHash(body, encoding) // consider the function is defined -}) -``` -
-
diff --git a/_includes/api/en/4x/app-use.md b/_includes/api/en/4x/app-use.md deleted file mode 100644 index 473b9f437e..0000000000 --- a/_includes/api/en/4x/app-use.md +++ /dev/null @@ -1,316 +0,0 @@ -

app.use([path,] callback [, callback...])

- -Mounts the specified [middleware](/{{page.lang}}/guide/using-middleware.html) function or functions -at the specified path: -the middleware function is executed when the base of the requested path matches `path`. - -{% include api/en/4x/routing-args.html %} - -#### Description - -A route will match any path that follows its path immediately with a "`/`". -For example: `app.use('/apple', ...)` will match "/apple", "/apple/images", -"/apple/images/news", and so on. - -Since `path` defaults to "/", middleware mounted without a path will be executed for every request to the app. -For example, this middleware function will be executed for _every_ request to the app: - -```js -app.use(function (req, res, next) { - console.log('Time: %d', Date.now()) - next() -}) -``` - -
-**NOTE** - -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. - -For details, see [Application settings](/en/4x/api.html#app.settings.table). -
- -Middleware functions are executed sequentially, therefore the order of middleware inclusion is important. - -```js -// this middleware will not allow the request to go beyond it -app.use(function (req, res, next) { - res.send('Hello World') -}) - -// requests will never reach this route -app.get('/', function (req, res) { - res.send('Welcome') -}) -``` - -**Error-handling middleware** - -Error-handling middleware always takes _four_ arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don't need to use the `next` object, you must specify it to maintain the signature. Otherwise, the `next` object will be interpreted as regular middleware and will fail to handle errors. For details about error-handling middleware, see: [Error handling](/{{ page.lang }}/guide/error-handling.html). - -Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature `(err, req, res, next)`): - -```js -app.use(function (err, req, res, next) { - console.error(err.stack) - res.status(500).send('Something broke!') -}) -``` - -#### Path examples - -The following table provides some simple examples of valid `path` values for -mounting middleware. - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TypeExample
Path -This will match paths starting with `/abcd`: - -```js -app.use('/abcd', function (req, res, next) { - next() -}) -``` - -
Path Pattern -This will match paths starting with `/abcd` and `/abd`: - -```js -app.use('/abc?d', function (req, res, next) { - next() -}) -``` - -This will match paths starting with `/abcd`, `/abbcd`, `/abbbbbcd`, and so on: - -```js -app.use('/ab+cd', function (req, res, next) { - next() -}) -``` - -This will match paths starting with `/abcd`, `/abxcd`, `/abFOOcd`, `/abbArcd`, and so on: - -```js -app.use('/ab*cd', function (req, res, next) { - next() -}) -``` - -This will match paths starting with `/ad` and `/abcd`: - -```js -app.use('/a(bc)?d', function (req, res, next) { - next() -}) -``` - -
Regular Expression -This will match paths starting with `/abc` and `/xyz`: - -```js -app.use(/\/abc|\/xyz/, function (req, res, next) { - next() -}) -``` - -
Array -This will match paths starting with `/abcd`, `/xyza`, `/lmn`, and `/pqr`: - -```js -app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], function (req, res, next) { - next() -}) -``` - -
-
- -#### Middleware callback function examples - -The following table provides some simple examples of middleware functions that -can be used as the `callback` argument to `app.use()`, `app.METHOD()`, and `app.all()`. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
UsageExample
Single Middleware -You can define and mount a middleware function locally. - -```js -app.use(function (req, res, next) { - next() -}) -``` - -A router is valid middleware. - -```js -var router = express.Router() -router.get('/', function (req, res, next) { - next() -}) -app.use(router) -``` - -An Express app is valid middleware. - -```js -var subApp = express() -subApp.get('/', function (req, res, next) { - next() -}) -app.use(subApp) -``` - -
Series of Middleware -You can specify more than one middleware function at the same mount path. - -```js -var r1 = express.Router() -r1.get('/', function (req, res, next) { - next() -}) - -var r2 = express.Router() -r2.get('/', function (req, res, next) { - next() -}) - -app.use(r1, r2) -``` - -
Array -Use an array to group middleware logically. - -```js -var r1 = express.Router() -r1.get('/', function (req, res, next) { - next() -}) - -var r2 = express.Router() -r2.get('/', function (req, res, next) { - next() -}) - -app.use([r1, r2]) -``` - -
Combination -You can combine all the above ways of mounting middleware. - -```js -function mw1 (req, res, next) { next() } -function mw2 (req, res, next) { next() } - -var r1 = express.Router() -r1.get('/', function (req, res, next) { next() }) - -var r2 = express.Router() -r2.get('/', function (req, res, next) { next() }) - -var subApp = express() -subApp.get('/', function (req, res, next) { next() }) - -app.use(mw1, [mw2, r1, r2], subApp) -``` - -
- -Following are some examples of using the [express.static](/{{page.lang}}/guide/using-middleware.html#middleware.built-in) -middleware in an Express app. - -Serve static content for the app from the "public" directory in the application directory: - -```js -// GET /style.css etc -app.use(express.static(path.join(__dirname, 'public'))) -``` - -Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static": - -```js -// GET /static/style.css etc. -app.use('/static', express.static(path.join(__dirname, 'public'))) -``` - -Disable logging for static content requests by loading the logger middleware after the static middleware: - -```js -app.use(express.static(path.join(__dirname, 'public'))) -app.use(logger()) -``` - -Serve static files from multiple directories, but give precedence to "./public" over the others: - -```js -app.use(express.static(path.join(__dirname, 'public'))) -app.use(express.static(path.join(__dirname, 'files'))) -app.use(express.static(path.join(__dirname, 'uploads'))) -``` diff --git a/_includes/api/en/4x/app.md b/_includes/api/en/4x/app.md deleted file mode 100644 index 518ec66efd..0000000000 --- a/_includes/api/en/4x/app.md +++ /dev/null @@ -1,123 +0,0 @@ -

Application

- -The `app` object conventionally denotes the Express application. -Create it by calling the top-level `express()` function exported by the Express module: - -```js -var express = require('express') -var app = express() - -app.get('/', function (req, res) { - res.send('hello world') -}) - -app.listen(3000) -``` - -The `app` object has methods for - -* Routing HTTP requests; see for example, [app.METHOD](#app.METHOD) and [app.param](#app.param). -* Configuring middleware; see [app.route](#app.route). -* Rendering HTML views; see [app.render](#app.render). -* Registering a template engine; see [app.engine](#app.engine). - -It also has settings (properties) that affect how the application behaves; -for more information, see [Application settings](#app.settings.table). - -
-The Express application object can be referred from the [request object](#req) and the [response object](#res) as `req.app`, and `res.app`, respectively. -
- -

Properties

- -
- {% include api/en/4x/app-locals.md %} -
- -
- {% include api/en/4x/app-mountpath.md %} -
- -

Events

- -
- {% include api/en/4x/app-onmount.md %} -
- -

Methods

- -
- {% include api/en/4x/app-all.md %} -
- -
- {% include api/en/4x/app-delete-method.md %} -
- -
- {% include api/en/4x/app-disable.md %} -
- -
- {% include api/en/4x/app-disabled.md %} -
- -
- {% include api/en/4x/app-enable.md %} -
- -
- {% include api/en/4x/app-enabled.md %} -
- -
- {% include api/en/4x/app-engine.md %} -
- -
- {% include api/en/4x/app-get.md %} -
- -
- {% include api/en/4x/app-get-method.md %} -
- -
- {% include api/en/4x/app-listen.md %} -
- -
- {% include api/en/4x/app-METHOD.md %} -
- -
- {% include api/en/4x/app-param.md %} -
- -
- {% include api/en/4x/app-path.md %} -
- -
- {% include api/en/4x/app-post-method.md %} -
- -
- {% include api/en/4x/app-put-method.md %} -
- -
- {% include api/en/4x/app-render.md %} -
- -
- {% include api/en/4x/app-route.md %} -
- -
- {% include api/en/4x/app-set.md %} -
- -
- {% include api/en/4x/app-use.md %} -
diff --git a/_includes/api/en/4x/express.json.md b/_includes/api/en/4x/express.json.md deleted file mode 100644 index f7cb4b7c1e..0000000000 --- a/_includes/api/en/4x/express.json.md +++ /dev/null @@ -1,38 +0,0 @@ -

express.json([options])

- -
-This middleware is available in Express v4.16.0 onwards. -
- -This is a built-in middleware function in Express. It parses incoming requests -with JSON payloads and is based on -[body-parser](/resources/middleware/body-parser.html). - -Returns middleware that only parses JSON and only looks at requests where -the `Content-Type` header matches the `type` option. This parser accepts any -Unicode encoding of the body and supports automatic inflation of `gzip` and -`deflate` encodings. - -A new `body` object containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`), or an empty object (`{}`) if -there was no body to parse, the `Content-Type` was not matched, or an error -occurred. - -
-As `req.body`'s shape is based on user-controlled input, all properties and -values in this object are untrusted and should be validated before trusting. -For example, `req.body.foo.toString()` may fail in multiple ways, for example -`foo` may not be there or may not be a string, and `toString` may not be a -function and instead a string or other user-input. -
- -The following table describes the properties of the optional `options` object. - -| Property | Description | Type | Default | -|---------------|-----------------------------------------------------------------------|-------------|-----------------| -| `inflate` | Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. | Boolean | `true` | -| `limit` | Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. | Mixed | `"100kb"` | -| `reviver` | The `reviver` option is passed directly to `JSON.parse` as the second argument. You can find more information on this argument [in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). | Function | `null` | -| `strict` | Enables or disables only accepting arrays and objects; when disabled will accept anything `JSON.parse` accepts. | Boolean | `true` | -| `type` | This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `json`), a mime type (like `application/json`), or a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. | Mixed | `"application/json"` | -| `verify` | This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. | Function | `undefined` | diff --git a/_includes/api/en/4x/express.md b/_includes/api/en/4x/express.md deleted file mode 100644 index 6ba0094cc7..0000000000 --- a/_includes/api/en/4x/express.md +++ /dev/null @@ -1,34 +0,0 @@ -

express()

- -Creates an Express application. The `express()` function is a top-level function exported by the `express` module. - -```js -var express = require('express') -var app = express() -``` - -

Methods

- -
- {% include api/en/4x/express.json.md %} -
- -
- {% include api/en/4x/express.raw.md %} -
- -
- {% include api/en/4x/express.router.md %} -
- -
- {% include api/en/4x/express.static.md %} -
- -
- {% include api/en/4x/express.text.md %} -
- -
- {% include api/en/4x/express.urlencoded.md %} -
diff --git a/_includes/api/en/4x/express.raw.md b/_includes/api/en/4x/express.raw.md deleted file mode 100644 index 0177f8dde0..0000000000 --- a/_includes/api/en/4x/express.raw.md +++ /dev/null @@ -1,36 +0,0 @@ -

express.raw([options])

- -
-This middleware is available in Express v4.17.0 onwards. -
- -This is a built-in middleware function in Express. It parses incoming request -payloads into a `Buffer` and is based on -[body-parser](/resources/middleware/body-parser.html). - -Returns middleware that parses all bodies as a `Buffer` and only looks at requests -where the `Content-Type` header matches the `type` option. This parser accepts -any Unicode encoding of the body and supports automatic inflation of `gzip` and -`deflate` encodings. - -A new `body` `Buffer` containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`), or an empty object (`{}`) if -there was no body to parse, the `Content-Type` was not matched, or an error -occurred. - -
-As `req.body`'s shape is based on user-controlled input, all properties and -values in this object are untrusted and should be validated before trusting. -For example, `req.body.toString()` may fail in multiple ways, for example -stacking multiple parsers `req.body` may be from a different parser. Testing -that `req.body` is a `Buffer` before calling buffer methods is recommended. -
- -The following table describes the properties of the optional `options` object. - -| Property | Description | Type | Default | -|-----------|-----------------------------------------------------------------------|-------------|-----------------| -| `inflate` | Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. | Boolean | `true` | -| `limit` | Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. | Mixed | `"100kb"` | -| `type` | This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `bin`), a mime type (like `application/octet-stream`), or a mime type with a wildcard (like `*/*` or `application/*`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. | Mixed | `"application/octet-stream"` | -| `verify` | This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. | Function | `undefined` | diff --git a/_includes/api/en/4x/express.router.md b/_includes/api/en/4x/express.router.md deleted file mode 100644 index 10dc92c94a..0000000000 --- a/_includes/api/en/4x/express.router.md +++ /dev/null @@ -1,24 +0,0 @@ -

express.Router([options])

- -Creates a new [router](#router) object. - -```js -var router = express.Router([options]) -``` - -The optional `options` parameter specifies the behavior of the router. - -
- -| Property | Description | Default | Availability | -|-----------------|-------------------------------------------------|-------------|---------------| -| `caseSensitive` | Enable case sensitivity. | Disabled by default, treating "/Foo" and "/foo" as the same.| | -| `mergeParams` | Preserve the `req.params` values from the parent router. If the parent and the child have conflicting param names, the child's value take precedence.| `false` | 4.5.0+ | -| `strict` | Enable strict routing. | Disabled by default, "/foo" and "/foo/" are treated the same by the router.|   | - -
- -You can add middleware and HTTP method routes (such as `get`, `put`, `post`, and -so on) to `router` just like an application. - -For more information, see [Router](#router). diff --git a/_includes/api/en/4x/express.static.md b/_includes/api/en/4x/express.static.md deleted file mode 100644 index 065ecb2762..0000000000 --- a/_includes/api/en/4x/express.static.md +++ /dev/null @@ -1,91 +0,0 @@ -

express.static(root, [options])

- -This is a built-in middleware function in Express. -It serves static files and is based on [serve-static](/resources/middleware/serve-static.html). - -{% capture alert_content %} -For best results, [use a reverse proxy](/{{page.lang}}/advanced/best-practice-performance.html#use-a-reverse-proxy) cache to improve performance of serving static assets. -{% endcapture %} -{% include admonitions/note.html content=alert_content %} - -The `root` argument specifies the root directory from which to serve static assets. -The function determines the file to serve by combining `req.url` with the provided `root` directory. -When a file is not found, instead of sending a 404 response, it calls `next()` -to move on to the next middleware, allowing for stacking and fall-backs. - -The following table describes the properties of the `options` object. -See also the [example below](#example.of.express.static). - -| Property | Description | Type | Default | -|---------------|-----------------------------------------------------------------------|-------------|-----------------| -| `dotfiles` | Determines how dotfiles (files or directories that begin with a dot ".") are treated.

See [dotfiles](#dotfiles) below. | String | `undefined` | -| `etag` | Enable or disable etag generation

NOTE: `express.static` always sends weak ETags. | Boolean | `true` | -| `extensions` | Sets file extension fallbacks: If a file is not found, search for files with the specified extensions and serve the first one found. Example: `['html', 'htm']`.| Mixed | `false` | -| `fallthrough` | Let client errors fall-through as unhandled requests, otherwise forward a client error.

See [fallthrough](#fallthrough) below.| Boolean | `true` | -| `immutable` | Enable or disable the `immutable` directive in the `Cache-Control` response header. If enabled, the `maxAge` option should also be specified to enable caching. The `immutable` directive will prevent supported clients from making conditional requests during the life of the `maxAge` option to check if the file has changed. | Boolean | `false` | -| `index` | Sends the specified directory index file. Set to `false` to disable directory indexing. | Mixed | "index.html" | -| `lastModified` | Set the `Last-Modified` header to the last modified date of the file on the OS. | Boolean | `true` | -| `maxAge` | Set the max-age property of the Cache-Control header in milliseconds or a string in [ms format](https://www.npmjs.org/package/ms). | Number | 0 | -| `redirect` | Redirect to trailing "/" when the pathname is a directory. | Boolean | `true` | -| `setHeaders` | Function for setting HTTP headers to serve with the file.

See [setHeaders](#setHeaders) below. | Function | | - -For more information, see [Serving static files in Express](/starter/static-files.html). -and [Using middleware - Built-in middleware](/{{page.lang}}/guide/using-middleware.html#middleware.built-in). - -
dotfiles
- -Possible values for this option are: - -- "allow" - No special treatment for dotfiles. -- "deny" - Deny a request for a dotfile, respond with `403`, then call `next()`. -- "ignore" - Act as if the dotfile does not exist, respond with `404`, then call `next()`. -- `undefined` - Act as ignore, except that files in a directory that begins with a dot are **NOT** ignored. - -
fallthrough
- -When this option is `true`, client errors such as a bad request or a request to a non-existent -file will cause this middleware to simply call `next()` to invoke the next middleware in the stack. -When false, these errors (even 404s), will invoke `next(err)`. - -Set this option to `true` so you can map multiple physical directories -to the same web address or for routes to fill in non-existent files. - -Use `false` if you have mounted this middleware at a path designed -to be strictly a single file system directory, which allows for short-circuiting 404s -for less overhead. This middleware will also reply to all methods. - -
setHeaders
- -For this option, specify a function to set custom response headers. Alterations to the headers must occur synchronously. - -The signature of the function is: - -```js -fn(res, path, stat) -``` - -Arguments: - -- `res`, the [response object](#res). -- `path`, the file path that is being sent. -- `stat`, the `stat` object of the file that is being sent. - -

Example of express.static

- -Here is an example of using the `express.static` middleware function with an elaborate options object: - -```js -var options = { - dotfiles: 'ignore', - etag: false, - extensions: ['htm', 'html'], - index: false, - maxAge: '1d', - redirect: false, - setHeaders: function (res, path, stat) { - res.set('x-timestamp', Date.now()) - } -} - -app.use(express.static('public', options)) -``` diff --git a/_includes/api/en/4x/express.text.md b/_includes/api/en/4x/express.text.md deleted file mode 100644 index 90364c6d76..0000000000 --- a/_includes/api/en/4x/express.text.md +++ /dev/null @@ -1,37 +0,0 @@ -

express.text([options])

- -
-This middleware is available in Express v4.17.0 onwards. -
- -This is a built-in middleware function in Express. It parses incoming request -payloads into a string and is based on -[body-parser](/resources/middleware/body-parser.html). - -Returns middleware that parses all bodies as a string and only looks at requests -where the `Content-Type` header matches the `type` option. This parser accepts -any Unicode encoding of the body and supports automatic inflation of `gzip` and -`deflate` encodings. - -A new `body` string containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`), or an empty object (`{}`) if -there was no body to parse, the `Content-Type` was not matched, or an error -occurred. - -
-As `req.body`'s shape is based on user-controlled input, all properties and -values in this object are untrusted and should be validated before trusting. -For example, `req.body.trim()` may fail in multiple ways, for example -stacking multiple parsers `req.body` may be from a different parser. Testing -that `req.body` is a string before calling string methods is recommended. -
- -The following table describes the properties of the optional `options` object. - -| Property | Description | Type | Default | -|------------------|-----------------------------------------------------------------------|-------------|-----------------| -| `defaultCharset` | Specify the default character set for the text content if the charset is not specified in the `Content-Type` header of the request. | String | `"utf-8"` | -| `inflate` | Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. | Boolean | `true` | -| `limit` | Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. | Mixed | `"100kb"` | -| `type` | This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `txt`), a mime type (like `text/plain`), or a mime type with a wildcard (like `*/*` or `text/*`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. | Mixed | `"text/plain"` | -| `verify` | This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. | Function | `undefined` | diff --git a/_includes/api/en/4x/express.urlencoded.md b/_includes/api/en/4x/express.urlencoded.md deleted file mode 100644 index f20ae40e30..0000000000 --- a/_includes/api/en/4x/express.urlencoded.md +++ /dev/null @@ -1,39 +0,0 @@ -

express.urlencoded([options])

- -
-This middleware is available in Express v4.16.0 onwards. -
- -This is a built-in middleware function in Express. It parses incoming requests -with urlencoded payloads and is based on [body-parser](/resources/middleware/body-parser.html). - -Returns middleware that only parses urlencoded bodies and only looks at -requests where the `Content-Type` header matches the `type` option. This -parser accepts only UTF-8 encoding of the body and supports automatic -inflation of `gzip` and `deflate` encodings. - -A new `body` object containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`), or an empty object (`{}`) if -there was no body to parse, the `Content-Type` was not matched, or an error -occurred. This object will contain key-value pairs, where the value can be -a string or array (when `extended` is `false`), or any type (when `extended` -is `true`). - -
-As `req.body`'s shape is based on user-controlled input, all properties and -values in this object are untrusted and should be validated before trusting. -For example, `req.body.foo.toString()` may fail in multiple ways, for example -`foo` may not be there or may not be a string, and `toString` may not be a -function and instead a string or other user-input. -
- -The following table describes the properties of the optional `options` object. - -| Property | Description | Type | Default | -|------------------|-----------------------------------------------------------------------|-------------|-----------------| -| `extended` | This option allows to choose between parsing the URL-encoded data with the `querystring` library (when `false`) or the `qs` library (when `true`). The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please [see the qs library](https://www.npmjs.org/package/qs#readme). | Boolean | `true` | -| `inflate` | Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. | Boolean | `true` | -| `limit` | Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. | Mixed | `"100kb"` | -| `parameterLimit` | This option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, an error will be raised. | Number | `1000` | -| `type` | This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `urlencoded`), a mime type (like `application/x-www-form-urlencoded`), or a mime type with a wildcard (like `*/x-www-form-urlencoded`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. | Mixed | `"application/x-www-form-urlencoded"` | -| `verify` | This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. | Function | `undefined` | diff --git a/_includes/api/en/4x/menu.md b/_includes/api/en/4x/menu.md deleted file mode 100644 index ff585b2905..0000000000 --- a/_includes/api/en/4x/menu.md +++ /dev/null @@ -1,207 +0,0 @@ - diff --git a/_includes/api/en/4x/req-accepts.md b/_includes/api/en/4x/req-accepts.md deleted file mode 100644 index 7258c71b4c..0000000000 --- a/_includes/api/en/4x/req-accepts.md +++ /dev/null @@ -1,36 +0,0 @@ -

req.accepts(types)

- -Checks if the specified content types are acceptable, based on the request's `Accept` HTTP header field. -The method returns the best match, or if none of the specified content types is acceptable, returns -`false` (in which case, the application should respond with `406 "Not Acceptable"`). - -The `type` value may be a single MIME type string (such as "application/json"), -an extension name such as "json", a comma-delimited list, or an array. For a -list or array, the method returns the *best* match (if any). - -```js -// Accept: text/html -req.accepts('html') -// => "html" - -// Accept: text/*, application/json -req.accepts('html') -// => "html" -req.accepts('text/html') -// => "text/html" -req.accepts(['json', 'text']) -// => "json" -req.accepts('application/json') -// => "application/json" - -// Accept: text/*, application/json -req.accepts('image/png') -req.accepts('png') -// => false - -// Accept: text/*;q=.5, application/json -req.accepts(['html', 'json']) -// => "json" -``` - -For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts). diff --git a/_includes/api/en/4x/req-acceptsCharsets.md b/_includes/api/en/4x/req-acceptsCharsets.md deleted file mode 100644 index d47d0480d3..0000000000 --- a/_includes/api/en/4x/req-acceptsCharsets.md +++ /dev/null @@ -1,7 +0,0 @@ -

req.acceptsCharsets(charset [, ...])

- -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`. - -For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts). diff --git a/_includes/api/en/4x/req-acceptsEncodings.md b/_includes/api/en/4x/req-acceptsEncodings.md deleted file mode 100644 index 2c6a3f236f..0000000000 --- a/_includes/api/en/4x/req-acceptsEncodings.md +++ /dev/null @@ -1,7 +0,0 @@ -

req.acceptsEncodings(encoding [, ...])

- -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`. - -For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts). diff --git a/_includes/api/en/4x/req-acceptsLanguages.md b/_includes/api/en/4x/req-acceptsLanguages.md deleted file mode 100644 index 0ea278b1da..0000000000 --- a/_includes/api/en/4x/req-acceptsLanguages.md +++ /dev/null @@ -1,15 +0,0 @@ -

req.acceptsLanguages([lang, ...])

- -Returns the first accepted language of the specified languages, -based on the request's `Accept-Language` HTTP header field. -If none of the specified languages is accepted, returns `false`. - -If no `lang` argument is given, then `req.acceptsLanguages()` -returns all languages from the HTTP `Accept-Language` header -as an `Array`. - -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) - -Accepts (1.3) source: [index.js line 195](https://github.com/jshttp/accepts/blob/f69c19e459bd501e59fb0b1a40b7471bb578113a/index.js#L195) diff --git a/_includes/api/en/4x/req-app.md b/_includes/api/en/4x/req-app.md deleted file mode 100644 index 8fde7da97e..0000000000 --- a/_includes/api/en/4x/req-app.md +++ /dev/null @@ -1,20 +0,0 @@ -

req.app

- -This property holds a reference to the instance of the Express application that is using the middleware. - -If you follow the pattern in which you create a module that just exports a middleware function -and `require()` it in your main file, then the middleware can access the Express instance via `req.app` - -For example: - -```js -// index.js -app.get('/viewdirectory', require('./mymiddleware.js')) -``` - -```js -// mymiddleware.js -module.exports = function (req, res) { - res.send('The views directory is ' + req.app.get('views')) -} -``` diff --git a/_includes/api/en/4x/req-baseUrl.md b/_includes/api/en/4x/req-baseUrl.md deleted file mode 100644 index 039c636f93..0000000000 --- a/_includes/api/en/4x/req-baseUrl.md +++ /dev/null @@ -1,30 +0,0 @@ -

req.baseUrl

- -The URL path on which a router instance was mounted. - -The `req.baseUrl` property is similar to the [mountpath](#app.mountpath) property of the `app` object, -except `app.mountpath` returns the matched path pattern(s). - -For example: - -```js -var greet = express.Router() - -greet.get('/jp', function (req, res) { - console.log(req.baseUrl) // /greet - res.send('Konnichiwa!') -}) - -app.use('/greet', greet) // load the router on '/greet' -``` - -Even if you use a path pattern or a set of path patterns to load the router, -the `baseUrl` property returns the matched string, not the pattern(s). In the -following example, the `greet` router is loaded on two path patterns. - -```js -app.use(['/gre+t', '/hel{2}o'], greet) // load the router on '/gre+t' and '/hel{2}o' -``` - -When a request is made to `/greet/jp`, `req.baseUrl` is "/greet". When a request is -made to `/hello/jp`, `req.baseUrl` is "/hello". diff --git a/_includes/api/en/4x/req-body.md b/_includes/api/en/4x/req-body.md deleted file mode 100644 index a0caa50067..0000000000 --- a/_includes/api/en/4x/req-body.md +++ /dev/null @@ -1,25 +0,0 @@ -

req.body

- -Contains key-value pairs of data submitted in the request body. -By default, it is `undefined`, and is populated when you use body-parsing middleware such -as [`express.json()`](#express.json) or [`express.urlencoded()`](#express.urlencoded). - -
-As `req.body`'s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input. -
- -The following example shows how to use body-parsing middleware to populate `req.body`. - -```js -var express = require('express') - -var app = express() - -app.use(express.json()) // for parsing application/json -app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded - -app.post('/profile', function (req, res, next) { - console.log(req.body) - res.json(req.body) -}) -``` diff --git a/_includes/api/en/4x/req-cookies.md b/_includes/api/en/4x/req-cookies.md deleted file mode 100644 index 244276fffe..0000000000 --- a/_includes/api/en/4x/req-cookies.md +++ /dev/null @@ -1,14 +0,0 @@ -

req.cookies

- -When using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this property is an object that -contains cookies sent by the request. If the request contains no cookies, it defaults to `{}`. - -```js -// Cookie: name=tj -console.dir(req.cookies.name) -// => 'tj' -``` - -If the cookie has been signed, you have to use [req.signedCookies](#req.signedCookies). - -For more information, issues, or concerns, see [cookie-parser](https://github.com/expressjs/cookie-parser). diff --git a/_includes/api/en/4x/req-fresh.md b/_includes/api/en/4x/req-fresh.md deleted file mode 100644 index 1b6ec61c59..0000000000 --- a/_includes/api/en/4x/req-fresh.md +++ /dev/null @@ -1,13 +0,0 @@ -

req.fresh

- -When the response is still "fresh" in the client's cache `true` is returned, otherwise `false` is returned to indicate that the client cache is now stale and the full response should be sent. - -When a client sends the `Cache-Control: no-cache` request header to indicate an end-to-end reload request, this module will return `false` to make handling these requests transparent. - -Further details for how cache validation works can be found in the -[HTTP/1.1 Caching Specification](https://tools.ietf.org/html/rfc7234). - -```js -console.dir(req.fresh) -// => true -``` diff --git a/_includes/api/en/4x/req-get.md b/_includes/api/en/4x/req-get.md deleted file mode 100644 index 7cd4250b22..0000000000 --- a/_includes/api/en/4x/req-get.md +++ /dev/null @@ -1,17 +0,0 @@ -

req.get(field)

- -Returns the specified HTTP request header field (case-insensitive match). -The `Referrer` and `Referer` fields are interchangeable. - -```js -req.get('Content-Type') -// => "text/plain" - -req.get('content-type') -// => "text/plain" - -req.get('Something') -// => undefined -``` - -Aliased as `req.header(field)`. diff --git a/_includes/api/en/4x/req-hostname.md b/_includes/api/en/4x/req-hostname.md deleted file mode 100644 index fbb4731440..0000000000 --- a/_includes/api/en/4x/req-hostname.md +++ /dev/null @@ -1,23 +0,0 @@ -

req.hostname

- -Contains the hostname derived from the `Host` HTTP header. - -When the [`trust proxy` setting](/4x/api.html#trust.proxy.options.table) -does not evaluate to `false`, this property will instead get the value -from the `X-Forwarded-Host` header field. This header can be set by -the client or by the proxy. - -If there is more than one `X-Forwarded-Host` header in the request, the -value of the first header is used. This includes a single header with -comma-separated values, in which the first value is used. - -
-Prior to Express v4.17.0, the `X-Forwarded-Host` could not contain multiple -values or be present more than once. -
- -```js -// Host: "example.com:3000" -console.dir(req.hostname) -// => 'example.com' -``` diff --git a/_includes/api/en/4x/req-ip.md b/_includes/api/en/4x/req-ip.md deleted file mode 100644 index fea8639d52..0000000000 --- a/_includes/api/en/4x/req-ip.md +++ /dev/null @@ -1,12 +0,0 @@ -

req.ip

- -Contains the remote IP address of the request. - -When the [`trust proxy` setting](/4x/api.html#trust.proxy.options.table) does not evaluate to `false`, -the value of this property is derived from the left-most entry in the -`X-Forwarded-For` header. This header can be set by the client or by the proxy. - -```js -console.dir(req.ip) -// => '127.0.0.1' -``` diff --git a/_includes/api/en/4x/req-ips.md b/_includes/api/en/4x/req-ips.md deleted file mode 100644 index 7fa7b2653e..0000000000 --- a/_includes/api/en/4x/req-ips.md +++ /dev/null @@ -1,9 +0,0 @@ -

req.ips

- -When the [`trust proxy` setting](/4x/api.html#trust.proxy.options.table) does not evaluate to `false`, -this property contains an array of IP addresses -specified in the `X-Forwarded-For` request header. Otherwise, it contains an -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. diff --git a/_includes/api/en/4x/req-is.md b/_includes/api/en/4x/req-is.md deleted file mode 100644 index fd4ca1dbdf..0000000000 --- a/_includes/api/en/4x/req-is.md +++ /dev/null @@ -1,28 +0,0 @@ -

req.is(type)

- -Returns the matching content type if the incoming request's "Content-Type" HTTP header field -matches the MIME type specified by the `type` parameter. If the request has no body, returns `null`. -Returns `false` otherwise. - -```js -// With Content-Type: text/html; charset=utf-8 -req.is('html') -// => 'html' -req.is('text/html') -// => 'text/html' -req.is('text/*') -// => 'text/*' - -// When Content-Type is application/json -req.is('json') -// => 'json' -req.is('application/json') -// => 'application/json' -req.is('application/*') -// => 'application/*' - -req.is('html') -// => false -``` - -For more information, or if you have issues or concerns, see [type-is](https://github.com/expressjs/type-is). diff --git a/_includes/api/en/4x/req-method.md b/_includes/api/en/4x/req-method.md deleted file mode 100644 index 3d2b886d7d..0000000000 --- a/_includes/api/en/4x/req-method.md +++ /dev/null @@ -1,4 +0,0 @@ -

req.method

- -Contains a string corresponding to the HTTP method of the request: -`GET`, `POST`, `PUT`, and so on. diff --git a/_includes/api/en/4x/req-originalUrl.md b/_includes/api/en/4x/req-originalUrl.md deleted file mode 100644 index 4babd80d04..0000000000 --- a/_includes/api/en/4x/req-originalUrl.md +++ /dev/null @@ -1,27 +0,0 @@ -

req.originalUrl

- -
-`req.url` is not a native Express property, it is inherited from Node's [http module](https://nodejs.org/api/http.html#http_message_url). -
- -This property is much like `req.url`; however, it retains the original request URL, -allowing you to rewrite `req.url` freely for internal routing purposes. For example, -the "mounting" feature of [app.use()](#app.use) will rewrite `req.url` to strip the mount point. - -```js -// GET /search?q=something -console.dir(req.originalUrl) -// => '/search?q=something' -``` - -`req.originalUrl` is available both in middleware and router objects, and is a -combination of `req.baseUrl` and `req.url`. Consider following example: - -```js -app.use('/admin', function (req, res, next) { // GET 'http://www.example.com/admin/new?sort=desc' - console.dir(req.originalUrl) // '/admin/new?sort=desc' - console.dir(req.baseUrl) // '/admin' - console.dir(req.path) // '/new' - next() -}) -``` diff --git a/_includes/api/en/4x/req-param.md b/_includes/api/en/4x/req-param.md deleted file mode 100644 index c0a31602be..0000000000 --- a/_includes/api/en/4x/req-param.md +++ /dev/null @@ -1,35 +0,0 @@ -

req.param(name [, defaultValue])

- -
-Deprecated. Use either `req.params`, `req.body` or `req.query`, as applicable. -
- -Returns the value of param `name` when present. - -```js -// ?name=tobi -req.param('name') -// => "tobi" - -// POST name=tobi -req.param('name') -// => "tobi" - -// /user/tobi for /user/:name -req.param('name') -// => "tobi" -``` - -Lookup is performed in the following order: - -* `req.params` -* `req.body` -* `req.query` - -Optionally, you can specify `defaultValue` to set a default value if the parameter is not found in any of the request objects. - -
-Direct access to `req.body`, `req.params`, and `req.query` should be favoured for clarity - unless you truly accept input from each object. - -Body-parsing middleware must be loaded for `req.param()` to work predictably. Refer [req.body](#req.body) for details. -
diff --git a/_includes/api/en/4x/req-params.md b/_includes/api/en/4x/req-params.md deleted file mode 100644 index 5c08065e08..0000000000 --- a/_includes/api/en/4x/req-params.md +++ /dev/null @@ -1,23 +0,0 @@ -

req.params

- -This property is an object containing properties mapped to the [named route "parameters"](/{{ page.lang }}/guide/routing.html#route-parameters). For example, if you have the route `/user/:name`, then the "name" property is available as `req.params.name`. This object defaults to `{}`. - -```js -// GET /user/tj -console.dir(req.params.name) -// => 'tj' -``` - -When you use a regular expression for the route definition, capture groups are provided in the array using `req.params[n]`, where `n` is the nth capture group. This rule is applied to unnamed wild card matches with string routes such as `/file/*`: - -```js -// GET /file/javascripts/jquery.js -console.dir(req.params[0]) -// => 'javascripts/jquery.js' -``` - -If you need to make changes to a key in `req.params`, use the [app.param](/{{ page.lang }}/4x/api.html#app.param) handler. Changes are applicable only to [parameters](/{{ page.lang }}/guide/routing.html#route-parameters) already defined in the route path. - -Any changes made to the `req.params` object in a middleware or route handler will be reset. - -{% include admonitions/note.html content="Express automatically decodes the values in `req.params` (using `decodeURIComponent`)." %} diff --git a/_includes/api/en/4x/req-path.md b/_includes/api/en/4x/req-path.md deleted file mode 100644 index 0b71c71bf7..0000000000 --- a/_includes/api/en/4x/req-path.md +++ /dev/null @@ -1,13 +0,0 @@ -

req.path

- -Contains the path part of the request URL. - -```js -// example.com/users?sort=desc -console.dir(req.path) -// => '/users' -``` - -
-When called from a middleware, the mount point is not included in `req.path`. See [app.use()](/4x/api.html#app.use) for more details. -
diff --git a/_includes/api/en/4x/req-protocol.md b/_includes/api/en/4x/req-protocol.md deleted file mode 100644 index 6d38cc1f19..0000000000 --- a/_includes/api/en/4x/req-protocol.md +++ /dev/null @@ -1,12 +0,0 @@ -

req.protocol

- -Contains the request protocol string: either `http` or (for TLS requests) `https`. - -When the [`trust proxy` setting](#trust.proxy.options.table) does not evaluate to `false`, -this property will use the value of the `X-Forwarded-Proto` header field if present. -This header can be set by the client or by the proxy. - -```js -console.dir(req.protocol) -// => 'http' -``` diff --git a/_includes/api/en/4x/req-query.md b/_includes/api/en/4x/req-query.md deleted file mode 100644 index 019779b8f3..0000000000 --- a/_includes/api/en/4x/req-query.md +++ /dev/null @@ -1,19 +0,0 @@ -

req.query

- -This property is an object containing a property for each query string parameter in the route. -When [query parser](#app.settings.table) is set to disabled, it is an empty object `{}`, otherwise it is the result of the configured query parser. - -
-As `req.query`'s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.query.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input. -
- -The value of this property can be configured with the [query parser application setting](#app.settings.table) to work how your application needs it. A very popular query string parser is the [`qs` module](https://www.npmjs.org/package/qs), and this is used by default. The `qs` module is very configurable with many settings, and it may be desirable to use different settings than the default to populate `req.query`: - -```js -var qs = require('qs') -app.set('query parser', function (str) { - return qs.parse(str, { /* custom options */ }) -}) -``` - -Check out the [query parser application setting](#app.settings.table) documentation for other customization options. diff --git a/_includes/api/en/4x/req-range.md b/_includes/api/en/4x/req-range.md deleted file mode 100644 index e6411c662d..0000000000 --- a/_includes/api/en/4x/req-range.md +++ /dev/null @@ -1,29 +0,0 @@ -

req.range(size[, options])

- -`Range` header parser. - -The `size` parameter is the maximum size of the resource. - -The `options` parameter is an object that can have the following properties. - -| Property | Type | Description | -|-------------|-------------------------------------------------------------------------| -| `combine` | Boolean | Specify if overlapping & adjacent ranges should be combined, defaults to `false`. When `true`, ranges will be combined and returned as if they were specified that way in the header. - -An array of ranges will be returned or negative numbers indicating an error parsing. - -* `-2` signals a malformed header string -* `-1` signals an unsatisfiable range - -```js -// parse header from request -var range = req.range(1000) - -// the type of the range -if (range.type === 'bytes') { - // the ranges - range.forEach(function (r) { - // do something with r.start and r.end - }) -} -``` diff --git a/_includes/api/en/4x/req-res.md b/_includes/api/en/4x/req-res.md deleted file mode 100644 index 772ddb43b4..0000000000 --- a/_includes/api/en/4x/req-res.md +++ /dev/null @@ -1,4 +0,0 @@ -

req.res

- -This property holds a reference to the response object -that relates to this request object. diff --git a/_includes/api/en/4x/req-route.md b/_includes/api/en/4x/req-route.md deleted file mode 100644 index bc5bc31a0b..0000000000 --- a/_includes/api/en/4x/req-route.md +++ /dev/null @@ -1,25 +0,0 @@ -

req.route

- -Contains the currently-matched route, a string. For example: - -```js -app.get('/user/:id?', function userIdHandler (req, res) { - console.log(req.route) - res.send('GET') -}) -``` - -Example output from the previous snippet: - -``` -{ path: '/user/:id?', - stack: - [ { handle: [Function: userIdHandler], - name: 'userIdHandler', - params: undefined, - path: undefined, - keys: [], - regexp: /^\/?$/i, - method: 'get' } ], - methods: { get: true } } -``` diff --git a/_includes/api/en/4x/req-secure.md b/_includes/api/en/4x/req-secure.md deleted file mode 100644 index 5519638a47..0000000000 --- a/_includes/api/en/4x/req-secure.md +++ /dev/null @@ -1,8 +0,0 @@ -

req.secure

- -A Boolean property that is true if a TLS connection is established. Equivalent to: - -```js -console.dir(req.protocol === 'https') -// => true -``` diff --git a/_includes/api/en/4x/req-signedCookies.md b/_includes/api/en/4x/req-signedCookies.md deleted file mode 100644 index eb2cba8343..0000000000 --- a/_includes/api/en/4x/req-signedCookies.md +++ /dev/null @@ -1,17 +0,0 @@ -

req.signedCookies

- -When using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this property -contains signed cookies sent by the request, unsigned and ready for use. Signed cookies reside -in a different object to show developer intent; otherwise, a malicious attack could be placed on -`req.cookie` values (which are easy to spoof). Note that signing a cookie does not make it "hidden" -or encrypted; but simply prevents tampering (because the secret used to sign is private). - -If no signed cookies are sent, the property defaults to `{}`. - -```js -// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3 -console.dir(req.signedCookies.user) -// => 'tobi' -``` - -For more information, issues, or concerns, see [cookie-parser](https://github.com/expressjs/cookie-parser). diff --git a/_includes/api/en/4x/req-stale.md b/_includes/api/en/4x/req-stale.md deleted file mode 100644 index ca8b479f4c..0000000000 --- a/_includes/api/en/4x/req-stale.md +++ /dev/null @@ -1,9 +0,0 @@ -

req.stale

- -Indicates whether the request is "stale," and is the opposite of `req.fresh`. -For more information, see [req.fresh](#req.fresh). - -```js -console.dir(req.stale) -// => true -``` diff --git a/_includes/api/en/4x/req-subdomains.md b/_includes/api/en/4x/req-subdomains.md deleted file mode 100644 index 0f8e27a840..0000000000 --- a/_includes/api/en/4x/req-subdomains.md +++ /dev/null @@ -1,13 +0,0 @@ -

req.subdomains

- -An array of subdomains in the domain name of the request. - -```js -// Host: "tobi.ferrets.example.com" -console.dir(req.subdomains) -// => ['ferrets', 'tobi'] -``` - -The application property `subdomain offset`, which defaults to 2, is used for determining the -beginning of the subdomain segments. To change this behavior, change its value -using [app.set](/{{ page.lang }}/4x/api.html#app.set). diff --git a/_includes/api/en/4x/req-xhr.md b/_includes/api/en/4x/req-xhr.md deleted file mode 100644 index 5c1da1c704..0000000000 --- a/_includes/api/en/4x/req-xhr.md +++ /dev/null @@ -1,9 +0,0 @@ -

req.xhr

- -A Boolean property that is `true` if the request's `X-Requested-With` header field is -"XMLHttpRequest", indicating that the request was issued by a client library such as jQuery. - -```js -console.dir(req.xhr) -// => true -``` diff --git a/_includes/api/en/4x/req.md b/_includes/api/en/4x/req.md deleted file mode 100644 index 8e217a6f5b..0000000000 --- a/_includes/api/en/4x/req.md +++ /dev/null @@ -1,156 +0,0 @@ -

Request

- -The `req` object represents the HTTP request and has properties for the -request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, -the object is always referred to as `req` (and the HTTP response is `res`) but its actual name is determined -by the parameters to the callback function in which you're working. - -For example: - -```js -app.get('/user/:id', function (req, res) { - res.send('user ' + req.params.id) -}) -``` - -But you could just as well have: - -```js -app.get('/user/:id', function (request, response) { - response.send('user ' + request.params.id) -}) -``` - -The `req` object is an enhanced version of Node's own request object -and supports all [built-in fields and methods](https://nodejs.org/api/http.html#http_class_http_incomingmessage). - -

Properties

- -
-In Express 4, `req.files` is no longer available on the `req` object by default. To access uploaded files -on the `req.files` object, use multipart-handling middleware like [busboy](https://www.npmjs. -com/package/busboy), [multer](https://www.npmjs.com/package/multer), -[formidable](https://www.npmjs.com/package/formidable), -[multiparty](https://www.npmjs.com/package/multiparty), -[connect-multiparty](https://www.npmjs.com/package/connect-multiparty), -or [pez](https://www.npmjs.com/package/pez). -
- -
- {% include api/en/4x/req-app.md %} -
- -
- {% include api/en/4x/req-baseUrl.md %} -
- -
- {% include api/en/4x/req-body.md %} -
- -
- {% include api/en/4x/req-cookies.md %} -
- -
- {% include api/en/4x/req-fresh.md %} -
- -
- {% include api/en/4x/req-hostname.md %} -
- -
- {% include api/en/4x/req-ip.md %} -
- -
- {% include api/en/4x/req-ips.md %} -
- -
- {% include api/en/4x/req-method.md %} -
- -
- {% include api/en/4x/req-originalUrl.md %} -
- -
- {% include api/en/4x/req-params.md %} -
- -
- {% include api/en/4x/req-path.md %} -
- -
- {% include api/en/4x/req-protocol.md %} -
- -
- {% include api/en/4x/req-query.md %} -
- -
- {% include api/en/4x/req-res.md %} -
- -
- {% include api/en/4x/req-route.md %} -
- -
- {% include api/en/4x/req-secure.md %} -
- -
- {% include api/en/4x/req-signedCookies.md %} -
- -
- {% include api/en/4x/req-stale.md %} -
- -
- {% include api/en/4x/req-subdomains.md %} -
- -
- {% include api/en/4x/req-xhr.md %} -
- -

Methods

- -
- {% include api/en/4x/req-accepts.md %} -
- -
- {% include api/en/4x/req-acceptsCharsets.md %} -
- -
- {% include api/en/4x/req-acceptsEncodings.md %} -
- -
- {% include api/en/4x/req-acceptsLanguages.md %} -
- -
- {% include api/en/4x/req-get.md %} -
- -
- {% include api/en/4x/req-is.md %} -
- -
- {% include api/en/4x/req-param.md %} -
- -
- {% include api/en/4x/req-range.md %} -
- diff --git a/_includes/api/en/4x/res-app.md b/_includes/api/en/4x/res-app.md deleted file mode 100644 index 19d8681d23..0000000000 --- a/_includes/api/en/4x/res-app.md +++ /dev/null @@ -1,5 +0,0 @@ -

res.app

- -This property holds a reference to the instance of the Express application that is using the middleware. - -`res.app` is identical to the [req.app](#req.app) property in the request object. diff --git a/_includes/api/en/4x/res-append.md b/_includes/api/en/4x/res-append.md deleted file mode 100644 index c74e2fd3ef..0000000000 --- a/_includes/api/en/4x/res-append.md +++ /dev/null @@ -1,13 +0,0 @@ -

res.append(field [, value])

- -{% include admonitions/note.html content="`res.append()` is supported by Express v4.11.0+" %} -Appends the specified `value` to the HTTP response header `field`. If the header is not already set, -it creates the header with the specified value. The `value` parameter can be a string or an array. - -{% include admonitions/note.html content="calling `res.set()` after `res.append()` will reset the previously-set header value." %} - -```js -res.append('Link', ['', '']) -res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly') -res.append('Warning', '199 Miscellaneous warning') -``` diff --git a/_includes/api/en/4x/res-attachment.md b/_includes/api/en/4x/res-attachment.md deleted file mode 100644 index 73932d14fc..0000000000 --- a/_includes/api/en/4x/res-attachment.md +++ /dev/null @@ -1,14 +0,0 @@ -

res.attachment([filename])

- -Sets the HTTP response `Content-Disposition` header field to "attachment". If a `filename` is given, -then it sets the Content-Type based on the extension name via `res.type()`, -and sets the `Content-Disposition` "filename=" parameter. - -```js -res.attachment() -// Content-Disposition: attachment - -res.attachment('path/to/logo.png') -// Content-Disposition: attachment; filename="logo.png" -// Content-Type: image/png -``` diff --git a/_includes/api/en/4x/res-clearCookie.md b/_includes/api/en/4x/res-clearCookie.md deleted file mode 100644 index de90e2471b..0000000000 --- a/_includes/api/en/4x/res-clearCookie.md +++ /dev/null @@ -1,14 +0,0 @@ -

res.clearCookie(name [, options])

- -Clears the cookie specified by `name`. For details about the `options` object, see [res.cookie()](#res.cookie). - -
-Web browsers and other compliant clients will only clear the cookie if the given -`options` is identical to those given to [res.cookie()](#res.cookie), excluding -`expires` and `maxAge`. -
- -```js -res.cookie('name', 'tobi', { path: '/admin' }) -res.clearCookie('name', { path: '/admin' }) -``` diff --git a/_includes/api/en/4x/res-cookie.md b/_includes/api/en/4x/res-cookie.md deleted file mode 100644 index 2cd8d32f10..0000000000 --- a/_includes/api/en/4x/res-cookie.md +++ /dev/null @@ -1,83 +0,0 @@ -

res.cookie(name, value [, options])

- -Sets cookie `name` to `value`. The `value` parameter may be a string or object converted to JSON. - -The `options` parameter is an object that can have the following properties. - -| Property | Type | Description | -|---------------|-------------------------------------------------------------------------| -| `domain` | String | Domain name for the cookie. Defaults to the domain name of the app. -| `encode` | Function | A synchronous function used for cookie value encoding. Defaults to `encodeURIComponent`. -| `expires` | Date | Expiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie. -| `httpOnly` | Boolean | Flags the cookie to be accessible only by the web server. -| `maxAge` | Number | Convenient option for setting the expiry time relative to the current time in milliseconds. -| `path` | String | Path for the cookie. Defaults to "/". -| `partitioned` | Boolean | Indicates that the cookie should be stored using partitioned storage. See [Cookies Having Independent Partitioned State (CHIPS)](https://developer.mozilla.org/en-US/docs/Web/Privacy/Partitioned_cookies) for more details. -| `priority` | String | Value of the "Priority" **Set-Cookie** attribute. -| `secure` | Boolean | Marks the cookie to be used with HTTPS only. -| `signed` | Boolean | Indicates if the cookie should be signed. -| `sameSite` | Boolean or String | Value of the "SameSite" **Set-Cookie** attribute. More information at [https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1](https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1). - -
-All `res.cookie()` does is set the HTTP `Set-Cookie` header with the options provided. -Any option not specified defaults to the value stated in [RFC 6265](http://tools.ietf.org/html/rfc6265). -
- -For example: - -```js -res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true }) -res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }) -``` - -You can set multiple cookies in a single response by calling `res.cookie` multiple times, for example: - -```js -res - .status(201) - .cookie('access_token', 'Bearer ' + token, { - expires: new Date(Date.now() + 8 * 3600000) // cookie will be removed after 8 hours - }) - .cookie('test', 'test') - .redirect(301, '/admin') -``` - -The `encode` option allows you to choose the function used for cookie value encoding. -Does not support asynchronous functions. - -Example use case: You need to set a domain-wide cookie for another site in your organization. -This other site (not under your administrative control) does not use URI-encoded cookie values. - -```js -// Default encoding -res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com' }) -// Result: 'some_cross_domain_cookie=http%3A%2F%2Fmysubdomain.example.com; Domain=example.com; Path=/' - -// Custom encoding -res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com', encode: String }) -// Result: 'some_cross_domain_cookie=http://mysubdomain.example.com; Domain=example.com; Path=/;' -``` - -The `maxAge` option is a convenience option for setting "expires" relative to the current time in milliseconds. -The following is equivalent to the second example above. - -```js -res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) -``` - -You can pass an object as the `value` parameter; it is then serialized as JSON and parsed by `bodyParser()` middleware. - -```js -res.cookie('cart', { items: [1, 2, 3] }) -res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 }) -``` - -When using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this method also -supports signed cookies. Simply include the `signed` option set to `true`. -Then `res.cookie()` will use the secret passed to `cookieParser(secret)` to sign the value. - -```js -res.cookie('name', 'tobi', { signed: true }) -``` - -Later you may access this value through the [req.signedCookie](#req.signedCookies) object. diff --git a/_includes/api/en/4x/res-download.md b/_includes/api/en/4x/res-download.md deleted file mode 100644 index 6851716f16..0000000000 --- a/_includes/api/en/4x/res-download.md +++ /dev/null @@ -1,56 +0,0 @@ -

res.download(path [, filename] [, options] [, fn])

- -Transfers the file at `path` as an "attachment". Typically, browsers will prompt the user for download. -By default, the `Content-Disposition` header "filename=" parameter is derived from the `path` argument, but can be overridden with the `filename` parameter. -If `path` is relative, then it will be based on the current working directory of the process or -the `root` option, if provided. - -
-This API provides access to data on the running file system. Ensure that either (a) the way in -which the `path` argument was constructed is secure if it contains user input or (b) set the `root` -option to the absolute path of a directory to contain access within. - -When the `root` option is provided, Express will validate that the relative path provided as -`path` will resolve within the given `root` option. -
- -The following table provides details on the `options` parameter. - -
-The optional `options` argument is supported by Express v4.16.0 onwards. -
- -
- -| Property | Description | Default | Availability | -|-----------------|-------------------------------------------------|-------------|--------------| -| `maxAge` | Sets the max-age property of the `Cache-Control` header in milliseconds or a string in [ms format](https://www.npmjs.org/package/ms)| 0 | 4.16+ | -| `root` | Root directory for relative filenames.| | 4.18+ | -| `lastModified` | Sets the `Last-Modified` header to the last modified date of the file on the OS. Set `false` to disable it.| Enabled | 4.16+ | -| `headers` | Object containing HTTP headers to serve with the file. The header `Content-Disposition` will be overridden by the `filename` argument.| | 4.16+ | -| `dotfiles` | Option for serving dotfiles. Possible values are "allow", "deny", "ignore".| "ignore" | 4.16+ | -| `acceptRanges` | Enable or disable accepting ranged requests. | `true` | 4.16+ | -| `cacheControl` | Enable or disable setting `Cache-Control` response header.| `true` | 4.16+ | -| `immutable` | Enable or disable the `immutable` directive in the `Cache-Control` response header. If enabled, the `maxAge` option should also be specified to enable caching. The `immutable` directive will prevent supported clients from making conditional requests during the life of the `maxAge` option to check if the file has changed. | `false` | 4.16+ | - -
- -The method invokes the callback function `fn(err)` when the transfer is complete -or when an error occurs. If the callback function is specified and an error occurs, -the callback function must explicitly handle the response process either by -ending the request-response cycle, or by passing control to the next route. - -```js -res.download('/report-12345.pdf') - -res.download('/report-12345.pdf', 'report.pdf') - -res.download('/report-12345.pdf', 'report.pdf', function (err) { - if (err) { - // Handle error, but keep in mind the response may be partially-sent - // so check res.headersSent - } else { - // decrement a download credit, etc. - } -}) -``` diff --git a/_includes/api/en/4x/res-end.md b/_includes/api/en/4x/res-end.md deleted file mode 100644 index 2906805fea..0000000000 --- a/_includes/api/en/4x/res-end.md +++ /dev/null @@ -1,10 +0,0 @@ -

res.end([data[, encoding]][, callback])

- -Ends the response process. This method actually comes from Node core, specifically the [response.end() method of http.ServerResponse](https://nodejs.org/api/http.html#responseenddata-encoding-callback). - -Use to quickly end the response without any data. If you need to respond with data, instead use methods such as [res.send()](#res.send) and [res.json()](#res.json). - -```js -res.end() -res.status(404).end() -``` diff --git a/_includes/api/en/4x/res-format.md b/_includes/api/en/4x/res-format.md deleted file mode 100644 index 476a2caea7..0000000000 --- a/_includes/api/en/4x/res-format.md +++ /dev/null @@ -1,52 +0,0 @@ -

res.format(object)

- -Performs content-negotiation on the `Accept` HTTP header on the request object, when present. -It uses [req.accepts()](#req.accepts) to select a handler for the request, based on the acceptable -types ordered by their quality values. If the header is not specified, the first callback is invoked. -When no match is found, the server responds with 406 "Not Acceptable", or invokes the `default` callback. - -The `Content-Type` response header is set when a callback is selected. However, you may alter -this within the callback using methods such as `res.set()` or `res.type()`. - -The following example would respond with `{ "message": "hey" }` when the `Accept` header field is set -to "application/json" or "\*/json" (however if it is "\*/\*", then the response will be "hey"). - -```js -res.format({ - 'text/plain': function () { - res.send('hey') - }, - - 'text/html': function () { - res.send('

hey

') - }, - - 'application/json': function () { - res.send({ message: 'hey' }) - }, - - default: function () { - // log the request and respond with 406 - res.status(406).send('Not Acceptable') - } -}) -``` - -In addition to canonicalized MIME types, you may also use extension names mapped -to these types for a slightly less verbose implementation: - -```js -res.format({ - text: function () { - res.send('hey') - }, - - html: function () { - res.send('

hey

') - }, - - json: function () { - res.send({ message: 'hey' }) - } -}) -``` diff --git a/_includes/api/en/4x/res-get.md b/_includes/api/en/4x/res-get.md deleted file mode 100644 index 8aefb205ef..0000000000 --- a/_includes/api/en/4x/res-get.md +++ /dev/null @@ -1,9 +0,0 @@ -

res.get(field)

- -Returns the HTTP response header specified by `field`. -The match is case-insensitive. - -```js -res.get('Content-Type') -// => "text/plain" -``` diff --git a/_includes/api/en/4x/res-headersSent.md b/_includes/api/en/4x/res-headersSent.md deleted file mode 100644 index 3f7923ee7d..0000000000 --- a/_includes/api/en/4x/res-headersSent.md +++ /dev/null @@ -1,11 +0,0 @@ -

res.headersSent

- -Boolean property that indicates if the app sent HTTP headers for the response. - -```js -app.get('/', function (req, res) { - console.dir(res.headersSent) // false - res.send('OK') - console.dir(res.headersSent) // true -}) -``` diff --git a/_includes/api/en/4x/res-json.md b/_includes/api/en/4x/res-json.md deleted file mode 100644 index 8e699a7ed5..0000000000 --- a/_includes/api/en/4x/res-json.md +++ /dev/null @@ -1,13 +0,0 @@ -

res.json([body])

- -Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a -JSON string using [JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). - -The parameter can be any JSON type, including object, array, string, Boolean, number, or null, -and you can also use it to convert other values to JSON. - -```js -res.json(null) -res.json({ user: 'tobi' }) -res.status(500).json({ error: 'message' }) -``` diff --git a/_includes/api/en/4x/res-jsonp.md b/_includes/api/en/4x/res-jsonp.md deleted file mode 100644 index edb7e45466..0000000000 --- a/_includes/api/en/4x/res-jsonp.md +++ /dev/null @@ -1,32 +0,0 @@ -

res.jsonp([body])

- -Sends a JSON response with JSONP support. This method is identical to `res.json()`, -except that it opts-in to JSONP callback support. - -```js -res.jsonp(null) -// => callback(null) - -res.jsonp({ user: 'tobi' }) -// => callback({ "user": "tobi" }) - -res.status(500).jsonp({ error: 'message' }) -// => callback({ "error": "message" }) -``` - -By default, the JSONP callback name is simply `callback`. Override this with the -jsonp callback name setting. - -The following are some examples of JSONP responses using the same code: - -```js -// ?callback=foo -res.jsonp({ user: 'tobi' }) -// => foo({ "user": "tobi" }) - -app.set('jsonp callback name', 'cb') - -// ?cb=foo -res.status(500).jsonp({ error: 'message' }) -// => foo({ "error": "message" }) -``` diff --git a/_includes/api/en/4x/res-links.md b/_includes/api/en/4x/res-links.md deleted file mode 100644 index 17164155d4..0000000000 --- a/_includes/api/en/4x/res-links.md +++ /dev/null @@ -1,20 +0,0 @@ - - -Joins the `links` provided as properties of the parameter to populate the response's -`Link` HTTP header field. - -For example, the following call: - -```js -res.links({ - next: 'http://api.example.com/users?page=2', - last: 'http://api.example.com/users?page=5' -}) -``` - -Yields the following results: - -``` -Link: ; rel="next", - ; rel="last" -``` diff --git a/_includes/api/en/4x/res-locals.md b/_includes/api/en/4x/res-locals.md deleted file mode 100644 index 38949ea971..0000000000 --- a/_includes/api/en/4x/res-locals.md +++ /dev/null @@ -1,28 +0,0 @@ -

res.locals

- -Use this property to set variables accessible in templates rendered with [res.render](#res.render). -The variables set on `res.locals` are available within a single request-response cycle, and will not -be shared between requests. - -
-The `locals` object is used by view engines to render a response. The object -keys may be particularly sensitive and should not contain user-controlled -input, as it may affect the operation of the view engine or provide a path to -cross-site scripting. Consult the documentation for the used view engine for -additional considerations. -
- -In order to keep local variables for use in template rendering between requests, use -[app.locals](#app.locals) instead. - -This property is useful for exposing request-level information such as the request path name, -authenticated user, user settings, and so on to templates rendered within the application. - -```js -app.use(function (req, res, next) { - // Make `user` and `authenticated` available in templates - res.locals.user = req.user - res.locals.authenticated = !req.user.anonymous - next() -}) -``` diff --git a/_includes/api/en/4x/res-location.md b/_includes/api/en/4x/res-location.md deleted file mode 100644 index ba5e943e6c..0000000000 --- a/_includes/api/en/4x/res-location.md +++ /dev/null @@ -1,22 +0,0 @@ -

res.location(path)

- -Sets the response `Location` HTTP header to the specified `path` parameter. - -```js -res.location('/foo/bar') -res.location('http://example.com') -res.location('back') -``` - -A `path` value of "back" has a special meaning, it refers to the URL specified in the `Referer` header of the request. If the `Referer` header was not specified, it refers to "/". - -See also [Security best practices: Prevent open redirect -vulnerabilities](http://expressjs.com/en/advanced/best-practice-security.html#prevent-open-redirects). - -
-After encoding the URL, if not encoded already, Express passes the specified URL to the browser in the `Location` header, -without any validation. - -Browsers take the responsibility of deriving the intended URL from the current URL -or the referring URL, and the URL specified in the `Location` header; and redirect the user accordingly. -
diff --git a/_includes/api/en/4x/res-redirect.md b/_includes/api/en/4x/res-redirect.md deleted file mode 100644 index d790e55c9a..0000000000 --- a/_includes/api/en/4x/res-redirect.md +++ /dev/null @@ -1,56 +0,0 @@ -

res.redirect([status,] path)

- -Redirects to the URL derived from the specified `path`, with specified `status`, a positive integer -that corresponds to an [HTTP status code](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) . -If not specified, `status` defaults to "302 "Found". - -```js -res.redirect('/foo/bar') -res.redirect('http://example.com') -res.redirect(301, 'http://example.com') -res.redirect('../login') -``` -Redirects can be a fully-qualified URL for redirecting to a different site: - -```js -res.redirect('http://google.com') -``` -Redirects can be relative to the root of the host name. For example, if the -application is on `http://example.com/admin/post/new`, the following -would redirect to the URL `http://example.com/admin`: - -```js -res.redirect('/admin') -``` - -Redirects can be relative to the current URL. For example, -from `http://example.com/blog/admin/` (notice the trailing slash), the following -would redirect to the URL `http://example.com/blog/admin/post/new`. - -```js -res.redirect('post/new') -``` - -Redirecting to `post/new` from `http://example.com/blog/admin` (no trailing slash), -will redirect to `http://example.com/blog/post/new`. - -If you found the above behavior confusing, think of path segments as directories -(with trailing slashes) and files, it will start to make sense. - -Path-relative redirects are also possible. If you were on -`http://example.com/admin/post/new`, the following would redirect to -`http://example.com/admin/post`: - -```js -res.redirect('..') -``` - -A `back` redirection redirects the request back to the [referer](http://en.wikipedia.org/wiki/HTTP_referer), -defaulting to `/` when the referer is missing. - -```js -res.redirect('back') -``` - -See also [Security best practices: Prevent open redirect -vulnerabilities](http://expressjs.com/en/advanced/best-practice-security.html#prevent-open-redirects). diff --git a/_includes/api/en/4x/res-render.md b/_includes/api/en/4x/res-render.md deleted file mode 100644 index 2bcb4e60cb..0000000000 --- a/_includes/api/en/4x/res-render.md +++ /dev/null @@ -1,45 +0,0 @@ -

res.render(view [, locals] [, callback])

- -Renders a `view` and sends the rendered HTML string to the client. -Optional parameters: - -- `locals`, an object whose properties define local variables for the view. -- `callback`, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokes `next(err)` internally. - -The `view` argument is a string that is the file path of the view file to render. This can be an absolute path, or a path relative to the `views` setting. If the path does not contain a file extension, then the `view engine` setting determines the file extension. If the path does contain a file extension, then Express will load the module for the specified template engine (via `require()`) and render it using the loaded module's `__express` function. - -For more information, see [Using template engines with Express](/{{page.lang}}/guide/using-template-engines.html). - -
-The `view` argument performs file system operations like reading a file from -disk and evaluating Node.js modules, and as so for security reasons should not -contain input from the end-user. -
- -
-The `locals` object is used by view engines to render a response. The object -keys may be particularly sensitive and should not contain user-controlled -input, as it may affect the operation of the view engine or provide a path to -cross-site scripting. Consult the documentation for the used view engine for -additional considerations. -
- -
-The local variable `cache` enables view caching. Set it to `true`, -to cache the view during development; view caching is enabled in production by default. -
- -```js -// send the rendered view to the client -res.render('index') - -// if a callback is specified, the rendered HTML string has to be sent explicitly -res.render('index', function (err, html) { - res.send(html) -}) - -// pass a local variable to the view -res.render('user', { name: 'Tobi' }, function (err, html) { - // ... -}) -``` diff --git a/_includes/api/en/4x/res-req.md b/_includes/api/en/4x/res-req.md deleted file mode 100644 index 8763653d9f..0000000000 --- a/_includes/api/en/4x/res-req.md +++ /dev/null @@ -1,4 +0,0 @@ -

res.req

- -This property holds a reference to the request object -that relates to this response object. diff --git a/_includes/api/en/4x/res-send.md b/_includes/api/en/4x/res-send.md deleted file mode 100644 index 8c902e568a..0000000000 --- a/_includes/api/en/4x/res-send.md +++ /dev/null @@ -1,39 +0,0 @@ -

res.send([body])

- -Sends the HTTP response. - -The `body` parameter can be a `Buffer` object, a `String`, an object, `Boolean`, or an `Array`. -For example: - -```js -res.send(Buffer.from('whoop')) -res.send({ some: 'json' }) -res.send('

some html

') -res.status(404).send('Sorry, we cannot find that!') -res.status(500).send({ error: 'something blew up' }) -``` - -This method performs many useful tasks for simple non-streaming responses: -For example, it automatically assigns the `Content-Length` HTTP response header field -(unless previously defined) and provides automatic HEAD and HTTP cache freshness support. - -When the parameter is a `Buffer` object, the method sets the `Content-Type` -response header field to "application/octet-stream", unless previously defined as shown below: - -```js -res.set('Content-Type', 'text/html') -res.send(Buffer.from('

some html

')) -``` - -When the parameter is a `String`, the method sets the `Content-Type` to "text/html": - -```js -res.send('

some html

') -``` - -When the parameter is an `Array` or `Object`, Express responds with the JSON representation: - -```js -res.send({ user: 'tobi' }) -res.send([1, 2, 3]) -``` diff --git a/_includes/api/en/4x/res-sendFile.md b/_includes/api/en/4x/res-sendFile.md deleted file mode 100644 index 7c72613c29..0000000000 --- a/_includes/api/en/4x/res-sendFile.md +++ /dev/null @@ -1,84 +0,0 @@ -

res.sendFile(path [, options] [, fn])

- -
-`res.sendFile()` is supported by Express v4.8.0 onwards. -
- -Transfers the file at the given `path`. Sets the `Content-Type` response HTTP header field -based on the filename's extension. Unless the `root` option is set in -the options object, `path` must be an absolute path to the file. - -
-This API provides access to data on the running file system. Ensure that either (a) the way in -which the `path` argument was constructed into an absolute path is secure if it contains user -input or (b) set the `root` option to the absolute path of a directory to contain access within. - -When the `root` option is provided, the `path` argument is allowed to be a relative path, -including containing `..`. Express will validate that the relative path provided as `path` will -resolve within the given `root` option. -
- -The following table provides details on the `options` parameter. - -
- -| Property | Description | Default | Availability | -|-----------------|-------------------------------------------------|-------------|--------------| -|`maxAge` | Sets the max-age property of the `Cache-Control` header in milliseconds or a string in [ms format](https://www.npmjs.org/package/ms)| 0 | | -| `root` | Root directory for relative filenames.| | | -| `lastModified` | Sets the `Last-Modified` header to the last modified date of the file on the OS. Set `false` to disable it.| Enabled | 4.9.0+ | -| `headers` | Object containing HTTP headers to serve with the file.| | | -| `dotfiles` | Option for serving dotfiles. Possible values are "allow", "deny", "ignore".| "ignore" |   | -| `acceptRanges` | Enable or disable accepting ranged requests. | `true` | 4.14+ | -| `cacheControl` | Enable or disable setting `Cache-Control` response header.| `true` | 4.14+ | -| `immutable` | Enable or disable the `immutable` directive in the `Cache-Control` response header. If enabled, the `maxAge` option should also be specified to enable caching. The `immutable` directive will prevent supported clients from making conditional requests during the life of the `maxAge` option to check if the file has changed. | `false` | 4.16+ | - -
- -The method invokes the callback function `fn(err)` when the transfer is complete -or when an error occurs. If the callback function is specified and an error occurs, -the callback function must explicitly handle the response process either by -ending the request-response cycle, or by passing control to the next route. - -Here is an example of using `res.sendFile` with all its arguments. - -```js -app.get('/file/:name', function (req, res, next) { - var options = { - root: path.join(__dirname, 'public'), - dotfiles: 'deny', - headers: { - 'x-timestamp': Date.now(), - 'x-sent': true - } - } - - var fileName = req.params.name - res.sendFile(fileName, options, function (err) { - if (err) { - next(err) - } else { - console.log('Sent:', fileName) - } - }) -}) -``` - -The following example illustrates using -`res.sendFile` to provide fine-grained support for serving files: - -```js -app.get('/user/:uid/photos/:file', function (req, res) { - var uid = req.params.uid - var file = req.params.file - - req.user.mayViewFilesFrom(uid, function (yes) { - if (yes) { - res.sendFile('/uploads/' + uid + '/' + file) - } else { - res.status(403).send("Sorry! You can't see that.") - } - }) -}) -``` -For more information, or if you have issues or concerns, see [send](https://github.com/pillarjs/send). diff --git a/_includes/api/en/4x/res-sendStatus.md b/_includes/api/en/4x/res-sendStatus.md deleted file mode 100644 index 4439f0216d..0000000000 --- a/_includes/api/en/4x/res-sendStatus.md +++ /dev/null @@ -1,15 +0,0 @@ -

res.sendStatus(statusCode)

- -Sets the response HTTP status code to `statusCode` and sends the registered status message as the text response body. If an unknown status code is specified, the response body will just be the code number. - -```js -res.sendStatus(404) -``` - -
-Some versions of Node.js will throw when `res.statusCode` is set to an -invalid HTTP status code (outside of the range `100` to `599`). Consult -the HTTP server documentation for the Node.js version being used. -
- -[More about HTTP Status Codes](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) diff --git a/_includes/api/en/4x/res-set.md b/_includes/api/en/4x/res-set.md deleted file mode 100644 index b91698d4b1..0000000000 --- a/_includes/api/en/4x/res-set.md +++ /dev/null @@ -1,16 +0,0 @@ -

res.set(field [, value])

- -Sets the response's HTTP header `field` to `value`. -To set multiple fields at once, pass an object as the parameter. - -```js -res.set('Content-Type', 'text/plain') - -res.set({ - 'Content-Type': 'text/plain', - 'Content-Length': '123', - ETag: '12345' -}) -``` - -Aliased as `res.header(field [, value])`. diff --git a/_includes/api/en/4x/res-status.md b/_includes/api/en/4x/res-status.md deleted file mode 100644 index 9cb9d44e94..0000000000 --- a/_includes/api/en/4x/res-status.md +++ /dev/null @@ -1,10 +0,0 @@ -

res.status(code)

- -Sets the HTTP status for the response. -It is a chainable alias of Node's [response.statusCode](http://nodejs.org/api/http.html#http_response_statuscode). - -```js -res.status(403).end() -res.status(400).send('Bad Request') -res.status(404).sendFile('/absolute/path/to/404.png') -``` diff --git a/_includes/api/en/4x/res-type.md b/_includes/api/en/4x/res-type.md deleted file mode 100644 index 49468cbad7..0000000000 --- a/_includes/api/en/4x/res-type.md +++ /dev/null @@ -1,16 +0,0 @@ -

res.type(type)

- -Sets the `Content-Type` HTTP header to the MIME type as determined by the specified `type`. If `type` contains the "/" character, then it sets the `Content-Type` to the exact value of `type`, otherwise it is assumed to be a file extension and the MIME type is looked up in a mapping using the `express.static.mime.lookup()` method. - -```js -res.type('.html') -// => 'text/html' -res.type('html') -// => 'text/html' -res.type('json') -// => 'application/json' -res.type('application/json') -// => 'application/json' -res.type('png') -// => 'image/png' -``` diff --git a/_includes/api/en/4x/res-vary.md b/_includes/api/en/4x/res-vary.md deleted file mode 100644 index 956aab25ae..0000000000 --- a/_includes/api/en/4x/res-vary.md +++ /dev/null @@ -1,7 +0,0 @@ -

res.vary(field)

- -Adds the field to the `Vary` response header, if it is not there already. - -```js -res.vary('User-Agent').render('docs') -``` diff --git a/_includes/api/en/4x/res.md b/_includes/api/en/4x/res.md deleted file mode 100644 index 3af14b5ee5..0000000000 --- a/_includes/api/en/4x/res.md +++ /dev/null @@ -1,130 +0,0 @@ -

Response

- -The `res` object represents the HTTP response that an Express app sends when it gets an HTTP request. - -In this documentation and by convention, -the object is always referred to as `res` (and the HTTP request is `req`) but its actual name is determined -by the parameters to the callback function in which you're working. - -For example: - -```js -app.get('/user/:id', function (req, res) { - res.send('user ' + req.params.id) -}) -``` - -But you could just as well have: - -```js -app.get('/user/:id', function (request, response) { - response.send('user ' + request.params.id) -}) -``` - -The `res` object is an enhanced version of Node's own response object -and supports all [built-in fields and methods](https://nodejs.org/api/http.html#http_class_http_serverresponse). - -

Properties

- -
- {% include api/en/4x/res-app.md %} -
- -
- {% include api/en/4x/res-headersSent.md %} -
- -
- {% include api/en/4x/res-locals.md %} -
- -

Methods

- -
- {% include api/en/4x/res-append.md %} -
- -
- {% include api/en/4x/res-attachment.md %} -
- -
- {% include api/en/4x/res-cookie.md %} -
- -
- {% include api/en/4x/res-clearCookie.md %} -
- -
- {% include api/en/4x/res-download.md %} -
- -
- {% include api/en/4x/res-end.md %} -
- -
- {% include api/en/4x/res-format.md %} -
- -
- {% include api/en/4x/res-get.md %} -
- -
- {% include api/en/4x/res-json.md %} -
- -
- {% include api/en/4x/res-jsonp.md %} -
- -
- {% include api/en/4x/res-links.md %} -
- -
- {% include api/en/4x/res-location.md %} -
- -
- {% include api/en/4x/res-redirect.md %} -
- -
- {% include api/en/4x/res-render.md %} -
- -
- {% include api/en/4x/res-req.md %} -
- -
- {% include api/en/4x/res-send.md %} -
- -
- {% include api/en/4x/res-sendFile.md %} -
- -
- {% include api/en/4x/res-sendStatus.md %} -
- -
- {% include api/en/4x/res-set.md %} -
- -
- {% include api/en/4x/res-status.md %} -
- -
- {% include api/en/4x/res-type.md %} -
- -
- {% include api/en/4x/res-vary.md %} -
diff --git a/_includes/api/en/4x/router-METHOD.md b/_includes/api/en/4x/router-METHOD.md deleted file mode 100644 index 82dd5fc866..0000000000 --- a/_includes/api/en/4x/router-METHOD.md +++ /dev/null @@ -1,42 +0,0 @@ -

router.METHOD(path, [callback, ...] callback)

- -The `router.METHOD()` methods provide the routing functionality in Express, -where METHOD is one of the HTTP methods, such as GET, PUT, POST, and so on, -in lowercase. Thus, the actual methods are `router.get()`, `router.post()`, -`router.put()`, and so on. - -
- The `router.get()` function is automatically called for the HTTP `HEAD` method in - addition to the `GET` method if `router.head()` was not called for the - path before `router.get()`. -
- -You can provide multiple callbacks, and all are treated equally, and behave just -like middleware, except that these callbacks may invoke `next('route')` -to bypass the remaining route callback(s). You can use this mechanism to perform -pre-conditions on a route then pass control to subsequent routes when there is no -reason to proceed with the route matched. - -The following snippet illustrates the most simple route definition possible. -Express translates the path strings to regular expressions, used internally -to match incoming requests. Query strings are _not_ considered when performing -these matches, for example "GET /" would match the following route, as would -"GET /?name=tobi". - -```js -router.get('/', function (req, res) { - res.send('hello world') -}) -``` - -You can also use regular expressions—useful if you have very specific -constraints, for example the following would match "GET /commits/71dbb9c" as well -as "GET /commits/71dbb9c..4c084f9". - -```js -router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function (req, res) { - var from = req.params[0] - var to = req.params[1] || 'HEAD' - res.send('commit range ' + from + '..' + to) -}) -``` diff --git a/_includes/api/en/4x/router-Router.md b/_includes/api/en/4x/router-Router.md deleted file mode 100644 index 664ffb34c2..0000000000 --- a/_includes/api/en/4x/router-Router.md +++ /dev/null @@ -1,2 +0,0 @@ -

Router([options])

- diff --git a/_includes/api/en/4x/router-all.md b/_includes/api/en/4x/router-all.md deleted file mode 100644 index 7fe32b156b..0000000000 --- a/_includes/api/en/4x/router-all.md +++ /dev/null @@ -1,31 +0,0 @@ -

router.all(path, [callback, ...] callback)

- -This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs). - -This method is extremely useful for -mapping "global" logic for specific path prefixes or arbitrary matches. -For example, if you placed the following route at the top of all other -route definitions, it would require that all routes from that point on -would require authentication, and automatically load a user. Keep in mind -that these callbacks do not have to act as end points; `loadUser` -can perform a task, then call `next()` to continue matching subsequent -routes. - -```js -router.all('*', requireAuthentication, loadUser) -``` - -Or the equivalent: - -```js -router.all('*', requireAuthentication) -router.all('*', loadUser) -``` - -Another example of this is white-listed "global" functionality. Here -the example is much like before, but it only restricts paths prefixed with -"/api": - -```js -router.all('/api/*', requireAuthentication) -``` diff --git a/_includes/api/en/4x/router-param.md b/_includes/api/en/4x/router-param.md deleted file mode 100644 index 20b35d1afe..0000000000 --- a/_includes/api/en/4x/router-param.md +++ /dev/null @@ -1,123 +0,0 @@ -

router.param(name, callback)

- -Adds callback triggers to route parameters, where `name` is the name of the parameter and `callback` is the callback function. Although `name` is technically optional, using this method without it is deprecated starting with Express v4.11.0 (see below). - -The parameters of the callback function are: - -- `req`, the request object. -- `res`, the response object. -- `next`, indicating the next middleware function. -- The value of the `name` parameter. -- The name of the parameter. - -
-Unlike `app.param()`, `router.param()` does not accept an array of route parameters. -
- -For example, when `:user` is present in a route path, you may map user loading logic to automatically provide `req.user` to the route, or perform validations on the parameter input. - -```js -router.param('user', function (req, res, next, id) { - // try to get the user details from the User model and attach it to the request object - User.find(id, function (err, user) { - if (err) { - next(err) - } else if (user) { - req.user = user - next() - } else { - next(new Error('failed to load user')) - } - }) -}) -``` - -Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers, nor are they triggered for route parameters inherited from parent routers. Hence, param callbacks defined on `router` will be triggered only by route parameters defined on `router` routes. - -A param callback will be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples. - -```js -router.param('id', function (req, res, next, id) { - console.log('CALLED ONLY ONCE') - next() -}) - -router.get('/user/:id', function (req, res, next) { - console.log('although this matches') - next() -}) - -router.get('/user/:id', function (req, res) { - console.log('and this matches too') - res.end() -}) -``` - -On `GET /user/42`, the following is printed: - -``` -CALLED ONLY ONCE -although this matches -and this matches too -``` - -
-The following section describes `router.param(callback)`, which is deprecated as of v4.11.0. -
- -The behavior of the `router.param(name, callback)` method can be altered entirely by passing only a function to `router.param()`. This function is a custom implementation of how `router.param(name, callback)` should behave - it accepts two parameters and must return a middleware. - -The first parameter of this function is the name of the URL parameter that should be captured, the second parameter can be any JavaScript object which might be used for returning the middleware implementation. - -The middleware returned by the function decides the behavior of what happens when a URL parameter is captured. - -In this example, the `router.param(name, callback)` signature is modified to `router.param(name, accessId)`. Instead of accepting a name and a callback, `router.param()` will now accept a name and a number. - -```js -var express = require('express') -var app = express() -var router = express.Router() - -// customizing the behavior of router.param() -router.param(function (param, option) { - return function (req, res, next, val) { - if (val === option) { - next() - } else { - res.sendStatus(403) - } - } -}) - -// using the customized router.param() -router.param('id', '1337') - -// route to trigger the capture -router.get('/user/:id', function (req, res) { - res.send('OK') -}) - -app.use(router) - -app.listen(3000, function () { - console.log('Ready') -}) -``` - -In this example, the `router.param(name, callback)` signature remains the same, but instead of a middleware callback, a custom data type checking function has been defined to validate the data type of the user id. - -```js -router.param(function (param, validator) { - return function (req, res, next, val) { - if (validator(val)) { - next() - } else { - res.sendStatus(403) - } - } -}) - -router.param('id', function (candidate) { - return !isNaN(parseFloat(candidate)) && isFinite(candidate) -}) -``` diff --git a/_includes/api/en/4x/router-route.md b/_includes/api/en/4x/router-route.md deleted file mode 100644 index 0f03d39adc..0000000000 --- a/_includes/api/en/4x/router-route.md +++ /dev/null @@ -1,48 +0,0 @@ -

router.route(path)

- -Returns an instance of a single route which you can then use to handle HTTP verbs -with optional middleware. Use `router.route()` to avoid duplicate route naming and -thus typing errors. - -Building on the `router.param()` example above, the following code shows how to use -`router.route()` to specify various HTTP method handlers. - -```js -var router = express.Router() - -router.param('user_id', function (req, res, next, id) { - // sample user, would actually fetch from DB, etc... - req.user = { - id: id, - name: 'TJ' - } - next() -}) - -router.route('/users/:user_id') - .all(function (req, res, next) { - // runs for all HTTP verbs first - // think of it as route specific middleware! - next() - }) - .get(function (req, res, next) { - res.json(req.user) - }) - .put(function (req, res, next) { - // just an example of maybe updating the user - req.user.name = req.params.name - // save user ... etc - res.json(req.user) - }) - .post(function (req, res, next) { - next(new Error('not implemented')) - }) - .delete(function (req, res, next) { - next(new Error('not implemented')) - }) -``` - -This approach re-uses the single `/users/:user_id` path and adds handlers for -various HTTP methods. - -{% include admonitions/note.html content="When you use `router.route()`, middleware ordering is based on when the _route_ is created, not when method handlers are added to the route. For this purpose, you can consider method handlers to belong to the route to which they were added." %} diff --git a/_includes/api/en/4x/router-use.md b/_includes/api/en/4x/router-use.md deleted file mode 100644 index 776a112fa0..0000000000 --- a/_includes/api/en/4x/router-use.md +++ /dev/null @@ -1,107 +0,0 @@ -

router.use([path], [function, ...] function)

- -Uses the specified middleware function or functions, with optional mount path `path`, that defaults to "/". - -This method is similar to [app.use()](#app.use). A simple example and use case is described below. -See [app.use()](#app.use) for more information. - -Middleware is like a plumbing pipe: requests start at the first middleware function defined -and work their way "down" the middleware stack processing for each path they match. - -```js -var express = require('express') -var app = express() -var router = express.Router() - -// simple logger for this router's requests -// all requests to this router will first hit this middleware -router.use(function (req, res, next) { - console.log('%s %s %s', req.method, req.url, req.path) - next() -}) - -// this will only be invoked if the path starts with /bar from the mount point -router.use('/bar', function (req, res, next) { - // ... maybe some additional /bar logging ... - next() -}) - -// always invoked -router.use(function (req, res, next) { - res.send('Hello World') -}) - -app.use('/foo', router) - -app.listen(3000) -``` - -The "mount" path is stripped and is _not_ visible to the middleware function. -The main effect of this feature is that a mounted middleware function may operate without -code changes regardless of its "prefix" pathname. - -The order in which you define middleware with `router.use()` is very important. -They are invoked sequentially, thus the order defines middleware precedence. For example, -usually a logger is the very first middleware you would use, so that every request gets logged. - -```js -var logger = require('morgan') -var path = require('path') - -router.use(logger()) -router.use(express.static(path.join(__dirname, 'public'))) -router.use(function (req, res) { - res.send('Hello') -}) -``` - -Now suppose you wanted to ignore logging requests for static files, but to continue -logging routes and middleware defined after `logger()`. You would simply move the call to `express.static()` to the top, -before adding the logger middleware: - -```js -router.use(express.static(path.join(__dirname, 'public'))) -router.use(logger()) -router.use(function (req, res) { - res.send('Hello') -}) -``` - -Another example is serving files from multiple directories, -giving precedence to "./public" over the others: - -```js -router.use(express.static(path.join(__dirname, 'public'))) -router.use(express.static(path.join(__dirname, 'files'))) -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_ -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: - -```js -var authRouter = express.Router() -var openRouter = express.Router() - -authRouter.use(require('./authenticate').basic(usersdb)) - -authRouter.get('/:user_id/edit', function (req, res, next) { - // ... Edit user UI ... -}) -openRouter.get('/', function (req, res, next) { - // ... List users ... -}) -openRouter.get('/:user_id', function (req, res, next) { - // ... View user ... -}) - -app.use('/users', authRouter) -app.use('/users', openRouter) -``` - -Even though the authentication middleware was added via the `authRouter` it will run on the routes defined by the `openRouter` as well since both routers were mounted on `/users`. To avoid this behavior, use different paths for each router. diff --git a/_includes/api/en/4x/router.md b/_includes/api/en/4x/router.md deleted file mode 100644 index 4198420a59..0000000000 --- a/_includes/api/en/4x/router.md +++ /dev/null @@ -1,62 +0,0 @@ -

Router

- -
-A `router` object is an instance of middleware and routes. You can think of it -as a "mini-application," capable only of performing middleware and routing -functions. Every Express application has a built-in app router. - -A router behaves like middleware itself, so you can use it as an argument to -[app.use()](#app.use) or as the argument to another router's [use()](#router.use) method. - -The top-level `express` object has a [Router()](#express.router) method that creates a new `router` object. - -Once you've created a router object, you can add middleware and HTTP method routes (such as `get`, `put`, `post`, -and so on) to it just like an application. For example: - -```js -// invoked for any requests passed to this router -router.use(function (req, res, next) { - // .. some logic here .. like any other middleware - next() -}) - -// will handle any request that ends in /events -// depends on where the router is "use()'d" -router.get('/events', function (req, res, next) { - // .. -}) -``` - -You can then use a router for a particular root URL in this way separating your routes into files or even mini-apps. - -```js -// only requests to /calendar/* will be sent to our "router" -app.use('/calendar', router) -``` - -Keep in mind that any middleware applied to a router will run for all requests on that router's path, even those that aren't part of the router. - - -
- -

Methods

- -
- {% include api/en/4x/router-all.md %} -
- -
- {% include api/en/4x/router-METHOD.md %} -
- -
- {% include api/en/4x/router-param.md %} -
- -
- {% include api/en/4x/router-route.md %} -
- -
- {% include api/en/4x/router-use.md %} -
diff --git a/_includes/api/en/4x/routing-args.html b/_includes/api/en/4x/routing-args.html deleted file mode 100644 index 4a3bc6fefe..0000000000 --- a/_includes/api/en/4x/routing-args.html +++ /dev/null @@ -1,49 +0,0 @@ -

Arguments

- - - - - - - - - - - - - - - - - - -
Argument Description Default
path -The path for which the middleware function is invoked; can be any of: -
    -
  • A string representing a path.
  • -
  • A path pattern.
  • -
  • A regular expression pattern to match paths.
  • -
  • An array of combinations of any of the above.
  • -
- -For examples, see Path examples. -
'/' (root path)
callback -Callback functions; can be: -
    -
  • A middleware function.
  • -
  • A series of middleware functions (separated by commas).
  • -
  • An array of middleware functions.
  • -
  • A combination of all of the above.
  • -
-

-You can provide multiple callback functions that behave just like middleware, except -that these callbacks can invoke next('route') to bypass -the remaining route callback(s). You can use this mechanism to impose pre-conditions -on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. -

-Since router and app implement the middleware interface, -you can use them as you would any other middleware function. -

-For examples, see Middleware callback function examples. -

-
None
diff --git a/_includes/api/en/5x/app-METHOD.md b/_includes/api/en/5x/app-METHOD.md deleted file mode 100644 index 0c7cc6f1ac..0000000000 --- a/_includes/api/en/5x/app-METHOD.md +++ /dev/null @@ -1,62 +0,0 @@ -

app.METHOD(path, callback [, callback ...])

- -Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET, -PUT, POST, and so on, in lowercase. Thus, the actual methods are `app.get()`, -`app.post()`, `app.put()`, and so on. See [Routing methods](#routing-methods) below for the complete list. - -{% include api/en/5x/routing-args.html %} - -#### Routing methods - -Express supports the following routing methods corresponding to the HTTP methods of the same names: - - - - - - - -
-* `checkout` -* `copy` -* `delete` -* `get` -* `head` -* `lock` -* `merge` -* `mkactivity` - -* `mkcol` -* `move` -* `m-search` -* `notify` -* `options` -* `patch` -* `post` - -* `purge` -* `put` -* `report` -* `search` -* `subscribe` -* `trace` -* `unlock` -* `unsubscribe` -
- -The API documentation has explicit entries only for the most popular HTTP methods `app.get()`, -`app.post()`, `app.put()`, and `app.delete()`. -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 ...`. - -
- The `app.get()` function is automatically called for the HTTP `HEAD` method in addition to the `GET` - method if `app.head()` was not called for the path before `app.get()`. -
- -The method, `app.all()`, is not derived from any HTTP method and loads middleware at -the specified path for _all_ HTTP request methods. -For more information, see [app.all](#app.all). - -For more information on routing, see the [routing guide](/{{page.lang}}/guide/routing.html). diff --git a/_includes/api/en/5x/app-all.md b/_includes/api/en/5x/app-all.md deleted file mode 100644 index fc8534b5d1..0000000000 --- a/_includes/api/en/5x/app-all.md +++ /dev/null @@ -1,44 +0,0 @@ -

app.all(path, callback [, callback ...])

- -This method is like the standard [app.METHOD()](#app.METHOD) methods, -except it matches all HTTP verbs. - -{% include api/en/5x/routing-args.html %} - -#### Examples - -The following callback is executed for requests to `/secret` whether using -GET, POST, PUT, DELETE, or any other HTTP request method: - -```js -app.all('/secret', (req, res, next) => { - console.log('Accessing the secret section ...') - next() // pass control to the next handler -}) -``` - -The `app.all()` method is useful for mapping "global" logic for specific path prefixes or arbitrary matches. For example, if you put the following at the top of all other -route definitions, it requires that all routes from that point on -require authentication, and automatically load a user. Keep in mind -that these callbacks do not have to act as end-points: `loadUser` -can perform a task, then call `next()` to continue matching subsequent -routes. - -```js -app.all('(.*)', requireAuthentication, loadUser) -``` - -Or the equivalent: - -```js -app.all('(.*)', requireAuthentication) -app.all('(.*)', loadUser) -``` - -Another example is white-listed "global" functionality. -The example is similar to the ones above, but it only restricts paths that start with -"/api": - -```js -app.all('/api/(.*)', requireAuthentication) -``` diff --git a/_includes/api/en/5x/app-delete-method.md b/_includes/api/en/5x/app-delete-method.md deleted file mode 100644 index 3a08590fd0..0000000000 --- a/_includes/api/en/5x/app-delete-method.md +++ /dev/null @@ -1,14 +0,0 @@ -

app.delete(path, callback [, callback ...])

- -Routes HTTP DELETE requests to the specified path with the specified callback functions. -For more information, see the [routing guide](/{{page.lang}}/guide/routing.html). - -{% include api/en/5x/routing-args.html %} - -#### Example - -```js -app.delete('/', (req, res) => { - res.send('DELETE request to homepage') -}) -``` diff --git a/_includes/api/en/5x/app-disable.md b/_includes/api/en/5x/app-disable.md deleted file mode 100644 index 08bbcf11ba..0000000000 --- a/_includes/api/en/5x/app-disable.md +++ /dev/null @@ -1,12 +0,0 @@ -

app.disable(name)

- -Sets the Boolean setting `name` to `false`, where `name` is one of the properties from the [app settings table](#app.settings.table). -Calling `app.set('foo', false)` for a Boolean property is the same as calling `app.disable('foo')`. - -For example: - -```js -app.disable('trust proxy') -app.get('trust proxy') -// => false -``` diff --git a/_includes/api/en/5x/app-disabled.md b/_includes/api/en/5x/app-disabled.md deleted file mode 100644 index 370048fde6..0000000000 --- a/_includes/api/en/5x/app-disabled.md +++ /dev/null @@ -1,13 +0,0 @@ -

app.disabled(name)

- -Returns `true` if the Boolean setting `name` is disabled (`false`), where `name` is one of the properties from -the [app settings table](#app.settings.table). - -```js -app.disabled('trust proxy') -// => true - -app.enable('trust proxy') -app.disabled('trust proxy') -// => false -``` diff --git a/_includes/api/en/5x/app-enable.md b/_includes/api/en/5x/app-enable.md deleted file mode 100644 index 1152335a4c..0000000000 --- a/_includes/api/en/5x/app-enable.md +++ /dev/null @@ -1,10 +0,0 @@ -

app.enable(name)

- -Sets the Boolean setting `name` to `true`, where `name` is one of the properties from the [app settings table](#app.settings.table). -Calling `app.set('foo', true)` for a Boolean property is the same as calling `app.enable('foo')`. - -```js -app.enable('trust proxy') -app.get('trust proxy') -// => true -``` diff --git a/_includes/api/en/5x/app-enabled.md b/_includes/api/en/5x/app-enabled.md deleted file mode 100644 index ad9b17aa89..0000000000 --- a/_includes/api/en/5x/app-enabled.md +++ /dev/null @@ -1,13 +0,0 @@ -

app.enabled(name)

- -Returns `true` if the setting `name` is enabled (`true`), where `name` is one of the -properties from the [app settings table](#app.settings.table). - -```js -app.enabled('trust proxy') -// => false - -app.enable('trust proxy') -app.enabled('trust proxy') -// => true -``` diff --git a/_includes/api/en/5x/app-engine.md b/_includes/api/en/5x/app-engine.md deleted file mode 100644 index 1314b0586e..0000000000 --- a/_includes/api/en/5x/app-engine.md +++ /dev/null @@ -1,36 +0,0 @@ -

app.engine(ext, callback)

- -Registers the given template engine `callback` as `ext`. - -By default, Express will `require()` the engine based on the file extension. -For example, if you try to render a "foo.pug" file, Express invokes the -following internally, and caches the `require()` on subsequent calls to increase -performance. - -```js -app.engine('pug', require('pug').__express) -``` - -Use this method for engines that do not provide `.__express` out of the box, -or if you wish to "map" a different extension to the template engine. - -For example, to map the EJS template engine to ".html" files: - -```js -app.engine('html', require('ejs').renderFile) -``` - -In this case, EJS provides a `.renderFile()` method with -the same signature that Express expects: `(path, options, callback)`, -though note that it aliases this method as `ejs.__express` internally -so if you're using ".ejs" extensions you don't need to do anything. - -Some template engines do not follow this convention. The -[consolidate.js](https://github.com/tj/consolidate.js) library maps Node template engines to follow this convention, -so they work seamlessly with Express. - -```js -const engines = require('consolidate') -app.engine('haml', engines.haml) -app.engine('html', engines.hogan) -``` diff --git a/_includes/api/en/5x/app-get-method.md b/_includes/api/en/5x/app-get-method.md deleted file mode 100644 index 99b91354d6..0000000000 --- a/_includes/api/en/5x/app-get-method.md +++ /dev/null @@ -1,15 +0,0 @@ -

app.get(path, callback [, callback ...])

- -Routes HTTP GET requests to the specified path with the specified callback functions. - -{% include api/en/5x/routing-args.html %} - -For more information, see the [routing guide](/{{page.lang}}/guide/routing.html). - -#### Example - -```js -app.get('/', (req, res) => { - res.send('GET request to homepage') -}) -``` diff --git a/_includes/api/en/5x/app-get.md b/_includes/api/en/5x/app-get.md deleted file mode 100644 index c93ef34d70..0000000000 --- a/_includes/api/en/5x/app-get.md +++ /dev/null @@ -1,13 +0,0 @@ -

app.get(name)

- -Returns the value of `name` app setting, where `name` is one of the strings in the -[app settings table](#app.settings.table). For example: - -```js -app.get('title') -// => undefined - -app.set('title', 'My Site') -app.get('title') -// => "My Site" -``` diff --git a/_includes/api/en/5x/app-listen.md b/_includes/api/en/5x/app-listen.md deleted file mode 100644 index 7135d69074..0000000000 --- a/_includes/api/en/5x/app-listen.md +++ /dev/null @@ -1,51 +0,0 @@ -

app.listen(path, [callback])

- -Starts a UNIX socket and listens for connections on the given path. -This method is identical to Node's [http.Server.listen()](https://nodejs.org/api/http.html#http_server_listen). - -```js -const express = require('express') -const app = express() -app.listen('/tmp/sock') -``` - -

app.listen([port[, host[, backlog]]][, callback])

- -Binds and listens for connections on the specified host and port. -This method is identical to Node's [http.Server.listen()](https://nodejs.org/api/http.html#http_server_listen). - -If port is omitted or is 0, the operating system will assign an arbitrary unused -port, which is useful for cases like automated tasks (tests, etc.). - -```js -const express = require('express') -const app = express() -app.listen(3000) -``` - -The `app` returned by `express()` is in fact a JavaScript -`Function`, designed to be passed to Node's HTTP servers as a callback -to handle requests. This makes it easy to provide both HTTP and HTTPS versions of -your app with the same code base, as the app does not inherit from these -(it is simply a callback): - -```js -const express = require('express') -const https = require('https') -const http = require('http') -const app = express() - -http.createServer(app).listen(80) -https.createServer(options, app).listen(443) -``` - -The `app.listen()` method returns an [http.Server](https://nodejs.org/api/http.html#http_class_http_server) object and (for HTTP) is a convenience method for the following: - -```js -app.listen = function () { - const server = http.createServer(this) - return server.listen.apply(server, arguments) -} -``` - -{% include admonitions/note.html content="All the forms of Node's [http.Server.listen()](https://nodejs.org/api/http.html#http_server_listen) method are in fact actually supported." %} diff --git a/_includes/api/en/5x/app-locals.md b/_includes/api/en/5x/app-locals.md deleted file mode 100644 index 720c50a96d..0000000000 --- a/_includes/api/en/5x/app-locals.md +++ /dev/null @@ -1,26 +0,0 @@ -

app.locals

- -The `app.locals` object has properties that are local variables within the application, -and will be available in templates rendered with [res.render](#res.render). - -```js -console.dir(app.locals.title) -// => 'My App' - -console.dir(app.locals.email) -// => 'me@myapp.com' -``` - -Once set, the value of `app.locals` properties persist throughout the life of the application, -in contrast with [res.locals](#res.locals) properties that -are valid only for the lifetime of the request. - -You can access local variables in templates rendered within the application. -This is useful for providing helper functions to templates, as well as application-level data. -Local variables are available in middleware via `req.app.locals` (see [req.app](#req.app)) - -```js -app.locals.title = 'My App' -app.locals.strftime = require('strftime') -app.locals.email = 'me@myapp.com' -``` diff --git a/_includes/api/en/5x/app-mountpath.md b/_includes/api/en/5x/app-mountpath.md deleted file mode 100644 index 5a41877f71..0000000000 --- a/_includes/api/en/5x/app-mountpath.md +++ /dev/null @@ -1,45 +0,0 @@ -

app.mountpath

- -The `app.mountpath` property contains one or more path patterns on which a sub-app was mounted. - -
- A sub-app is an instance of `express` that may be used for handling the request to a route. -
- -```js -const express = require('express') - -const app = express() // the main app -const admin = express() // the sub app - -admin.get('/', (req, res) => { - console.log(admin.mountpath) // /admin - res.send('Admin Homepage') -}) - -app.use('/admin', admin) // mount the sub app -``` - -It is similar to the [baseUrl](#req.baseUrl) property of the `req` object, except `req.baseUrl` -returns the matched URL path, instead of the matched patterns. - -If a sub-app is mounted on multiple path patterns, `app.mountpath` returns the list of -patterns it is mounted on, as shown in the following example. - -```js -const admin = express() - -admin.get('/', (req, res) => { - console.log(admin.mountpath) // [ '/adm*n', '/manager' ] - res.send('Admin Homepage') -}) - -const secret = express() -secret.get('/', (req, res) => { - console.log(secret.mountpath) // /secr*t - res.send('Admin Secret') -}) - -admin.use('/secr*t', secret) // load the 'secret' router on '/secr*t', on the 'admin' sub app -app.use(['/adm*n', '/manager'], admin) // load the 'admin' router on '/adm*n' and '/manager', on the parent app -``` diff --git a/_includes/api/en/5x/app-onmount.md b/_includes/api/en/5x/app-onmount.md deleted file mode 100644 index 80e38520eb..0000000000 --- a/_includes/api/en/5x/app-onmount.md +++ /dev/null @@ -1,29 +0,0 @@ -

app.on('mount', callback(parent))

- -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: - -* 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. - -For details, see [Application settings](/en/5x/api.html#app.settings.table). -
- -```js -const admin = express() - -admin.on('mount', (parent) => { - console.log('Admin Mounted') - console.log(parent) // refers to the parent app -}) - -admin.get('/', (req, res) => { - res.send('Admin Homepage') -}) - -app.use('/admin', admin) -``` diff --git a/_includes/api/en/5x/app-param.md b/_includes/api/en/5x/app-param.md deleted file mode 100644 index a1e064add2..0000000000 --- a/_includes/api/en/5x/app-param.md +++ /dev/null @@ -1,78 +0,0 @@ -

app.param(name, callback)

- -Add callback triggers to [route parameters](/{{ page.lang }}/guide/routing.html#route-parameters), where `name` is the name of the parameter or an array of them, and `callback` is the callback function. The parameters of the callback function are the request object, the response object, the next middleware, the value of the parameter and the name of the parameter, in that order. - -If `name` is an array, the `callback` trigger is registered for each parameter declared in it, in the order in which they are declared. Furthermore, for each declared parameter except the last one, a call to `next` inside the callback will call the callback for the next declared parameter. For the last parameter, a call to `next` will call the next middleware in place for the route currently being processed, just like it would if `name` were just a string. - -For example, when `:user` is present in a route path, you may map user loading logic to automatically provide `req.user` to the route, or perform validations on the parameter input. - -```js -app.param('user', (req, res, next, id) => { - // try to get the user details from the User model and attach it to the request object - User.find(id, (err, user) => { - if (err) { - next(err) - } else if (user) { - req.user = user - next() - } else { - next(new Error('failed to load user')) - } - }) -}) -``` - -Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers, nor are they triggered for route parameters inherited from parent routers. Hence, param callbacks defined on `app` will be triggered only by route parameters defined on `app` routes. - -All param callbacks will be called before any handler of any route in which the param occurs, and they will each be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples. - -```js -app.param('id', (req, res, next, id) => { - console.log('CALLED ONLY ONCE') - next() -}) - -app.get('/user/:id', (req, res, next) => { - console.log('although this matches') - next() -}) - -app.get('/user/:id', (req, res) => { - console.log('and this matches too') - res.end() -}) -``` - -On `GET /user/42`, the following is printed: - -``` -CALLED ONLY ONCE -although this matches -and this matches too -``` - -```js -app.param(['id', 'page'], (req, res, next, value) => { - console.log('CALLED ONLY ONCE with', value) - next() -}) - -app.get('/user/:id/:page', (req, res, next) => { - console.log('although this matches') - next() -}) - -app.get('/user/:id/:page', (req, res) => { - console.log('and this matches too') - res.end() -}) -``` - -On `GET /user/42/3`, the following is printed: - -``` -CALLED ONLY ONCE with 42 -CALLED ONLY ONCE with 3 -although this matches -and this matches too -``` diff --git a/_includes/api/en/5x/app-path.md b/_includes/api/en/5x/app-path.md deleted file mode 100644 index e1fabc0c10..0000000000 --- a/_includes/api/en/5x/app-path.md +++ /dev/null @@ -1,19 +0,0 @@ -

app.path()

- -Returns the canonical path of the app, a string. - -```js -const app = express() -const blog = express() -const blogAdmin = express() - -app.use('/blog', blog) -blog.use('/admin', blogAdmin) - -console.log(app.path()) // '' -console.log(blog.path()) // '/blog' -console.log(blogAdmin.path()) // '/blog/admin' -``` - -The behavior of this method can become very complicated in complex cases of mounted apps: -it is usually better to use [req.baseUrl](#req.baseUrl) to get the canonical path of the app. diff --git a/_includes/api/en/5x/app-post-method.md b/_includes/api/en/5x/app-post-method.md deleted file mode 100644 index 9bde32e02a..0000000000 --- a/_includes/api/en/5x/app-post-method.md +++ /dev/null @@ -1,14 +0,0 @@ -

app.post(path, callback [, callback ...])

- -Routes HTTP POST requests to the specified path with the specified callback functions. -For more information, see the [routing guide](/{{page.lang}}/guide/routing.html). - -{% include api/en/5x/routing-args.html %} - -#### Example - -```js -app.post('/', (req, res) => { - res.send('POST request to homepage') -}) -``` diff --git a/_includes/api/en/5x/app-put-method.md b/_includes/api/en/5x/app-put-method.md deleted file mode 100644 index 0575714854..0000000000 --- a/_includes/api/en/5x/app-put-method.md +++ /dev/null @@ -1,13 +0,0 @@ -

app.put(path, callback [, callback ...])

- -Routes HTTP PUT requests to the specified path with the specified callback functions. - -{% include api/en/5x/routing-args.html %} - -#### Example - -```js -app.put('/', (req, res) => { - res.send('PUT request to homepage') -}) -``` diff --git a/_includes/api/en/5x/app-render.md b/_includes/api/en/5x/app-render.md deleted file mode 100644 index 1a40d0f210..0000000000 --- a/_includes/api/en/5x/app-render.md +++ /dev/null @@ -1,25 +0,0 @@ -

app.render(view, [locals], callback)

- -Returns the rendered HTML of a view via the `callback` function. It accepts an optional parameter -that is an object containing local variables for the view. It is like [res.render()](#res.render), -except it cannot send the rendered view to the client on its own. - -
-Think of `app.render()` as a utility function for generating rendered view strings. -Internally `res.render()` uses `app.render()` to render views. -
- -
-The local variable `cache` is reserved for enabling view cache. Set it to `true`, if you want to -cache view during development; view caching is enabled in production by default. -
- -```js -app.render('email', (err, html) => { - // ... -}) - -app.render('email', { name: 'Tobi' }, (err, html) => { - // ... -}) -``` diff --git a/_includes/api/en/5x/app-route.md b/_includes/api/en/5x/app-route.md deleted file mode 100644 index 2a0db757dd..0000000000 --- a/_includes/api/en/5x/app-route.md +++ /dev/null @@ -1,20 +0,0 @@ -

app.route(path)

- -Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. -Use `app.route()` to avoid duplicate route names (and thus typo errors). - -```js -const app = express() - -app.route('/events') - .all((req, res, next) => { - // runs for all HTTP verbs first - // think of it as route specific middleware! - }) - .get((req, res, next) => { - res.json({}) - }) - .post((req, res, next) => { - // maybe add a new event... - }) -``` diff --git a/_includes/api/en/5x/app-router.md b/_includes/api/en/5x/app-router.md deleted file mode 100644 index b821faa75d..0000000000 --- a/_includes/api/en/5x/app-router.md +++ /dev/null @@ -1,19 +0,0 @@ -

app.router

- -The application's in-built instance of router. This is created lazily, on first access. - -```js -const express = require('express') -const app = express() -const router = app.router - -router.get('/', (req, res) => { - res.send('hello world') -}) - -app.listen(3000) -``` - -You can add middleware and HTTP method routes to the `router` just like an application. - -For more information, see [Router](#router). diff --git a/_includes/api/en/5x/app-set.md b/_includes/api/en/5x/app-set.md deleted file mode 100644 index e85bd9be19..0000000000 --- a/_includes/api/en/5x/app-set.md +++ /dev/null @@ -1,20 +0,0 @@ -

app.set(name, value)

- -Assigns setting `name` to `value`. You may store any value that you want, -but certain names can be used to configure the behavior of the server. These -special names are listed in the [app settings table](#app.settings.table). - -Calling `app.set('foo', true)` for a Boolean property is the same as calling -`app.enable('foo')`. Similarly, calling `app.set('foo', false)` for a Boolean -property is the same as calling `app.disable('foo')`. - -Retrieve the value of a setting with [`app.get()`](#app.get). - -```js -app.set('title', 'My Site') -app.get('title') // "My Site" -``` - -

Application Settings

- -{% include api/en/5x/app-settings.md %} diff --git a/_includes/api/en/5x/app-settings.md b/_includes/api/en/5x/app-settings.md deleted file mode 100644 index bed5176ce3..0000000000 --- a/_includes/api/en/5x/app-settings.md +++ /dev/null @@ -1,319 +0,0 @@ -The following table lists application settings. - -Note that 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. - -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"). - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyTypeDescriptionDefault
- `case sensitive routing` - Boolean

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.

-
N/A (undefined) -
- `env` - StringEnvironment mode. - Be sure to set to "production" in a production environment; - see Production best practices: performance and reliability. - - `process.env.NODE_ENV` (`NODE_ENV` environment variable) or "development" if `NODE_ENV` is not set. -
- `etag` - Varied - Set the ETag response header. For possible values, see the [`etag` options table](#etag.options.table). - - [More about the HTTP ETag header](http://en.wikipedia.org/wiki/HTTP_ETag). - - `weak` -
- `jsonp callback name` - StringSpecifies the default JSONP callback name. - "callback" -
- `json escape` - Boolean - 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.

-
N/A (undefined)
- `json replacer` - VariedThe 'replacer' argument used by `JSON.stringify`. -

NOTE: Sub-apps will inherit the value of this setting.

-
N/A (undefined) -
- `json spaces` - VariedThe 'space' argument used by `JSON.stringify`. -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.

-
N/A (undefined)
- `query parser` - Varied -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](http://nodejs.org/api/querystring.html). - -The extended query parser is based on [qs](https://www.npmjs.org/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. - "simple"
- `strict routing` - Boolean

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.

-
N/A (undefined)
- `subdomain offset` - NumberThe number of dot-separated parts of the host to remove to access subdomain.2
- `trust proxy` - Varied - 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. -

- The `trust proxy` setting is implemented using the 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. -

-
- `false` (disabled) -
- `views` - String or ArrayA 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. - `process.cwd() + '/views'` -
- `view cache` - Boolean

Enables view template compilation caching.

-

NOTE: Sub-apps will not inherit the value of this setting in production (when `NODE_ENV` is "production").

-
- `true` in production, otherwise undefined. -
- `view engine` - StringThe default engine extension to use when omitted. -

NOTE: Sub-apps will inherit the value of this setting.

-
N/A (undefined)
- `x-powered-by` - BooleanEnables the "X-Powered-By: Express" HTTP header. - `true` -
- -
Options for `trust proxy` setting
- -

- Read [Express behind proxies]/{{page.lang}}/behind-proxies.html) for more - information. -

- - - - - - - - - - - - - - - - - - - - - -
TypeValue
Boolean - If `true`, the client's IP address is understood as the left-most entry in the `X-Forwarded-*` header. - - If `false`, the app is understood as directly facing the Internet and the client's IP address is derived from `req.connection.remoteAddress`. This is the default setting. -
String
String containing comma-separated values
Array of strings
- An IP address, subnet, or an array of IP addresses, and subnets to trust. Pre-configured subnet names are: - - * loopback - `127.0.0.1/8`, `::1/128` - * linklocal - `169.254.0.0/16`, `fe80::/10` - * uniquelocal - `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `fc00::/7` - - Set IP addresses in any of the following ways: - -Specify a single subnet: - -```js -app.set('trust proxy', 'loopback') -``` - -Specify a subnet and an address: - -```js -app.set('trust proxy', 'loopback, 123.123.123.123') -``` - -Specify multiple subnets as CSV: - -```js -app.set('trust proxy', 'loopback, linklocal, uniquelocal') -``` - -Specify multiple subnets as an array: - -```js -app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) -``` - - When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client's IP address. -
Number - Trust the nth hop from the front-facing proxy server as the client. -
Function - Custom trust implementation. Use this only if you know what you are doing. - -```js -app.set('trust proxy', (ip) => { - if (ip === '127.0.0.1' || ip === '123.123.123.123') return true // trusted IPs - else return false -}) -``` -
- -
Options for `etag` setting
- -

-**NOTE**: These settings apply only to dynamic files, not static files. -The [express.static](#express.static) middleware ignores these settings. -

- -

- The ETag functionality is implemented using the - [etag](https://www.npmjs.org/package/etag) package. - For more information, see its documentation. -

- - - - - - - - - - - - - - - - - -
TypeValue
Boolean - `true` enables weak ETag. This is the default setting.
- `false` disables ETag altogether. -
String - If "strong", enables strong ETag.
- If "weak", enables weak ETag. -
FunctionCustom ETag function implementation. Use this only if you know what you are doing. - -```js -app.set('etag', (body, encoding) => { - return generateHash(body, encoding) // consider the function is defined -}) -``` -
-
diff --git a/_includes/api/en/5x/app-use.md b/_includes/api/en/5x/app-use.md deleted file mode 100644 index 17a8792c53..0000000000 --- a/_includes/api/en/5x/app-use.md +++ /dev/null @@ -1,292 +0,0 @@ -

app.use([path,] callback [, callback...])

- -Mounts the specified [middleware](/{{page.lang}}/guide/using-middleware.html) function or functions -at the specified path: -the middleware function is executed when the base of the requested path matches `path`. - -{% include api/en/5x/routing-args.html %} - -#### Description - -A route will match any path that follows its path immediately with a "`/`". -For example: `app.use('/apple', ...)` will match "/apple", "/apple/images", -"/apple/images/news", and so on. - -Since `path` defaults to "/", middleware mounted without a path will be executed for every request to the app. -For example, this middleware function will be executed for _every_ request to the app: - -```js -app.use((req, res, next) => { - console.log('Time: %d', Date.now()) - next() -}) -``` - -
-**NOTE** - -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. - -For details, see [Application settings](/en/5x/api.html#app.settings.table). -
- -Middleware functions are executed sequentially, therefore the order of middleware inclusion is important. - -```js -// this middleware will not allow the request to go beyond it -app.use((req, res, next) => { - res.send('Hello World') -}) - -// requests will never reach this route -app.get('/', (req, res) => { - res.send('Welcome') -}) -``` - -**Error-handling middleware** - -Error-handling middleware always takes _four_ arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don't need to use the `next` object, you must specify it to maintain the signature. Otherwise, the `next` object will be interpreted as regular middleware and will fail to handle errors. For details about error-handling middleware, see: [Error handling](/{{ page.lang }}/guide/error-handling.html). - -Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature `(err, req, res, next)`): - -```js -app.use((err, req, res, next) => { - console.error(err.stack) - res.status(500).send('Something broke!') -}) -``` - -#### Path examples - -The following table provides some simple examples of valid `path` values for -mounting middleware. - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TypeExample
Path -This will match paths starting with `/abcd`: - -```js -app.use('/abcd', (req, res, next) => { - next() -}) -``` - -
Path Pattern -This will match paths starting with `/abcd` and `/abd`: - -```js -app.use('/ab(c?)d', (req, res, next) => { - next() -}) -``` - -
Regular Expression -This will match paths starting with `/abc` and `/xyz`: - -```js -app.use(/\/abc|\/xyz/, (req, res, next) => { - next() -}) -``` - -
Array -This will match paths starting with `/abcd`, `/xyza`, `/lmn`, and `/pqr`: - -```js -app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], (req, res, next) => { - next() -}) -``` - -
-
- -#### Middleware callback function examples - -The following table provides some simple examples of middleware functions that -can be used as the `callback` argument to `app.use()`, `app.METHOD()`, and `app.all()`. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
UsageExample
Single Middleware -You can define and mount a middleware function locally. - -```js -app.use((req, res, next) => { - next() -}) -``` - -A router is valid middleware. - -```js -const router = express.Router() -router.get('/', (req, res, next) => { - next() -}) -app.use(router) -``` - -An Express app is valid middleware. - -```js -const subApp = express() -subApp.get('/', (req, res, next) => { - next() -}) -app.use(subApp) -``` - -
Series of Middleware -You can specify more than one middleware function at the same mount path. - -```js -const r1 = express.Router() -r1.get('/', (req, res, next) => { - next() -}) - -const r2 = express.Router() -r2.get('/', (req, res, next) => { - next() -}) - -app.use(r1, r2) -``` - -
Array -Use an array to group middleware logically. - -```js -const r1 = express.Router() -r1.get('/', (req, res, next) => { - next() -}) - -const r2 = express.Router() -r2.get('/', (req, res, next) => { - next() -}) - -app.use([r1, r2]) -``` - -
Combination -You can combine all the above ways of mounting middleware. - -```js -function mw1 (req, res, next) { next() } -function mw2 (req, res, next) { next() } - -const r1 = express.Router() -r1.get('/', (req, res, next) => { next() }) - -const r2 = express.Router() -r2.get('/', (req, res, next) => { next() }) - -const subApp = express() -subApp.get('/', (req, res, next) => { next() }) - -app.use(mw1, [mw2, r1, r2], subApp) -``` - -
- -Following are some examples of using the [express.static](/{{page.lang}}/guide/using-middleware.html#middleware.built-in) -middleware in an Express app. - -Serve static content for the app from the "public" directory in the application directory: - -```js -// GET /style.css etc -app.use(express.static(path.join(__dirname, 'public'))) -``` - -Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static": - -```js -// GET /static/style.css etc. -app.use('/static', express.static(path.join(__dirname, 'public'))) -``` - -Disable logging for static content requests by loading the logger middleware after the static middleware: - -```js -app.use(express.static(path.join(__dirname, 'public'))) -app.use(logger()) -``` - -Serve static files from multiple directories, but give precedence to "./public" over the others: - -```js -app.use(express.static(path.join(__dirname, 'public'))) -app.use(express.static(path.join(__dirname, 'files'))) -app.use(express.static(path.join(__dirname, 'uploads'))) -``` diff --git a/_includes/api/en/5x/app.md b/_includes/api/en/5x/app.md deleted file mode 100644 index 458ba8a447..0000000000 --- a/_includes/api/en/5x/app.md +++ /dev/null @@ -1,127 +0,0 @@ -

Application

- -The `app` object conventionally denotes the Express application. -Create it by calling the top-level `express()` function exported by the Express module: - -```js -const express = require('express') -const app = express() - -app.get('/', (req, res) => { - res.send('hello world') -}) - -app.listen(3000) -``` - -The `app` object has methods for - -* Routing HTTP requests; see for example, [app.METHOD](#app.METHOD) and [app.param](#app.param). -* Configuring middleware; see [app.route](#app.route). -* Rendering HTML views; see [app.render](#app.render). -* Registering a template engine; see [app.engine](#app.engine). - -It also has settings (properties) that affect how the application behaves; -for more information, see [Application settings](#app.settings.table). - -
-The Express application object can be referred from the [request object](#req) and the [response object](#res) as `req.app`, and `res.app`, respectively. -
- -

Properties

- -
- {% include api/en/5x/app-locals.md %} -
- -
- {% include api/en/5x/app-mountpath.md %} -
- -
- {% include api/en/5x/app-router.md %} -
- -

Events

- -
- {% include api/en/5x/app-onmount.md %} -
- -

Methods

- -
- {% include api/en/5x/app-all.md %} -
- -
- {% include api/en/5x/app-delete-method.md %} -
- -
- {% include api/en/5x/app-disable.md %} -
- -
- {% include api/en/5x/app-disabled.md %} -
- -
- {% include api/en/5x/app-enable.md %} -
- -
- {% include api/en/5x/app-enabled.md %} -
- -
- {% include api/en/5x/app-engine.md %} -
- -
- {% include api/en/5x/app-get.md %} -
- -
- {% include api/en/5x/app-get-method.md %} -
- -
- {% include api/en/5x/app-listen.md %} -
- -
- {% include api/en/5x/app-METHOD.md %} -
- -
- {% include api/en/5x/app-param.md %} -
- -
- {% include api/en/5x/app-path.md %} -
- -
- {% include api/en/5x/app-post-method.md %} -
- -
- {% include api/en/5x/app-put-method.md %} -
- -
- {% include api/en/5x/app-render.md %} -
- -
- {% include api/en/5x/app-route.md %} -
- -
- {% include api/en/5x/app-set.md %} -
- -
- {% include api/en/5x/app-use.md %} -
diff --git a/_includes/api/en/5x/express.json.md b/_includes/api/en/5x/express.json.md deleted file mode 100644 index 0262f570c7..0000000000 --- a/_includes/api/en/5x/express.json.md +++ /dev/null @@ -1,34 +0,0 @@ -

express.json([options])

- -This is a built-in middleware function in Express. It parses incoming requests -with JSON payloads and is based on -[body-parser](/resources/middleware/body-parser.html). - -Returns middleware that only parses JSON and only looks at requests where -the `Content-Type` header matches the `type` option. This parser accepts any -Unicode encoding of the body and supports automatic inflation of `gzip` and -`deflate` encodings. - -A new `body` object containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`), or an empty object (`{}`) if -there was no body to parse, the `Content-Type` was not matched, or an error -occurred. - -
-As `req.body`'s shape is based on user-controlled input, all properties and -values in this object are untrusted and should be validated before trusting. -For example, `req.body.foo.toString()` may fail in multiple ways, for example -`foo` may not be there or may not be a string, and `toString` may not be a -function and instead a string or other user-input. -
- -The following table describes the properties of the optional `options` object. - -| Property | Description | Type | Default | -|---------------|-----------------------------------------------------------------------|-------------|-----------------| -| `inflate` | Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. | Boolean | `true` | -| `limit` | Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. | Mixed | `"100kb"` | -| `reviver` | The `reviver` option is passed directly to `JSON.parse` as the second argument. You can find more information on this argument [in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). | Function | `null` | -| `strict` | Enables or disables only accepting arrays and objects; when disabled will accept anything `JSON.parse` accepts. | Boolean | `true` | -| `type` | This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `json`), a mime type (like `application/json`), or a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. | Mixed | `"application/json"` | -| `verify` | This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. | Function | `undefined` | diff --git a/_includes/api/en/5x/express.md b/_includes/api/en/5x/express.md deleted file mode 100644 index cf6e625a72..0000000000 --- a/_includes/api/en/5x/express.md +++ /dev/null @@ -1,26 +0,0 @@ -

express()

- -Creates an Express application. The `express()` function is a top-level function exported by the `express` module. - -```js -const express = require('express') -const app = express() -``` - -

Methods

- -
- {% include api/en/5x/express.json.md %} -
- -
- {% include api/en/5x/express.static.md %} -
- -
- {% include api/en/5x/express.router.md %} -
- -
- {% include api/en/5x/express.urlencoded.md %} -
diff --git a/_includes/api/en/5x/express.raw.md b/_includes/api/en/5x/express.raw.md deleted file mode 100644 index a3dc828c9d..0000000000 --- a/_includes/api/en/5x/express.raw.md +++ /dev/null @@ -1,32 +0,0 @@ -

express.raw([options])

- -This is a built-in middleware function in Express. It parses incoming request -payloads into a `Buffer` and is based on -[body-parser](/resources/middleware/body-parser.html). - -Returns middleware that parses all bodies as a `Buffer` and only looks at requests -where the `Content-Type` header matches the `type` option. This parser accepts -any Unicode encoding of the body and supports automatic inflation of `gzip` and -`deflate` encodings. - -A new `body` `Buffer` containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`), or an empty object (`{}`) if -there was no body to parse, the `Content-Type` was not matched, or an error -occurred. - -
-As `req.body`'s shape is based on user-controlled input, all properties and -values in this object are untrusted and should be validated before trusting. -For example, `req.body.toString()` may fail in multiple ways, for example -stacking multiple parsers `req.body` may be from a different parser. Testing -that `req.body` is a `Buffer` before calling buffer methods is recommended. -
- -The following table describes the properties of the optional `options` object. - -| Property | Description | Type | Default | -|-----------|-----------------------------------------------------------------------|-------------|-----------------| -| `inflate` | Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. | Boolean | `true` | -| `limit` | Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. | Mixed | `"100kb"` | -| `type` | This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `bin`), a mime type (like `application/octet-stream`), or a mime type with a wildcard (like `*/*` or `application/*`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. | Mixed | `"application/octet-stream"` | -| `verify` | This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. | Function | `undefined` | diff --git a/_includes/api/en/5x/express.router.md b/_includes/api/en/5x/express.router.md deleted file mode 100644 index babd0b0279..0000000000 --- a/_includes/api/en/5x/express.router.md +++ /dev/null @@ -1,24 +0,0 @@ -

express.Router([options])

- -Creates a new [router](#router) object. - -```js -const router = express.Router([options]) -``` - -The optional `options` parameter specifies the behavior of the router. - -
- -| Property | Description | Default | Availability | -|-----------------|-------------------------------------------------|-------------|---------------| -| `caseSensitive` | Enable case sensitivity. | Disabled by default, treating "/Foo" and "/foo" as the same.| | -| `mergeParams` | Preserve the `req.params` values from the parent router. If the parent and the child have conflicting param names, the child's value take precedence.| `false` | 4.5.0+ | -| `strict` | Enable strict routing. | Disabled by default, "/foo" and "/foo/" are treated the same by the router.|   | - -
- -You can add middleware and HTTP method routes (such as `get`, `put`, `post`, and -so on) to `router` just like an application. - -For more information, see [Router](#router). diff --git a/_includes/api/en/5x/express.static.md b/_includes/api/en/5x/express.static.md deleted file mode 100644 index d1c0d5b44d..0000000000 --- a/_includes/api/en/5x/express.static.md +++ /dev/null @@ -1,88 +0,0 @@ -

express.static(root, [options])

- -This is a built-in middleware function in Express. -It serves static files and is based on [serve-static](/resources/middleware/serve-static.html). - -
NOTE: For best results, [use a reverse proxy](/{{page.lang}}/advanced/best-practice-performance.html#use-a-reverse-proxy) cache to improve performance of serving static assets. -
- -The `root` argument specifies the root directory from which to serve static assets. -The function determines the file to serve by combining `req.url` with the provided `root` directory. -When a file is not found, instead of sending a 404 response, it instead calls `next()` -to move on to the next middleware, allowing for stacking and fall-backs. - -The following table describes the properties of the `options` object. -See also the [example below](#example.of.express.static). - -| Property | Description | Type | Default | -|---------------|-----------------------------------------------------------------------|-------------|-----------------| -| `dotfiles` | Determines how dotfiles (files or directories that begin with a dot ".") are treated.

See [dotfiles](#dotfiles) below. | String | "ignore"| -| `etag` | Enable or disable etag generation

NOTE: `express.static` always sends weak ETags. | Boolean | `true` | -| `extensions` | Sets file extension fallbacks: If a file is not found, search for files with the specified extensions and serve the first one found. Example: `['html', 'htm']`.| Mixed | `false` | -| `fallthrough` | Let client errors fall-through as unhandled requests, otherwise forward a client error.

See [fallthrough](#fallthrough) below.| Boolean | `true` | -| `immutable` | Enable or disable the `immutable` directive in the `Cache-Control` response header. If enabled, the `maxAge` option should also be specified to enable caching. The `immutable` directive will prevent supported clients from making conditional requests during the life of the `maxAge` option to check if the file has changed. | Boolean | `false` | -| `index` | Sends the specified directory index file. Set to `false` to disable directory indexing. | Mixed | "index.html" | -| `lastModified` | Set the `Last-Modified` header to the last modified date of the file on the OS. | Boolean | `true` | -| `maxAge` | Set the max-age property of the Cache-Control header in milliseconds or a string in [ms format](https://www.npmjs.org/package/ms). | Number | 0 | -| `redirect` | Redirect to trailing "/" when the pathname is a directory. | Boolean | `true` | -| `setHeaders` | Function for setting HTTP headers to serve with the file.

See [setHeaders](#setHeaders) below. | Function | | - -For more information, see [Serving static files in Express](/starter/static-files.html). -and [Using middleware - Built-in middleware](/{{page.lang}}/guide/using-middleware.html#middleware.built-in). - -
dotfiles
- -Possible values for this option are: - -- "allow" - No special treatment for dotfiles. -- "deny" - Deny a request for a dotfile, respond with `403`, then call `next()`. -- "ignore" - Act as if the dotfile does not exist, respond with `404`, then call `next()`. - -
fallthrough
- -When this option is `true`, client errors such as a bad request or a request to a non-existent -file will cause this middleware to simply call `next()` to invoke the next middleware in the stack. -When false, these errors (even 404s), will invoke `next(err)`. - -Set this option to `true` so you can map multiple physical directories -to the same web address or for routes to fill in non-existent files. - -Use `false` if you have mounted this middleware at a path designed -to be strictly a single file system directory, which allows for short-circuiting 404s -for less overhead. This middleware will also reply to all methods. - -
setHeaders
- -For this option, specify a function to set custom response headers. Alterations to the headers must occur synchronously. - -The signature of the function is: - -```js -fn(res, path, stat) -``` - -Arguments: - -- `res`, the [response object](#res). -- `path`, the file path that is being sent. -- `stat`, the `stat` object of the file that is being sent. - -

Example of express.static

- -Here is an example of using the `express.static` middleware function with an elaborate options object: - -```js -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)) -``` diff --git a/_includes/api/en/5x/express.text.md b/_includes/api/en/5x/express.text.md deleted file mode 100644 index 28988c1016..0000000000 --- a/_includes/api/en/5x/express.text.md +++ /dev/null @@ -1,33 +0,0 @@ -

express.text([options])

- -This is a built-in middleware function in Express. It parses incoming request -payloads into a string and is based on -[body-parser](/resources/middleware/body-parser.html). - -Returns middleware that parses all bodies as a string and only looks at requests -where the `Content-Type` header matches the `type` option. This parser accepts -any Unicode encoding of the body and supports automatic inflation of `gzip` and -`deflate` encodings. - -A new `body` string containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`), or an empty object (`{}`) if -there was no body to parse, the `Content-Type` was not matched, or an error -occurred. - -
-As `req.body`'s shape is based on user-controlled input, all properties and -values in this object are untrusted and should be validated before trusting. -For example, `req.body.trim()` may fail in multiple ways, for example -stacking multiple parsers `req.body` may be from a different parser. Testing -that `req.body` is a string before calling string methods is recommended. -
- -The following table describes the properties of the optional `options` object. - -| Property | Description | Type | Default | -|------------------|-----------------------------------------------------------------------|-------------|-----------------| -| `defaultCharset` | Specify the default character set for the text content if the charset is not specified in the `Content-Type` header of the request. | String | `"utf-8"` | -| `inflate` | Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. | Boolean | `true` | -| `limit` | Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. | Mixed | `"100kb"` | -| `type` | This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `txt`), a mime type (like `text/plain`), or a mime type with a wildcard (like `*/*` or `text/*`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. | Mixed | `"text/plain"` | -| `verify` | This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. | Function | `undefined` | diff --git a/_includes/api/en/5x/express.urlencoded.md b/_includes/api/en/5x/express.urlencoded.md deleted file mode 100644 index 49d44b44bc..0000000000 --- a/_includes/api/en/5x/express.urlencoded.md +++ /dev/null @@ -1,35 +0,0 @@ -

express.urlencoded([options])

- -This is a built-in middleware function in Express. It parses incoming requests -with urlencoded payloads and is based on [body-parser](/resources/middleware/body-parser.html). - -Returns middleware that only parses urlencoded bodies and only looks at -requests where the `Content-Type` header matches the `type` option. This -parser accepts only UTF-8 encoding of the body and supports automatic -inflation of `gzip` and `deflate` encodings. - -A new `body` object containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`), or an empty object (`{}`) if -there was no body to parse, the `Content-Type` was not matched, or an error -occurred. This object will contain key-value pairs, where the value can be -a string or array (when `extended` is `false`), or any type (when `extended` -is `true`). - -
-As `req.body`'s shape is based on user-controlled input, all properties and -values in this object are untrusted and should be validated before trusting. -For example, `req.body.foo.toString()` may fail in multiple ways, for example -`foo` may not be there or may not be a string, and `toString` may not be a -function and instead a string or other user-input. -
- -The following table describes the properties of the optional `options` object. - -| Property | Description | Type | Default | -|------------------|-----------------------------------------------------------------------|-------------|-----------------| -| `extended` | This option allows to choose between parsing the URL-encoded data with the `querystring` library (when `false`) or the `qs` library (when `true`). The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please [see the qs library](https://www.npmjs.org/package/qs#readme). | Boolean | `false` | -| `inflate` | Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected. | Boolean | `true` | -| `limit` | Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. | Mixed | `"100kb"` | -| `parameterLimit` | This option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, an error will be raised. | Number | `1000` | -| `type` | This is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `urlencoded`), a mime type (like `application/x-www-form-urlencoded`), or a mime type with a wildcard (like `*/x-www-form-urlencoded`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. | Mixed | `"application/x-www-form-urlencoded"` | -| `verify` | This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. | Function | `undefined` | diff --git a/_includes/api/en/5x/menu.md b/_includes/api/en/5x/menu.md deleted file mode 100644 index 27a73cc779..0000000000 --- a/_includes/api/en/5x/menu.md +++ /dev/null @@ -1,207 +0,0 @@ - diff --git a/_includes/api/en/5x/req-accepts.md b/_includes/api/en/5x/req-accepts.md deleted file mode 100644 index 7258c71b4c..0000000000 --- a/_includes/api/en/5x/req-accepts.md +++ /dev/null @@ -1,36 +0,0 @@ -

req.accepts(types)

- -Checks if the specified content types are acceptable, based on the request's `Accept` HTTP header field. -The method returns the best match, or if none of the specified content types is acceptable, returns -`false` (in which case, the application should respond with `406 "Not Acceptable"`). - -The `type` value may be a single MIME type string (such as "application/json"), -an extension name such as "json", a comma-delimited list, or an array. For a -list or array, the method returns the *best* match (if any). - -```js -// Accept: text/html -req.accepts('html') -// => "html" - -// Accept: text/*, application/json -req.accepts('html') -// => "html" -req.accepts('text/html') -// => "text/html" -req.accepts(['json', 'text']) -// => "json" -req.accepts('application/json') -// => "application/json" - -// Accept: text/*, application/json -req.accepts('image/png') -req.accepts('png') -// => false - -// Accept: text/*;q=.5, application/json -req.accepts(['html', 'json']) -// => "json" -``` - -For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts). diff --git a/_includes/api/en/5x/req-acceptsCharsets.md b/_includes/api/en/5x/req-acceptsCharsets.md deleted file mode 100644 index d47d0480d3..0000000000 --- a/_includes/api/en/5x/req-acceptsCharsets.md +++ /dev/null @@ -1,7 +0,0 @@ -

req.acceptsCharsets(charset [, ...])

- -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`. - -For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts). diff --git a/_includes/api/en/5x/req-acceptsEncodings.md b/_includes/api/en/5x/req-acceptsEncodings.md deleted file mode 100644 index 2c6a3f236f..0000000000 --- a/_includes/api/en/5x/req-acceptsEncodings.md +++ /dev/null @@ -1,7 +0,0 @@ -

req.acceptsEncodings(encoding [, ...])

- -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`. - -For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts). diff --git a/_includes/api/en/5x/req-acceptsLanguages.md b/_includes/api/en/5x/req-acceptsLanguages.md deleted file mode 100644 index 8744fafd23..0000000000 --- a/_includes/api/en/5x/req-acceptsLanguages.md +++ /dev/null @@ -1,7 +0,0 @@ -

req.acceptsLanguages(lang [, ...])

- -Returns the first accepted language of the specified languages, -based on the request's `Accept-Language` HTTP header field. -If none of the specified languages is accepted, returns `false`. - -For more information, or if you have issues or concerns, see [accepts](https://github.com/expressjs/accepts). diff --git a/_includes/api/en/5x/req-app.md b/_includes/api/en/5x/req-app.md deleted file mode 100644 index 30873d7ab7..0000000000 --- a/_includes/api/en/5x/req-app.md +++ /dev/null @@ -1,20 +0,0 @@ -

req.app

- -This property holds a reference to the instance of the Express application that is using the middleware. - -If you follow the pattern in which you create a module that just exports a middleware function -and `require()` it in your main file, then the middleware can access the Express instance via `req.app` - -For example: - -```js -// index.js -app.get('/viewdirectory', require('./mymiddleware.js')) -``` - -```js -// mymiddleware.js -module.exports = (req, res) => { - res.send(`The views directory is ${req.app.get('views')}`) -} -``` diff --git a/_includes/api/en/5x/req-baseUrl.md b/_includes/api/en/5x/req-baseUrl.md deleted file mode 100644 index 89245d47bc..0000000000 --- a/_includes/api/en/5x/req-baseUrl.md +++ /dev/null @@ -1,30 +0,0 @@ -

req.baseUrl

- -The URL path on which a router instance was mounted. - -The `req.baseUrl` property is similar to the [mountpath](#app.mountpath) property of the `app` object, -except `app.mountpath` returns the matched path pattern(s). - -For example: - -```js -const greet = express.Router() - -greet.get('/jp', (req, res) => { - console.log(req.baseUrl) // /greet - res.send('Konichiwa!') -}) - -app.use('/greet', greet) // load the router on '/greet' -``` - -Even if you use a path pattern or a set of path patterns to load the router, -the `baseUrl` property returns the matched string, not the pattern(s). In the -following example, the `greet` router is loaded on two path patterns. - -```js -app.use(['/gre+t', '/hel{2}o'], greet) // load the router on '/gre+t' and '/hel{2}o' -``` - -When a request is made to `/greet/jp`, `req.baseUrl` is "/greet". When a request is -made to `/hello/jp`, `req.baseUrl` is "/hello". diff --git a/_includes/api/en/5x/req-body.md b/_includes/api/en/5x/req-body.md deleted file mode 100644 index 591d8991e5..0000000000 --- a/_includes/api/en/5x/req-body.md +++ /dev/null @@ -1,26 +0,0 @@ -

req.body

- -Contains key-value pairs of data submitted in the request body. -By default, it is `undefined`, and is populated when you use body-parsing middleware such -as [body-parser](https://www.npmjs.org/package/body-parser) and [multer](https://www.npmjs.org/package/multer). - -
-As `req.body`'s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input. -
- -The following example shows how to use body-parsing middleware to populate `req.body`. - -```js -const app = require('express')() -const bodyParser = require('body-parser') -const multer = require('multer') // v1.0.5 -const upload = multer() // for parsing multipart/form-data - -app.use(bodyParser.json()) // for parsing application/json -app.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded - -app.post('/profile', upload.array(), (req, res, next) => { - console.log(req.body) - res.json(req.body) -}) -``` diff --git a/_includes/api/en/5x/req-cookies.md b/_includes/api/en/5x/req-cookies.md deleted file mode 100644 index 00821e722f..0000000000 --- a/_includes/api/en/5x/req-cookies.md +++ /dev/null @@ -1,14 +0,0 @@ -

req.cookies

- -When using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this property is an object that -contains cookies sent by the request. If the request contains no cookies, it defaults to `{}`. - -```js -// Cookie: name=tj -console.dir(req.cookies.name) -// => "tj" -``` - -If the cookie has been signed, you have to use [req.signedCookies](#req.signedCookies). - -For more information, issues, or concerns, see [cookie-parser](https://github.com/expressjs/cookie-parser). diff --git a/_includes/api/en/5x/req-fresh.md b/_includes/api/en/5x/req-fresh.md deleted file mode 100644 index 1b6ec61c59..0000000000 --- a/_includes/api/en/5x/req-fresh.md +++ /dev/null @@ -1,13 +0,0 @@ -

req.fresh

- -When the response is still "fresh" in the client's cache `true` is returned, otherwise `false` is returned to indicate that the client cache is now stale and the full response should be sent. - -When a client sends the `Cache-Control: no-cache` request header to indicate an end-to-end reload request, this module will return `false` to make handling these requests transparent. - -Further details for how cache validation works can be found in the -[HTTP/1.1 Caching Specification](https://tools.ietf.org/html/rfc7234). - -```js -console.dir(req.fresh) -// => true -``` diff --git a/_includes/api/en/5x/req-get.md b/_includes/api/en/5x/req-get.md deleted file mode 100644 index 7cd4250b22..0000000000 --- a/_includes/api/en/5x/req-get.md +++ /dev/null @@ -1,17 +0,0 @@ -

req.get(field)

- -Returns the specified HTTP request header field (case-insensitive match). -The `Referrer` and `Referer` fields are interchangeable. - -```js -req.get('Content-Type') -// => "text/plain" - -req.get('content-type') -// => "text/plain" - -req.get('Something') -// => undefined -``` - -Aliased as `req.header(field)`. diff --git a/_includes/api/en/5x/req-host.md b/_includes/api/en/5x/req-host.md deleted file mode 100644 index dfcf63be9e..0000000000 --- a/_includes/api/en/5x/req-host.md +++ /dev/null @@ -1,22 +0,0 @@ -

req.host

- -Contains the host derived from the `Host` HTTP header. - -When the [`trust proxy` setting](api.html#app.settings.table) -does not evaluate to `false`, this property will instead get the value -from the `X-Forwarded-Host` header field. This header can be set by -the client or by the proxy. - -If there is more than one `X-Forwarded-Host` header in the request, the -value of the first header is used. This includes a single header with -comma-separated values, in which the first value is used. - -```js -// Host: "example.com:3000" -console.dir(req.host) -// => 'example.com:3000' - -// Host: "[::1]:3000" -console.dir(req.host) -// => '[::1]:3000' -``` diff --git a/_includes/api/en/5x/req-hostname.md b/_includes/api/en/5x/req-hostname.md deleted file mode 100644 index 327a22426d..0000000000 --- a/_includes/api/en/5x/req-hostname.md +++ /dev/null @@ -1,23 +0,0 @@ -

req.hostname

- -Contains the hostname derived from the `Host` HTTP header. - -When the [`trust proxy` setting](/5x/api.html#trust.proxy.options.table) -does not evaluate to `false`, this property will instead get the value -from the `X-Forwarded-Host` header field. This header can be set by -the client or by the proxy. - -If there is more than one `X-Forwarded-Host` header in the request, the -value of the first header is used. This includes a single header with -comma-separated values, in which the first value is used. - -
-Prior to Express v4.17.0, the `X-Forwarded-Host` could not contain multiple -values or be present more than once. -
- -```js -// Host: "example.com:3000" -console.dir(req.hostname) -// => 'example.com' -``` diff --git a/_includes/api/en/5x/req-ip.md b/_includes/api/en/5x/req-ip.md deleted file mode 100644 index 0bbc7f0318..0000000000 --- a/_includes/api/en/5x/req-ip.md +++ /dev/null @@ -1,12 +0,0 @@ -

req.ip

- -Contains the remote IP address of the request. - -When the [`trust proxy` setting](/5x/api.html#trust.proxy.options.table) does not evaluate to `false`, -the value of this property is derived from the left-most entry in the -`X-Forwarded-For` header. This header can be set by the client or by the proxy. - -```js -console.dir(req.ip) -// => "127.0.0.1" -``` diff --git a/_includes/api/en/5x/req-ips.md b/_includes/api/en/5x/req-ips.md deleted file mode 100644 index 312238b346..0000000000 --- a/_includes/api/en/5x/req-ips.md +++ /dev/null @@ -1,9 +0,0 @@ -

req.ips

- -When the [`trust proxy` setting](/5x/api.html#trust.proxy.options.table) does not evaluate to `false`, -this property contains an array of IP addresses -specified in the `X-Forwarded-For` request header. Otherwise, it contains an -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. diff --git a/_includes/api/en/5x/req-is.md b/_includes/api/en/5x/req-is.md deleted file mode 100644 index c46e38abba..0000000000 --- a/_includes/api/en/5x/req-is.md +++ /dev/null @@ -1,22 +0,0 @@ -

req.is(type)

- -Returns the matching content type if the incoming request's "Content-Type" HTTP header field -matches the MIME type specified by the `type` parameter. If the request has no body, returns `null`. -Returns `false` otherwise. - -```js -// With Content-Type: text/html; charset=utf-8 -req.is('html') // => 'html' -req.is('text/html') // => 'text/html' -req.is('text/*') // => 'text/*' - -// When Content-Type is application/json -req.is('json') // => 'json' -req.is('application/json') // => 'application/json' -req.is('application/*') // => 'application/*' - -req.is('html') -// => false -``` - -For more information, or if you have issues or concerns, see [type-is](https://github.com/expressjs/type-is). diff --git a/_includes/api/en/5x/req-method.md b/_includes/api/en/5x/req-method.md deleted file mode 100644 index 3d2b886d7d..0000000000 --- a/_includes/api/en/5x/req-method.md +++ /dev/null @@ -1,4 +0,0 @@ -

req.method

- -Contains a string corresponding to the HTTP method of the request: -`GET`, `POST`, `PUT`, and so on. diff --git a/_includes/api/en/5x/req-originalUrl.md b/_includes/api/en/5x/req-originalUrl.md deleted file mode 100644 index 660f46d7b1..0000000000 --- a/_includes/api/en/5x/req-originalUrl.md +++ /dev/null @@ -1,28 +0,0 @@ -

req.originalUrl

- -
-`req.url` is not a native Express property, it is inherited from Node's [http module](https://nodejs.org/api/http.html#http_message_url). -
- -This property is much like `req.url`; however, it retains the original request URL, -allowing you to rewrite `req.url` freely for internal routing purposes. For example, -the "mounting" feature of [app.use()](#app.use) will rewrite `req.url` to strip the mount point. - -```js -// GET /search?q=something -console.dir(req.originalUrl) -// => "/search?q=something" -``` - -`req.originalUrl` is available both in middleware and router objects, and is a -combination of `req.baseUrl` and `req.url`. Consider following example: - -```js -// GET 'http://www.example.com/admin/new?sort=desc' -app.use('/admin', (req, res, next) => { - console.dir(req.originalUrl) // '/admin/new?sort=desc' - console.dir(req.baseUrl) // '/admin' - console.dir(req.path) // '/new' - next() -}) -``` diff --git a/_includes/api/en/5x/req-params.md b/_includes/api/en/5x/req-params.md deleted file mode 100644 index 54520c6d8a..0000000000 --- a/_includes/api/en/5x/req-params.md +++ /dev/null @@ -1,23 +0,0 @@ -

req.params

- -This property is an object containing properties mapped to the [named route "parameters"](/{{ page.lang }}/guide/routing.html#route-parameters). For example, if you have the route `/user/:name`, then the "name" property is available as `req.params.name`. This object defaults to `{}`. - -```js -// GET /user/tj -console.dir(req.params.name) -// => "tj" -``` - -When you use a regular expression for the route definition, capture groups are provided in the array using `req.params[n]`, where `n` is the nth capture group. This rule is applied to unnamed wild card matches with string routes such as `/file/*`: - -```js -// GET /file/javascripts/jquery.js -console.dir(req.params[0]) -// => "javascripts/jquery.js" -``` - -If you need to make changes to a key in `req.params`, use the [app.param](/{{ page.lang }}/5x/api.html#app.param) handler. Changes are applicable only to [parameters](/{{ page.lang }}/guide/routing.html#route-parameters) already defined in the route path. - -Any changes made to the `req.params` object in a middleware or route handler will be reset. - -{% include admonitions/note.html content="Express automatically decodes the values in `req.params` (using `decodeURIComponent`)." %} \ No newline at end of file diff --git a/_includes/api/en/5x/req-path.md b/_includes/api/en/5x/req-path.md deleted file mode 100644 index 70eb680c50..0000000000 --- a/_includes/api/en/5x/req-path.md +++ /dev/null @@ -1,13 +0,0 @@ -

req.path

- -Contains the path part of the request URL. - -```js -// example.com/users?sort=desc -console.dir(req.path) -// => "/users" -``` - -
-When called from a middleware, the mount point is not included in `req.path`. See [app.use()](/5x/api.html#app.use) for more details. -
diff --git a/_includes/api/en/5x/req-protocol.md b/_includes/api/en/5x/req-protocol.md deleted file mode 100644 index 32e1ba8a75..0000000000 --- a/_includes/api/en/5x/req-protocol.md +++ /dev/null @@ -1,12 +0,0 @@ -

req.protocol

- -Contains the request protocol string: either `http` or (for TLS requests) `https`. - -When the [`trust proxy` setting](#trust.proxy.options.table) does not evaluate to `false`, -this property will use the value of the `X-Forwarded-Proto` header field if present. -This header can be set by the client or by the proxy. - -```js -console.dir(req.protocol) -// => "http" -``` diff --git a/_includes/api/en/5x/req-query.md b/_includes/api/en/5x/req-query.md deleted file mode 100644 index ca114cf2ca..0000000000 --- a/_includes/api/en/5x/req-query.md +++ /dev/null @@ -1,18 +0,0 @@ -

req.query

- -This property is an object containing a property for each query string parameter in the route. -When [query parser](#app.settings.table) is set to disabled, it is an empty object `{}`, otherwise it is the result of the configured query parser. - -
-As `req.query`'s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.query.foo.toString()` may fail in multiple ways, for example `foo` may not be there or may not be a string, and `toString` may not be a function and instead a string or other user-input. -
- -The value of this property can be configured with the [query parser application setting](#app.settings.table) to work how your application needs it. A very popular query string parser is the [`qs` module](https://www.npmjs.org/package/qs), and this is used by default. The `qs` module is very configurable with many settings, and it may be desirable to use different settings than the default to populate `req.query`: - -```js -const qs = require('qs') -app.set('query parser', - (str) => qs.parse(str, { /* custom options */ })) -``` - -Check out the [query parser application setting](#app.settings.table) documentation for other customization options. diff --git a/_includes/api/en/5x/req-range.md b/_includes/api/en/5x/req-range.md deleted file mode 100644 index 8ebce46382..0000000000 --- a/_includes/api/en/5x/req-range.md +++ /dev/null @@ -1,29 +0,0 @@ -

req.range(size[, options])

- -`Range` header parser. - -The `size` parameter is the maximum size of the resource. - -The `options` parameter is an object that can have the following properties. - -| Property | Type | Description | -|-------------|-------------------------------------------------------------------------| -| `combine` | Boolean | Specify if overlapping & adjacent ranges should be combined, defaults to `false`. When `true`, ranges will be combined and returned as if they were specified that way in the header. - -An array of ranges will be returned or negative numbers indicating an error parsing. - -* `-2` signals a malformed header string -* `-1` signals an unsatisfiable range - -```js -// parse header from request -const range = req.range(1000) - -// the type of the range -if (range.type === 'bytes') { - // the ranges - range.forEach((r) => { - // do something with r.start and r.end - }) -} -``` diff --git a/_includes/api/en/5x/req-res.md b/_includes/api/en/5x/req-res.md deleted file mode 100644 index 772ddb43b4..0000000000 --- a/_includes/api/en/5x/req-res.md +++ /dev/null @@ -1,4 +0,0 @@ -

req.res

- -This property holds a reference to the response object -that relates to this request object. diff --git a/_includes/api/en/5x/req-route.md b/_includes/api/en/5x/req-route.md deleted file mode 100644 index 508ac174e2..0000000000 --- a/_includes/api/en/5x/req-route.md +++ /dev/null @@ -1,26 +0,0 @@ -

req.route

- -Contains the currently-matched route, a string. For example: - -```js -app.get('/user/:id?', (req, res) => { - console.log(req.route) - res.send('GET') -}) -``` - -Example output from the previous snippet: - -``` -{ path: '/user/:id?', - stack: - [ { handle: [Function: userIdHandler], - name: 'userIdHandler', - params: undefined, - path: undefined, - keys: [], - regexp: /^\/?$/i, - method: 'get' } ], - methods: { get: true } -} -``` diff --git a/_includes/api/en/5x/req-secure.md b/_includes/api/en/5x/req-secure.md deleted file mode 100644 index 4d8ab831ce..0000000000 --- a/_includes/api/en/5x/req-secure.md +++ /dev/null @@ -1,8 +0,0 @@ -

req.secure

- -A Boolean property that is true if a TLS connection is established. Equivalent to the following: - - -```js -req.protocol === 'https' -``` diff --git a/_includes/api/en/5x/req-signedCookies.md b/_includes/api/en/5x/req-signedCookies.md deleted file mode 100644 index 2fd5b3c29c..0000000000 --- a/_includes/api/en/5x/req-signedCookies.md +++ /dev/null @@ -1,17 +0,0 @@ -

req.signedCookies

- -When using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this property -contains signed cookies sent by the request, unsigned and ready for use. Signed cookies reside -in a different object to show developer intent; otherwise, a malicious attack could be placed on -`req.cookie` values (which are easy to spoof). Note that signing a cookie does not make it "hidden" -or encrypted; but simply prevents tampering (because the secret used to sign is private). - -If no signed cookies are sent, the property defaults to `{}`. - -```js -// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3 -console.dir(req.signedCookies.user) -// => "tobi" -``` - -For more information, issues, or concerns, see [cookie-parser](https://github.com/expressjs/cookie-parser). diff --git a/_includes/api/en/5x/req-stale.md b/_includes/api/en/5x/req-stale.md deleted file mode 100644 index ca8b479f4c..0000000000 --- a/_includes/api/en/5x/req-stale.md +++ /dev/null @@ -1,9 +0,0 @@ -

req.stale

- -Indicates whether the request is "stale," and is the opposite of `req.fresh`. -For more information, see [req.fresh](#req.fresh). - -```js -console.dir(req.stale) -// => true -``` diff --git a/_includes/api/en/5x/req-subdomains.md b/_includes/api/en/5x/req-subdomains.md deleted file mode 100644 index 714e6e8c07..0000000000 --- a/_includes/api/en/5x/req-subdomains.md +++ /dev/null @@ -1,13 +0,0 @@ -

req.subdomains

- -An array of subdomains in the domain name of the request. - -```js -// Host: "tobi.ferrets.example.com" -console.dir(req.subdomains) -// => ["ferrets", "tobi"] -``` - -The application property `subdomain offset`, which defaults to 2, is used for determining the -beginning of the subdomain segments. To change this behavior, change its value -using [app.set](/{{ page.lang }}/5x/api.html#app.set). diff --git a/_includes/api/en/5x/req-xhr.md b/_includes/api/en/5x/req-xhr.md deleted file mode 100644 index 5c1da1c704..0000000000 --- a/_includes/api/en/5x/req-xhr.md +++ /dev/null @@ -1,9 +0,0 @@ -

req.xhr

- -A Boolean property that is `true` if the request's `X-Requested-With` header field is -"XMLHttpRequest", indicating that the request was issued by a client library such as jQuery. - -```js -console.dir(req.xhr) -// => true -``` diff --git a/_includes/api/en/5x/req.md b/_includes/api/en/5x/req.md deleted file mode 100644 index 7b330b88f8..0000000000 --- a/_includes/api/en/5x/req.md +++ /dev/null @@ -1,156 +0,0 @@ -

Request

- -The `req` object represents the HTTP request and has properties for the -request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, -the object is always referred to as `req` (and the HTTP response is `res`) but its actual name is determined -by the parameters to the callback function in which you're working. - -For example: - -```js -app.get('/user/:id', (req, res) => { - res.send(`user ${req.params.id}`) -}) -``` - -But you could just as well have: - -```js -app.get('/user/:id', (request, response) => { - response.send(`user ${request.params.id}`) -}) -``` - -The `req` object is an enhanced version of Node's own request object -and supports all [built-in fields and methods](https://nodejs.org/api/http.html#http_class_http_incomingmessage). - -

Properties

- -
-In Express 4, `req.files` is no longer available on the `req` object by default. To access uploaded files -on the `req.files` object, use multipart-handling middleware like [busboy](https://www.npmjs. -com/package/busboy), [multer](https://www.npmjs.com/package/multer), -[formidable](https://www.npmjs.com/package/formidable), -[multiparty](https://www.npmjs.com/package/multiparty), -[connect-multiparty](https://www.npmjs.com/package/connect-multiparty), -or [pez](https://www.npmjs.com/package/pez). -
- -
- {% include api/en/5x/req-app.md %} -
- -
- {% include api/en/5x/req-baseUrl.md %} -
- -
- {% include api/en/5x/req-body.md %} -
- -
- {% include api/en/5x/req-cookies.md %} -
- -
- {% include api/en/5x/req-fresh.md %} -
- -
- {% include api/en/5x/req-host.md %} -
- -
- {% include api/en/5x/req-hostname.md %} -
- -
- {% include api/en/5x/req-ip.md %} -
- -
- {% include api/en/5x/req-ips.md %} -
- -
- {% include api/en/5x/req-method.md %} -
- -
- {% include api/en/5x/req-originalUrl.md %} -
- -
- {% include api/en/5x/req-params.md %} -
- -
- {% include api/en/5x/req-path.md %} -
- -
- {% include api/en/5x/req-protocol.md %} -
- -
- {% include api/en/5x/req-query.md %} -
- -
- {% include api/en/5x/req-res.md %} -
- -
- {% include api/en/5x/req-route.md %} -
- -
- {% include api/en/5x/req-secure.md %} -
- -
- {% include api/en/5x/req-signedCookies.md %} -
- -
- {% include api/en/5x/req-stale.md %} -
- -
- {% include api/en/5x/req-subdomains.md %} -
- -
- {% include api/en/5x/req-xhr.md %} -
- -

Methods

- -
- {% include api/en/5x/req-accepts.md %} -
- -
- {% include api/en/5x/req-acceptsCharsets.md %} -
- -
- {% include api/en/5x/req-acceptsEncodings.md %} -
- -
- {% include api/en/5x/req-acceptsLanguages.md %} -
- -
- {% include api/en/5x/req-get.md %} -
- -
- {% include api/en/5x/req-is.md %} -
- -
- {% include api/en/5x/req-range.md %} -
- diff --git a/_includes/api/en/5x/res-app.md b/_includes/api/en/5x/res-app.md deleted file mode 100644 index 19d8681d23..0000000000 --- a/_includes/api/en/5x/res-app.md +++ /dev/null @@ -1,5 +0,0 @@ -

res.app

- -This property holds a reference to the instance of the Express application that is using the middleware. - -`res.app` is identical to the [req.app](#req.app) property in the request object. diff --git a/_includes/api/en/5x/res-append.md b/_includes/api/en/5x/res-append.md deleted file mode 100644 index 2522d827ba..0000000000 --- a/_includes/api/en/5x/res-append.md +++ /dev/null @@ -1,16 +0,0 @@ -

res.append(field [, value])

- -
-`res.append()` is supported by Express v4.11.0+ -
- -Appends the specified `value` to the HTTP response header `field`. If the header is not already set, -it creates the header with the specified value. The `value` parameter can be a string or an array. - -{% include admonitions/note.html content="calling `res.set()` after `res.append()` will reset the previously-set header value." %} - -```js -res.append('Link', ['', '']) -res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly') -res.append('Warning', '199 Miscellaneous warning') -``` diff --git a/_includes/api/en/5x/res-attachment.md b/_includes/api/en/5x/res-attachment.md deleted file mode 100644 index 73556bece4..0000000000 --- a/_includes/api/en/5x/res-attachment.md +++ /dev/null @@ -1,14 +0,0 @@ -

res.attachment([filename])

- -Sets the HTTP response `Content-Disposition` header field to "attachment". If a `filename` is given, -then it sets the `Content-Type` based on the extension name via `res.type()`, -and sets the `Content-Disposition` "filename=" parameter. - -```js -res.attachment() -// Content-Disposition: attachment - -res.attachment('path/to/logo.png') -// Content-Disposition: attachment; filename="logo.png" -// Content-Type: image/png -``` diff --git a/_includes/api/en/5x/res-clearCookie.md b/_includes/api/en/5x/res-clearCookie.md deleted file mode 100644 index de90e2471b..0000000000 --- a/_includes/api/en/5x/res-clearCookie.md +++ /dev/null @@ -1,14 +0,0 @@ -

res.clearCookie(name [, options])

- -Clears the cookie specified by `name`. For details about the `options` object, see [res.cookie()](#res.cookie). - -
-Web browsers and other compliant clients will only clear the cookie if the given -`options` is identical to those given to [res.cookie()](#res.cookie), excluding -`expires` and `maxAge`. -
- -```js -res.cookie('name', 'tobi', { path: '/admin' }) -res.clearCookie('name', { path: '/admin' }) -``` diff --git a/_includes/api/en/5x/res-cookie.md b/_includes/api/en/5x/res-cookie.md deleted file mode 100644 index c06e9142a7..0000000000 --- a/_includes/api/en/5x/res-cookie.md +++ /dev/null @@ -1,69 +0,0 @@ -

res.cookie(name, value [, options])

- -Sets cookie `name` to `value`. The `value` parameter may be a string or object converted to JSON. - -The `options` parameter is an object that can have the following properties. - -| Property | Type | Description | -|-------------|-------------------------------------------------------------------------| -| `domain` | String | Domain name for the cookie. Defaults to the domain name of the app. -| `encode` | Function | A synchronous function used for cookie value encoding. Defaults to `encodeURIComponent`. -| `expires` | Date | Expiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie. -| `httpOnly` | Boolean | Flags the cookie to be accessible only by the web server. -| `maxAge` | Number | Convenient option for setting the expiry time relative to the current time in milliseconds. -| `path` | String | Path for the cookie. Defaults to "/". -| `secure` | Boolean | Marks the cookie to be used with HTTPS only. -| `signed` | Boolean | Indicates if the cookie should be signed. -| `sameSite` | Boolean or String | Value of the "SameSite" **Set-Cookie** attribute. More information at [https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1](https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1). - -
-All `res.cookie()` does is set the HTTP `Set-Cookie` header with the options provided. -Any option not specified defaults to the value stated in [RFC 6265](http://tools.ietf.org/html/rfc6265). -
- -For example: - -```js -res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true }) -res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }) -``` - -The `encode` option allows you to choose the function used for cookie value encoding. -Does not support asynchronous functions. - -Example use case: You need to set a domain-wide cookie for another site in your organization. -This other site (not under your administrative control) does not use URI-encoded cookie values. - -```js -// Default encoding -res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com' }) -// Result: 'some_cross_domain_cookie=http%3A%2F%2Fmysubdomain.example.com; Domain=example.com; Path=/' - -// Custom encoding -res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com', encode: String }) -// Result: 'some_cross_domain_cookie=http://mysubdomain.example.com; Domain=example.com; Path=/;' -``` - -The `maxAge` option is a convenience option for setting "expires" relative to the current time in milliseconds. -The following is equivalent to the second example above. - -```js -res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) -``` - -You can pass an object as the `value` parameter; it is then serialized as JSON and parsed by `bodyParser()` middleware. - -```js -res.cookie('cart', { items: [1, 2, 3] }) -res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 }) -``` - -When using [cookie-parser](https://www.npmjs.com/package/cookie-parser) middleware, this method also -supports signed cookies. Simply include the `signed` option set to `true`. -Then, `res.cookie()` will use the secret passed to `cookieParser(secret)` to sign the value. - -```js -res.cookie('name', 'tobi', { signed: true }) -``` - -Later, you may access this value through the [req.signedCookies](#req.signedCookies) object. diff --git a/_includes/api/en/5x/res-download.md b/_includes/api/en/5x/res-download.md deleted file mode 100644 index a50df3fc86..0000000000 --- a/_includes/api/en/5x/res-download.md +++ /dev/null @@ -1,49 +0,0 @@ -

res.download(path [, filename] [, options] [, fn])

- -
-The optional `options` argument is supported by Express v4.16.0 onwards. -
- -Transfers the file at `path` as an "attachment". Typically, browsers will prompt the user for download. -By default, the `Content-Disposition` header "filename=" parameter is derived from the `path` argument, but can be overridden with the `filename` parameter. -If `path` is relative, then it will be based on the current working directory of the process. - -The following table provides details on the `options` parameter. - -
-The optional `options` argument is supported by Express v4.16.0 onwards. -
- -
- -| Property | Description | Default | Availability | -|-----------------|-------------------------------------------------|-------------|--------------| -| `maxAge` | Sets the max-age property of the `Cache-Control` header in milliseconds or a string in [ms format](https://www.npmjs.org/package/ms)| 0 | 4.16+ | -| `lastModified` | Sets the `Last-Modified` header to the last modified date of the file on the OS. Set `false` to disable it.| Enabled | 4.16+ | -| `headers` | Object containing HTTP headers to serve with the file. The header `Content-Disposition` will be overridden by the `filename` argument.| | 4.16+ | -| `dotfiles` | Option for serving dotfiles. Possible values are "allow", "deny", "ignore".| "ignore" | 4.16+ | -| `acceptRanges` | Enable or disable accepting ranged requests. | `true` | 4.16+ | -| `cacheControl` | Enable or disable setting `Cache-Control` response header.| `true` | 4.16+ | -| `immutable` | Enable or disable the `immutable` directive in the `Cache-Control` response header. If enabled, the `maxAge` option should also be specified to enable caching. The `immutable` directive will prevent supported clients from making conditional requests during the life of the `maxAge` option to check if the file has changed. | `false` | 4.16+ | - -
- -The method invokes the callback function `fn(err)` when the transfer is complete -or when an error occurs. If the callback function is specified and an error occurs, -the callback function must explicitly handle the response process either by -ending the request-response cycle, or by passing control to the next route. - -```js -res.download('/report-12345.pdf') - -res.download('/report-12345.pdf', 'report.pdf') - -res.download('/report-12345.pdf', 'report.pdf', (err) => { - if (err) { - // Handle error, but keep in mind the response may be partially-sent - // so check res.headersSent - } else { - // decrement a download credit, etc. - } -}) -``` diff --git a/_includes/api/en/5x/res-end.md b/_includes/api/en/5x/res-end.md deleted file mode 100644 index 2906805fea..0000000000 --- a/_includes/api/en/5x/res-end.md +++ /dev/null @@ -1,10 +0,0 @@ -

res.end([data[, encoding]][, callback])

- -Ends the response process. This method actually comes from Node core, specifically the [response.end() method of http.ServerResponse](https://nodejs.org/api/http.html#responseenddata-encoding-callback). - -Use to quickly end the response without any data. If you need to respond with data, instead use methods such as [res.send()](#res.send) and [res.json()](#res.json). - -```js -res.end() -res.status(404).end() -``` diff --git a/_includes/api/en/5x/res-format.md b/_includes/api/en/5x/res-format.md deleted file mode 100644 index 1a5a3d7a5a..0000000000 --- a/_includes/api/en/5x/res-format.md +++ /dev/null @@ -1,52 +0,0 @@ -

res.format(object)

- -Performs content-negotiation on the `Accept` HTTP header on the request object, when present. -It uses [req.accepts()](#req.accepts) to select a handler for the request, based on the acceptable -types ordered by their quality values. If the header is not specified, the first callback is invoked. -When no match is found, the server responds with 406 "Not Acceptable", or invokes the `default` callback. - -The `Content-Type` response header is set when a callback is selected. However, you may alter -this within the callback using methods such as `res.set()` or `res.type()`. - -The following example would respond with `{ "message": "hey" }` when the `Accept` header field is set -to "application/json" or "\*/json" (however, if it is "\*/\*", then the response will be "hey"). - -```js -res.format({ - 'text/plain' () { - res.send('hey') - }, - - 'text/html' () { - res.send('

hey

') - }, - - 'application/json' () { - res.send({ message: 'hey' }) - }, - - default () { - // log the request and respond with 406 - res.status(406).send('Not Acceptable') - } -}) -``` - -In addition to canonicalized MIME types, you may also use extension names mapped -to these types for a slightly less verbose implementation: - -```js -res.format({ - text () { - res.send('hey') - }, - - html () { - res.send('

hey

') - }, - - json () { - res.send({ message: 'hey' }) - } -}) -``` diff --git a/_includes/api/en/5x/res-get.md b/_includes/api/en/5x/res-get.md deleted file mode 100644 index 8aefb205ef..0000000000 --- a/_includes/api/en/5x/res-get.md +++ /dev/null @@ -1,9 +0,0 @@ -

res.get(field)

- -Returns the HTTP response header specified by `field`. -The match is case-insensitive. - -```js -res.get('Content-Type') -// => "text/plain" -``` diff --git a/_includes/api/en/5x/res-headersSent.md b/_includes/api/en/5x/res-headersSent.md deleted file mode 100644 index 1bbe06d1b3..0000000000 --- a/_includes/api/en/5x/res-headersSent.md +++ /dev/null @@ -1,11 +0,0 @@ -

res.headersSent

- -Boolean property that indicates if the app sent HTTP headers for the response. - -```js -app.get('/', (req, res) => { - console.log(res.headersSent) // false - res.send('OK') - console.log(res.headersSent) // true -}) -``` diff --git a/_includes/api/en/5x/res-json.md b/_includes/api/en/5x/res-json.md deleted file mode 100644 index 8e699a7ed5..0000000000 --- a/_includes/api/en/5x/res-json.md +++ /dev/null @@ -1,13 +0,0 @@ -

res.json([body])

- -Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a -JSON string using [JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). - -The parameter can be any JSON type, including object, array, string, Boolean, number, or null, -and you can also use it to convert other values to JSON. - -```js -res.json(null) -res.json({ user: 'tobi' }) -res.status(500).json({ error: 'message' }) -``` diff --git a/_includes/api/en/5x/res-jsonp.md b/_includes/api/en/5x/res-jsonp.md deleted file mode 100644 index edb7e45466..0000000000 --- a/_includes/api/en/5x/res-jsonp.md +++ /dev/null @@ -1,32 +0,0 @@ -

res.jsonp([body])

- -Sends a JSON response with JSONP support. This method is identical to `res.json()`, -except that it opts-in to JSONP callback support. - -```js -res.jsonp(null) -// => callback(null) - -res.jsonp({ user: 'tobi' }) -// => callback({ "user": "tobi" }) - -res.status(500).jsonp({ error: 'message' }) -// => callback({ "error": "message" }) -``` - -By default, the JSONP callback name is simply `callback`. Override this with the -jsonp callback name setting. - -The following are some examples of JSONP responses using the same code: - -```js -// ?callback=foo -res.jsonp({ user: 'tobi' }) -// => foo({ "user": "tobi" }) - -app.set('jsonp callback name', 'cb') - -// ?cb=foo -res.status(500).jsonp({ error: 'message' }) -// => foo({ "error": "message" }) -``` diff --git a/_includes/api/en/5x/res-links.md b/_includes/api/en/5x/res-links.md deleted file mode 100644 index 17164155d4..0000000000 --- a/_includes/api/en/5x/res-links.md +++ /dev/null @@ -1,20 +0,0 @@ - - -Joins the `links` provided as properties of the parameter to populate the response's -`Link` HTTP header field. - -For example, the following call: - -```js -res.links({ - next: 'http://api.example.com/users?page=2', - last: 'http://api.example.com/users?page=5' -}) -``` - -Yields the following results: - -``` -Link: ; rel="next", - ; rel="last" -``` diff --git a/_includes/api/en/5x/res-locals.md b/_includes/api/en/5x/res-locals.md deleted file mode 100644 index 0bc6faa8e6..0000000000 --- a/_includes/api/en/5x/res-locals.md +++ /dev/null @@ -1,20 +0,0 @@ -

res.locals

- -Use this property to set variables accessible in templates rendered with [res.render](#res.render). -The variables set on `res.locals` are available within a single request-response cycle, and will not -be shared between requests. - -In order to keep local variables for use in template rendering between requests, use -[app.locals](#app.locals) instead. - -This property is useful for exposing request-level information such as the request path name, -authenticated user, user settings, and so on to templates rendered within the application. - -```js -app.use((req, res, next) => { - // Make `user` and `authenticated` available in templates - res.locals.user = req.user - res.locals.authenticated = !req.user.anonymous - next() -}) -``` diff --git a/_includes/api/en/5x/res-location.md b/_includes/api/en/5x/res-location.md deleted file mode 100644 index ba5e943e6c..0000000000 --- a/_includes/api/en/5x/res-location.md +++ /dev/null @@ -1,22 +0,0 @@ -

res.location(path)

- -Sets the response `Location` HTTP header to the specified `path` parameter. - -```js -res.location('/foo/bar') -res.location('http://example.com') -res.location('back') -``` - -A `path` value of "back" has a special meaning, it refers to the URL specified in the `Referer` header of the request. If the `Referer` header was not specified, it refers to "/". - -See also [Security best practices: Prevent open redirect -vulnerabilities](http://expressjs.com/en/advanced/best-practice-security.html#prevent-open-redirects). - -
-After encoding the URL, if not encoded already, Express passes the specified URL to the browser in the `Location` header, -without any validation. - -Browsers take the responsibility of deriving the intended URL from the current URL -or the referring URL, and the URL specified in the `Location` header; and redirect the user accordingly. -
diff --git a/_includes/api/en/5x/res-redirect.md b/_includes/api/en/5x/res-redirect.md deleted file mode 100644 index d849120f7e..0000000000 --- a/_includes/api/en/5x/res-redirect.md +++ /dev/null @@ -1,56 +0,0 @@ -

res.redirect([status,] path)

- -Redirects to the URL derived from the specified `path`, with specified `status`, a positive integer -that corresponds to an [HTTP status code](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html). -If not specified, `status` defaults to `302 "Found"`. - -```js -res.redirect('/foo/bar') -res.redirect('http://example.com') -res.redirect(301, 'http://example.com') -res.redirect('../login') -``` -Redirects can be a fully-qualified URL for redirecting to a different site: - -```js -res.redirect('http://google.com') -``` -Redirects can be relative to the root of the host name. For example, if the -application is on `http://example.com/admin/post/new`, the following -would redirect to the URL `http://example.com/admin`: - -```js -res.redirect('/admin') -``` - -Redirects can be relative to the current URL. For example, -from `http://example.com/blog/admin/` (notice the trailing slash), the following -would redirect to the URL `http://example.com/blog/admin/post/new`. - -```js -res.redirect('post/new') -``` - -Redirecting to `post/new` from `http://example.com/blog/admin` (no trailing slash), -will redirect to `http://example.com/blog/post/new`. - -If you found the above behavior confusing, think of path segments as directories -(with trailing slashes) and files, it will start to make sense. - -Path-relative redirects are also possible. If you were on -`http://example.com/admin/post/new`, the following would redirect to -`http://example.com/admin/post`: - -```js -res.redirect('..') -``` - -A `back` redirection redirects the request back to the [referer](http://en.wikipedia.org/wiki/HTTP_referer), -defaulting to `/` when the referer is missing. - -```js -res.redirect('back') -``` - -See also [Security best practices: Prevent open redirect -vulnerabilities](http://expressjs.com/en/advanced/best-practice-security.html#prevent-open-redirects). \ No newline at end of file diff --git a/_includes/api/en/5x/res-render.md b/_includes/api/en/5x/res-render.md deleted file mode 100644 index 5a4efbc834..0000000000 --- a/_includes/api/en/5x/res-render.md +++ /dev/null @@ -1,31 +0,0 @@ -

res.render(view [, locals] [, callback])

- -Renders a `view` and sends the rendered HTML string to the client. -Optional parameters: - -- `locals`, an object whose properties define local variables for the view. -- `callback`, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method invokes `next(err)` internally. - -The `view` argument is a string that is the file path of the view file to render. This can be an absolute path, or a path relative to the `views` setting. If the path does not contain a file extension, then the `view engine` setting determines the file extension. If the path does contain a file extension, then Express will load the module for the specified template engine (via `require()`) and render it using the loaded module's `__express` function. - -For more information, see [Using template engines with Express](/{{page.lang}}/guide/using-template-engines.html). - -{% include admonitions/note.html content="The `view` argument performs file system operations like reading a file from disk and evaluating Node.js modules, and as so for security reasons should not contain input from the end-user." %} - -{% include admonitions/caution.html content="The local variable `cache` enables view caching. Set it to `true`, -to cache the view during development; view caching is enabled in production by default." %} - -```js -// send the rendered view to the client -res.render('index') - -// if a callback is specified, the rendered HTML string has to be sent explicitly -res.render('index', (err, html) => { - res.send(html) -}) - -// pass a local variable to the view -res.render('user', { name: 'Tobi' }, (err, html) => { - // ... -}) -``` diff --git a/_includes/api/en/5x/res-req.md b/_includes/api/en/5x/res-req.md deleted file mode 100644 index 8763653d9f..0000000000 --- a/_includes/api/en/5x/res-req.md +++ /dev/null @@ -1,4 +0,0 @@ -

res.req

- -This property holds a reference to the request object -that relates to this response object. diff --git a/_includes/api/en/5x/res-send.md b/_includes/api/en/5x/res-send.md deleted file mode 100644 index ba46abd399..0000000000 --- a/_includes/api/en/5x/res-send.md +++ /dev/null @@ -1,39 +0,0 @@ -

res.send([body])

- -Sends the HTTP response. - -The `body` parameter can be a `Buffer` object, a `String`, an object, `Boolean`, or an `Array`. -For example: - -```js -res.send(Buffer.from('whoop')) -res.send({ some: 'json' }) -res.send('

some html

') -res.status(404).send('Sorry, we cannot find that!') -res.status(500).send({ error: 'something blew up' }) -``` - -This method performs many useful tasks for simple non-streaming responses: -For example, it automatically assigns the `Content-Length` HTTP response header field -and provides automatic HEAD and HTTP cache freshness support. - -When the parameter is a `Buffer` object, the method sets the `Content-Type` -response header field to "application/octet-stream", unless previously defined as shown below: - -```js -res.set('Content-Type', 'text/html') -res.send(Buffer.from('

some html

')) -``` - -When the parameter is a `String`, the method sets the `Content-Type` to "text/html": - -```js -res.send('

some html

') -``` - -When the parameter is an `Array` or `Object`, Express responds with the JSON representation: - -```js -res.send({ user: 'tobi' }) -res.send([1, 2, 3]) -``` diff --git a/_includes/api/en/5x/res-sendFile.md b/_includes/api/en/5x/res-sendFile.md deleted file mode 100644 index e415a21dc6..0000000000 --- a/_includes/api/en/5x/res-sendFile.md +++ /dev/null @@ -1,84 +0,0 @@ -

res.sendFile(path [, options] [, fn])

- -
-`res.sendFile()` is supported by Express v4.8.0 onwards. -
- -Transfers the file at the given `path`. Sets the `Content-Type` response HTTP header field -based on the filename's extension. Unless the `root` option is set in -the options object, `path` must be an absolute path to the file. - -
-This API provides access to data on the running file system. Ensure that either (a) the way in -which the `path` argument was constructed into an absolute path is secure if it contains user -input or (b) set the `root` option to the absolute path of a directory to contain access within. - -When the `root` option is provided, the `path` argument is allowed to be a relative path, -including containing `..`. Express will validate that the relative path provided as `path` will -resolve within the given `root` option. -
- -The following table provides details on the `options` parameter. - -
- -| Property | Description | Default | Availability | -|-----------------|-------------------------------------------------|-------------|--------------| -|`maxAge` | Sets the max-age property of the `Cache-Control` header in milliseconds or a string in [ms format](https://www.npmjs.org/package/ms)| 0 | | -| `root` | Root directory for relative filenames.| | | -| `lastModified` | Sets the `Last-Modified` header to the last modified date of the file on the OS. Set `false` to disable it.| Enabled | 4.9.0+ | -| `headers` | Object containing HTTP headers to serve with the file.| | | -| `dotfiles` | Option for serving dotfiles. Possible values are "allow", "deny", "ignore".| "ignore" |   | -| `acceptRanges` | Enable or disable accepting ranged requests. | `true` | 4.14+ | -| `cacheControl` | Enable or disable setting `Cache-Control` response header.| `true` | 4.14+ | -| `immutable` | Enable or disable the `immutable` directive in the `Cache-Control` response header. If enabled, the `maxAge` option should also be specified to enable caching. The `immutable` directive will prevent supported clients from making conditional requests during the life of the `maxAge` option to check if the file has changed. | `false` | 4.16+ | - -
- -The method invokes the callback function `fn(err)` when the transfer is complete -or when an error occurs. If the callback function is specified and an error occurs, -the callback function must explicitly handle the response process either by -ending the request-response cycle, or by passing control to the next route. - -Here is an example of using `res.sendFile` with all its arguments. - -```js -app.get('/file/:name', (req, res, next) => { - const options = { - root: path.join(__dirname, 'public'), - dotfiles: 'deny', - headers: { - 'x-timestamp': Date.now(), - 'x-sent': true - } - } - - const fileName = req.params.name - res.sendFile(fileName, options, (err) => { - if (err) { - next(err) - } else { - console.log('Sent:', fileName) - } - }) -}) -``` - -The following example illustrates using -`res.sendFile` to provide fine-grained support for serving files: - -```js -app.get('/user/:uid/photos/:file', (req, res) => { - const uid = req.params.uid - const file = req.params.file - - req.user.mayViewFilesFrom(uid, (yes) => { - if (yes) { - res.sendFile(`/uploads/${uid}/${file}`) - } else { - res.status(403).send("Sorry! You can't see that.") - } - }) -}) -``` -For more information, or if you have issues or concerns, see [send](https://github.com/pillarjs/send). diff --git a/_includes/api/en/5x/res-sendStatus.md b/_includes/api/en/5x/res-sendStatus.md deleted file mode 100644 index fe819bdfcf..0000000000 --- a/_includes/api/en/5x/res-sendStatus.md +++ /dev/null @@ -1,15 +0,0 @@ -

res.sendStatus(statusCode)

- -Sets the response HTTP status code to `statusCode` and sends the registered status message as the text response body. If an unknown status code is specified, the response body will just be the code number. - -```js -res.sendStatus(404) -``` - -
-Some versions of Node.js will throw when `res.statusCode` is set to an -invalid HTTP status code (outside of the range `100` to `599`). Consult -the HTTP server documentation for the Node.js version being used. -
- -[More about HTTP Status Codes](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes) diff --git a/_includes/api/en/5x/res-set.md b/_includes/api/en/5x/res-set.md deleted file mode 100644 index b91698d4b1..0000000000 --- a/_includes/api/en/5x/res-set.md +++ /dev/null @@ -1,16 +0,0 @@ -

res.set(field [, value])

- -Sets the response's HTTP header `field` to `value`. -To set multiple fields at once, pass an object as the parameter. - -```js -res.set('Content-Type', 'text/plain') - -res.set({ - 'Content-Type': 'text/plain', - 'Content-Length': '123', - ETag: '12345' -}) -``` - -Aliased as `res.header(field [, value])`. diff --git a/_includes/api/en/5x/res-status.md b/_includes/api/en/5x/res-status.md deleted file mode 100644 index 9cb9d44e94..0000000000 --- a/_includes/api/en/5x/res-status.md +++ /dev/null @@ -1,10 +0,0 @@ -

res.status(code)

- -Sets the HTTP status for the response. -It is a chainable alias of Node's [response.statusCode](http://nodejs.org/api/http.html#http_response_statuscode). - -```js -res.status(403).end() -res.status(400).send('Bad Request') -res.status(404).sendFile('/absolute/path/to/404.png') -``` diff --git a/_includes/api/en/5x/res-type.md b/_includes/api/en/5x/res-type.md deleted file mode 100644 index d488cfd11b..0000000000 --- a/_includes/api/en/5x/res-type.md +++ /dev/null @@ -1,11 +0,0 @@ -

res.type(type)

- -Sets the `Content-Type` HTTP header to the MIME type as determined by the specified `type`. If `type` contains the "/" character, then it sets the `Content-Type` to the exact value of `type`, otherwise it is assumed to be a file extension and the MIME type is looked up in a mapping using the `express.static.mime.lookup()` method. - -```js -res.type('.html') // => 'text/html' -res.type('html') // => 'text/html' -res.type('json') // => 'application/json' -res.type('application/json') // => 'application/json' -res.type('png') // => image/png: -``` diff --git a/_includes/api/en/5x/res-vary.md b/_includes/api/en/5x/res-vary.md deleted file mode 100644 index 956aab25ae..0000000000 --- a/_includes/api/en/5x/res-vary.md +++ /dev/null @@ -1,7 +0,0 @@ -

res.vary(field)

- -Adds the field to the `Vary` response header, if it is not there already. - -```js -res.vary('User-Agent').render('docs') -``` diff --git a/_includes/api/en/5x/res.md b/_includes/api/en/5x/res.md deleted file mode 100644 index a26c2c7d14..0000000000 --- a/_includes/api/en/5x/res.md +++ /dev/null @@ -1,130 +0,0 @@ -

Response

- -The `res` object represents the HTTP response that an Express app sends when it gets an HTTP request. - -In this documentation and by convention, -the object is always referred to as `res` (and the HTTP request is `req`) but its actual name is determined -by the parameters to the callback function in which you're working. - -For example: - -```js -app.get('/user/:id', (req, res) => { - res.send(`user ${req.params.id}`) -}) -``` - -But you could just as well have: - -```js -app.get('/user/:id', (request, response) => { - response.send(`user ${request.params.id}`) -}) -``` - -The `res` object is an enhanced version of Node's own response object -and supports all [built-in fields and methods](https://nodejs.org/api/http.html#http_class_http_serverresponse). - -

Properties

- -
- {% include api/en/5x/res-app.md %} -
- -
- {% include api/en/5x/res-headersSent.md %} -
- -
- {% include api/en/5x/res-locals.md %} -
- -
- {% include api/en/5x/res-req.md %} -
- -

Methods

- -
- {% include api/en/5x/res-append.md %} -
- -
- {% include api/en/5x/res-attachment.md %} -
- -
- {% include api/en/5x/res-cookie.md %} -
- -
- {% include api/en/5x/res-clearCookie.md %} -
- -
- {% include api/en/5x/res-download.md %} -
- -
- {% include api/en/5x/res-end.md %} -
- -
- {% include api/en/5x/res-format.md %} -
- -
- {% include api/en/5x/res-get.md %} -
- -
- {% include api/en/5x/res-json.md %} -
- -
- {% include api/en/5x/res-jsonp.md %} -
- -
- {% include api/en/5x/res-links.md %} -
- -
- {% include api/en/5x/res-location.md %} -
- -
- {% include api/en/5x/res-redirect.md %} -
- -
- {% include api/en/5x/res-render.md %} -
- -
- {% include api/en/5x/res-send.md %} -
- -
- {% include api/en/5x/res-sendFile.md %} -
- -
- {% include api/en/5x/res-sendStatus.md %} -
- -
- {% include api/en/5x/res-set.md %} -
- -
- {% include api/en/5x/res-status.md %} -
- -
- {% include api/en/5x/res-type.md %} -
- -
- {% include api/en/5x/res-vary.md %} -
diff --git a/_includes/api/en/5x/router-METHOD.md b/_includes/api/en/5x/router-METHOD.md deleted file mode 100644 index 8f42424566..0000000000 --- a/_includes/api/en/5x/router-METHOD.md +++ /dev/null @@ -1,66 +0,0 @@ -

router.METHOD(path, [callback, ...] callback)

- -The `router.METHOD()` methods provide the routing functionality in Express, -where METHOD is one of the HTTP methods, such as GET, PUT, POST, and so on, -in lowercase. Thus, the actual methods are `router.get()`, `router.post()`, -`router.put()`, and so on. - -
- The `router.get()` function is automatically called for the HTTP `HEAD` method in - addition to the `GET` method if `router.head()` was not called for the - path before `router.get()`. -
- -You can provide multiple callbacks, and all are treated equally, and behave just -like middleware, except that these callbacks may invoke `next('route')` -to bypass the remaining route callback(s). You can use this mechanism to perform -pre-conditions on a route then pass control to subsequent routes when there is no -reason to proceed with the route matched. - -The following snippet illustrates the most simple route definition possible. -Express translates the path strings to regular expressions, used internally -to match incoming requests. Query strings are _not_ considered when performing -these matches, for example "GET /" would match the following route, as would -"GET /?name=tobi". - -```js -router.get('/', (req, res) => { - res.send('hello world') -}) -``` - -You can also use regular expressions—useful if you have very specific -constraints, for example the following would match "GET /commits/71dbb9c" as well -as "GET /commits/71dbb9c..4c084f9". - -```js -router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, (req, res) => { - const from = req.params[0] - const to = req.params[1] || 'HEAD' - res.send(`commit range ${from}..${to}`) -}) -``` - -You can use `next` primitive to implement a flow control between different -middleware functions, based on a specific program state. Invoking `next` with -the string `'router'` will cause all the remaining route callbacks on that router -to be bypassed. - -The following example illustrates `next('router')` usage. - -```js -function fn (req, res, next) { - console.log('I come here') - next('router') -} -router.get('/foo', fn, (req, res, next) => { - console.log('I dont come here') -}) -router.get('/foo', (req, res, next) => { - console.log('I dont come here') -}) -app.get('/foo', (req, res) => { - console.log(' I come here too') - res.end('good') -}) -``` diff --git a/_includes/api/en/5x/router-Router.md b/_includes/api/en/5x/router-Router.md deleted file mode 100644 index 664ffb34c2..0000000000 --- a/_includes/api/en/5x/router-Router.md +++ /dev/null @@ -1,2 +0,0 @@ -

Router([options])

- diff --git a/_includes/api/en/5x/router-all.md b/_includes/api/en/5x/router-all.md deleted file mode 100644 index 359e4d4f8f..0000000000 --- a/_includes/api/en/5x/router-all.md +++ /dev/null @@ -1,31 +0,0 @@ -

router.all(path, [callback, ...] callback)

- -This method is just like the `router.METHOD()` methods, except that it matches all HTTP methods (verbs). - -This method is extremely useful for -mapping "global" logic for specific path prefixes or arbitrary matches. -For example, if you placed the following route at the top of all other -route definitions, it would require that all routes from that point on -would require authentication, and automatically load a user. Keep in mind -that these callbacks do not have to act as end points; `loadUser` -can perform a task, then call `next()` to continue matching subsequent -routes. - -```js -router.all('(.*)', requireAuthentication, loadUser) -``` - -Or the equivalent: - -```js -router.all('(.*)', requireAuthentication) -router.all('(.*)', loadUser) -``` - -Another example of this is white-listed "global" functionality. Here, -the example is much like before, but it only restricts paths prefixed with -"/api": - -```js -router.all('/api/(.*)', requireAuthentication) -``` diff --git a/_includes/api/en/5x/router-param.md b/_includes/api/en/5x/router-param.md deleted file mode 100644 index f2b11d8946..0000000000 --- a/_includes/api/en/5x/router-param.md +++ /dev/null @@ -1,123 +0,0 @@ -

router.param(name, callback)

- -Adds callback triggers to route parameters, where `name` is the name of the parameter and `callback` is the callback function. Although `name` is technically optional, using this method without it is deprecated starting with Express v4.11.0 (see below). - -The parameters of the callback function are: - -- `req`, the request object. -- `res`, the response object. -- `next`, indicating the next middleware function. -- The value of the `name` parameter. -- The name of the parameter. - -
-Unlike `app.param()`, `router.param()` does not accept an array of route parameters. -
- -For example, when `:user` is present in a route path, you may map user loading logic to automatically provide `req.user` to the route, or perform validations on the parameter input. - -```js -router.param('user', (req, res, next, id) => { - // try to get the user details from the User model and attach it to the request object - User.find(id, (err, user) => { - if (err) { - next(err) - } else if (user) { - req.user = user - next() - } else { - next(new Error('failed to load user')) - } - }) -}) -``` - -Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers, nor are they triggered for route parameters inherited from parent routers. Hence, param callbacks defined on `router` will be triggered only by route parameters defined on `router` routes. - -A param callback will be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples. - -```js -router.param('id', (req, res, next, id) => { - console.log('CALLED ONLY ONCE') - next() -}) - -router.get('/user/:id', (req, res, next) => { - console.log('although this matches') - next() -}) - -router.get('/user/:id', (req, res) => { - console.log('and this matches too') - res.end() -}) -``` - -On `GET /user/42`, the following is printed: - -``` -CALLED ONLY ONCE -although this matches -and this matches too -``` - -
-The following section describes `router.param(callback)`, which is deprecated as of v4.11.0. -
- -The behavior of the `router.param(name, callback)` method can be altered entirely by passing only a function to `router.param()`. This function is a custom implementation of how `router.param(name, callback)` should behave - it accepts two parameters and must return a middleware. - -The first parameter of this function is the name of the URL parameter that should be captured, the second parameter can be any JavaScript object which might be used for returning the middleware implementation. - -The middleware returned by the function decides the behavior of what happens when a URL parameter is captured. - -In this example, the `router.param(name, callback)` signature is modified to `router.param(name, accessId)`. Instead of accepting a name and a callback, `router.param()` will now accept a name and a number. - -```js -const express = require('express') -const app = express() -const router = express.Router() - -// customizing the behavior of router.param() -router.param((param, option) => { - return (req, res, next, val) => { - if (val === option) { - next() - } else { - res.sendStatus(403) - } - } -}) - -// using the customized router.param() -router.param('id', 1337) - -// route to trigger the capture -router.get('/user/:id', (req, res) => { - res.send('OK') -}) - -app.use(router) - -app.listen(3000, () => { - console.log('Ready') -}) -``` - -In this example, the `router.param(name, callback)` signature remains the same, but instead of a middleware callback, a custom data type checking function has been defined to validate the data type of the user id. - -```js -router.param((param, validator) => { - return (req, res, next, val) => { - if (validator(val)) { - next() - } else { - res.sendStatus(403) - } - } -}) - -router.param('id', (candidate) => { - return !isNaN(parseFloat(candidate)) && isFinite(candidate) -}) -``` diff --git a/_includes/api/en/5x/router-route.md b/_includes/api/en/5x/router-route.md deleted file mode 100644 index 30b5603ed9..0000000000 --- a/_includes/api/en/5x/router-route.md +++ /dev/null @@ -1,48 +0,0 @@ -

router.route(path)

- -Returns an instance of a single route which you can then use to handle HTTP verbs -with optional middleware. Use `router.route()` to avoid duplicate route naming and -thus typing errors. - -Building on the `router.param()` example above, the following code shows how to use -`router.route()` to specify various HTTP method handlers. - -```js -const router = express.Router() - -router.param('user_id', (req, res, next, id) => { - // sample user, would actually fetch from DB, etc... - req.user = { - id, - name: 'TJ' - } - next() -}) - -router.route('/users/:user_id') - .all((req, res, next) => { - // runs for all HTTP verbs first - // think of it as route specific middleware! - next() - }) - .get((req, res, next) => { - res.json(req.user) - }) - .put((req, res, next) => { - // just an example of maybe updating the user - req.user.name = req.params.name - // save user ... etc - res.json(req.user) - }) - .post((req, res, next) => { - next(new Error('not implemented')) - }) - .delete((req, res, next) => { - next(new Error('not implemented')) - }) -``` - -This approach re-uses the single `/users/:user_id` path and adds handlers for -various HTTP methods. - -{% include admonitions/note.html content="When you use `router.route()`, middleware ordering is based on when the _route_ is created, not when method handlers are added to the route. For this purpose, you can consider method handlers to belong to the route to which they were added." %} diff --git a/_includes/api/en/5x/router-use.md b/_includes/api/en/5x/router-use.md deleted file mode 100644 index 1a0799af7f..0000000000 --- a/_includes/api/en/5x/router-use.md +++ /dev/null @@ -1,106 +0,0 @@ -

router.use([path], [function, ...] function)

- -Uses the specified middleware function or functions, with optional mount path `path`, that defaults to "/". - -This method is similar to [app.use()](#app.use). A simple example and use case is described below. -See [app.use()](#app.use) for more information. - -Middleware is like a plumbing pipe: requests start at the first middleware function defined -and work their way "down" the middleware stack processing for each path they match. - -```js -const express = require('express') -const app = express() -const router = express.Router() - -// simple logger for this router's requests -// all requests to this router will first hit this middleware -router.use((req, res, next) => { - console.log('%s %s %s', req.method, req.url, req.path) - next() -}) - -// this will only be invoked if the path starts with /bar from the mount point -router.use('/bar', (req, res, next) => { - // ... maybe some additional /bar logging ... - next() -}) - -// always invoked -router.use((req, res, next) => { - res.send('Hello World') -}) - -app.use('/foo', router) - -app.listen(3000) -``` - -The "mount" path is stripped and is _not_ visible to the middleware function. -The main effect of this feature is that a mounted middleware function may operate without -code changes regardless of its "prefix" pathname. - -The order in which you define middleware with `router.use()` is very important. -They are invoked sequentially, thus the order defines middleware precedence. For example, -usually a logger is the very first middleware you would use, so that every request gets logged. - -```js -const logger = require('morgan') - -router.use(logger()) -router.use(express.static(path.join(__dirname, 'public'))) -router.use((req, res) => { - res.send('Hello') -}) -``` - -Now suppose you wanted to ignore logging requests for static files, but to continue -logging routes and middleware defined after `logger()`. You would simply move the call to `express.static()` to the top, -before adding the logger middleware: - -```js -router.use(express.static(path.join(__dirname, 'public'))) -router.use(logger()) -router.use((req, res) => { - res.send('Hello') -}) -``` - -Another example is serving files from multiple directories, -giving precedence to "./public" over the others: - -```js -app.use(express.static(path.join(__dirname, 'public'))) -app.use(express.static(path.join(__dirname, 'files'))) -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_ -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: - -```js -const authRouter = express.Router() -const openRouter = express.Router() - -authRouter.use(require('./authenticate').basic(usersdb)) - -authRouter.get('/:user_id/edit', (req, res, next) => { - // ... Edit user UI ... -}) -openRouter.get('/', (req, res, next) => { - // ... List users ... -}) -openRouter.get('/:user_id', (req, res, next) => { - // ... View user ... -}) - -app.use('/users', authRouter) -app.use('/users', openRouter) -``` - -Even though the authentication middleware was added via the `authRouter` it will run on the routes defined by the `openRouter` as well since both routers were mounted on `/users`. To avoid this behavior, use different paths for each router. diff --git a/_includes/api/en/5x/router.md b/_includes/api/en/5x/router.md deleted file mode 100644 index 26eb778ca9..0000000000 --- a/_includes/api/en/5x/router.md +++ /dev/null @@ -1,62 +0,0 @@ -

Router

- -
-A `router` object is an instance of middleware and routes. You can think of it -as a "mini-application," capable only of performing middleware and routing -functions. Every Express application has a built-in app router. - -A router behaves like middleware itself, so you can use it as an argument to -[app.use()](#app.use) or as the argument to another router's [use()](#router.use) method. - -The top-level `express` object has a [Router()](#express.router) method that creates a new `router` object. - -Once you've created a router object, you can add middleware and HTTP method routes (such as `get`, `put`, `post`, -and so on) to it just like an application. For example: - -```js -// invoked for any requests passed to this router -router.use((req, res, next) => { - // .. some logic here .. like any other middleware - next() -}) - -// will handle any request that ends in /events -// depends on where the router is "use()'d" -router.get('/events', (req, res, next) => { - // .. -}) -``` - -You can then use a router for a particular root URL in this way separating your routes into files or even mini-apps. - -```js -// only requests to /calendar/* will be sent to our "router" -app.use('/calendar', router) -``` - -Keep in mind that any middleware applied to a router will run for all requests on that router's path, even those that aren't part of the router. - - -
- -

Methods

- -
- {% include api/en/5x/router-all.md %} -
- -
- {% include api/en/5x/router-METHOD.md %} -
- -
- {% include api/en/5x/router-param.md %} -
- -
- {% include api/en/5x/router-route.md %} -
- -
- {% include api/en/5x/router-use.md %} -
diff --git a/_includes/api/en/5x/routing-args.html b/_includes/api/en/5x/routing-args.html deleted file mode 100644 index 7ad66fdbc4..0000000000 --- a/_includes/api/en/5x/routing-args.html +++ /dev/null @@ -1,51 +0,0 @@ -

Arguments

- - - - - - - - - - - - - - - - - - -
Argument Description Default
path -The path for which the middleware function is invoked; can be any of: -
    -
  • A string representing a path.
  • -
  • A path pattern.
  • -
  • A regular expression pattern to match paths.
  • -
  • An array of combinations of any of the above.
  • -
- -For examples, see Path examples. -
'/' (root path)
callback -Callback functions; can be: -
    -
  • A middleware function.
  • -
  • A series of middleware functions (separated by commas).
  • -
  • An array of middleware functions.
  • -
  • A combination of all of the above.
  • -
-

-You can provide multiple callback functions that behave just like middleware, except -that these callbacks can invoke next('route') to bypass -the remaining route callback(s). You can use this mechanism to impose pre-conditions -on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. -

-When a callback function throws an error or returns a rejected promise, `next(err)` will be invoked automatically. -

-Since router and app implement the middleware interface, -you can use them as you would any other middleware function. -

-For examples, see Middleware callback function examples. -

-
None
diff --git a/_includes/blog/posts-menu.md b/_includes/blog/posts-menu.md deleted file mode 100644 index 5afe3f32c7..0000000000 --- a/_includes/blog/posts-menu.md +++ /dev/null @@ -1,12 +0,0 @@ -
-

- Posts -

- -
diff --git a/_includes/blog/tags-menu.md b/_includes/blog/tags-menu.md deleted file mode 100644 index 8b722e9cec..0000000000 --- a/_includes/blog/tags-menu.md +++ /dev/null @@ -1,10 +0,0 @@ -
    - {% for tag in site.tags %} -
  • {{ tag[0] }}
  • - -{% endfor %} -
diff --git a/_includes/changelog/menu.md b/_includes/changelog/menu.md deleted file mode 100644 index ae4ca191c2..0000000000 --- a/_includes/changelog/menu.md +++ /dev/null @@ -1,4 +0,0 @@ -### Versions - -- [5.x](#5.x) -- [4.x](#4.x) \ No newline at end of file diff --git a/_includes/community-caveat.html b/_includes/community-caveat.html deleted file mode 100644 index 6cd463141f..0000000000 --- a/_includes/community-caveat.html +++ /dev/null @@ -1,4 +0,0 @@ -{% include admonitions/warning.html content="This information refers to third-party sites, -products, or modules that are not maintained by the Expressjs team. Listing here does not constitute -an endorsement or recommendation from the Expressjs project team. -" %} diff --git a/_includes/footer/_docsearch.html b/_includes/footer/_docsearch.html deleted file mode 100644 index d6fa0c65d1..0000000000 --- a/_includes/footer/_docsearch.html +++ /dev/null @@ -1,6 +0,0 @@ - diff --git a/_includes/footer/footer-de.html b/_includes/footer/footer-de.html deleted file mode 100755 index 9db90815ed..0000000000 --- a/_includes/footer/footer-de.html +++ /dev/null @@ -1,58 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-en.html b/_includes/footer/footer-en.html deleted file mode 100755 index 1fc1b086bc..0000000000 --- a/_includes/footer/footer-en.html +++ /dev/null @@ -1,64 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-es.html b/_includes/footer/footer-es.html deleted file mode 100755 index 3901fccce2..0000000000 --- a/_includes/footer/footer-es.html +++ /dev/null @@ -1,58 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-fr.html b/_includes/footer/footer-fr.html deleted file mode 100755 index c43fb61b99..0000000000 --- a/_includes/footer/footer-fr.html +++ /dev/null @@ -1,58 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-id.html b/_includes/footer/footer-id.html deleted file mode 100755 index 8818367083..0000000000 --- a/_includes/footer/footer-id.html +++ /dev/null @@ -1,64 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-it.html b/_includes/footer/footer-it.html deleted file mode 100755 index 2b8e15048c..0000000000 --- a/_includes/footer/footer-it.html +++ /dev/null @@ -1,58 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-ja.html b/_includes/footer/footer-ja.html deleted file mode 100755 index 7daa345bbf..0000000000 --- a/_includes/footer/footer-ja.html +++ /dev/null @@ -1,58 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-ko.html b/_includes/footer/footer-ko.html deleted file mode 100755 index 2b8e15048c..0000000000 --- a/_includes/footer/footer-ko.html +++ /dev/null @@ -1,58 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-pt-br.html b/_includes/footer/footer-pt-br.html deleted file mode 100755 index 31dfde59b9..0000000000 --- a/_includes/footer/footer-pt-br.html +++ /dev/null @@ -1,59 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-ru.html b/_includes/footer/footer-ru.html deleted file mode 100755 index 2b8e15048c..0000000000 --- a/_includes/footer/footer-ru.html +++ /dev/null @@ -1,58 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-sk.html b/_includes/footer/footer-sk.html deleted file mode 100644 index 2b8e15048c..0000000000 --- a/_includes/footer/footer-sk.html +++ /dev/null @@ -1,58 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-th.html b/_includes/footer/footer-th.html deleted file mode 100755 index ab4f13f95d..0000000000 --- a/_includes/footer/footer-th.html +++ /dev/null @@ -1,58 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-tr.html b/_includes/footer/footer-tr.html deleted file mode 100644 index ab4f13f95d..0000000000 --- a/_includes/footer/footer-tr.html +++ /dev/null @@ -1,58 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-uk.html b/_includes/footer/footer-uk.html deleted file mode 100755 index 2b8e15048c..0000000000 --- a/_includes/footer/footer-uk.html +++ /dev/null @@ -1,58 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-uz.html b/_includes/footer/footer-uz.html deleted file mode 100755 index 2b8e15048c..0000000000 --- a/_includes/footer/footer-uz.html +++ /dev/null @@ -1,58 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-zh-cn.html b/_includes/footer/footer-zh-cn.html deleted file mode 100755 index 2b8e15048c..0000000000 --- a/_includes/footer/footer-zh-cn.html +++ /dev/null @@ -1,58 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/footer/footer-zh-tw.html b/_includes/footer/footer-zh-tw.html deleted file mode 100755 index 2b8e15048c..0000000000 --- a/_includes/footer/footer-zh-tw.html +++ /dev/null @@ -1,58 +0,0 @@ -{% include icons/arrow.svg %} - - - -{% include footer/_docsearch.html %} diff --git a/_includes/head.html b/_includes/head.html deleted file mode 100644 index d830f2d3e5..0000000000 --- a/_includes/head.html +++ /dev/null @@ -1,50 +0,0 @@ - - {{ page.title }} - - - - - - - - - - - - - - - - - {% if page.author %} - - - {% else %} - - {% endif %} - - - - {% if page.image %} - - {% else %} - - {% endif %} - - - - - - {% if page contains "image" %} - - {% else %} - - {% endif %} - - - - - - - - diff --git a/_includes/header/header-de.html b/_includes/header/header-de.html deleted file mode 100644 index 327bd06c56..0000000000 --- a/_includes/header/header-de.html +++ /dev/null @@ -1,128 +0,0 @@ -
-
- -
- - -
- - -
-
diff --git a/_includes/header/header-en.html b/_includes/header/header-en.html deleted file mode 100644 index 998494eea1..0000000000 --- a/_includes/header/header-en.html +++ /dev/null @@ -1,150 +0,0 @@ -
-
- -
- - -
- - -
-
\ No newline at end of file diff --git a/_includes/header/header-es.html b/_includes/header/header-es.html deleted file mode 100644 index 806d260e84..0000000000 --- a/_includes/header/header-es.html +++ /dev/null @@ -1,129 +0,0 @@ -
-
- -
- - -
- - -
-
diff --git a/_includes/header/header-fr.html b/_includes/header/header-fr.html deleted file mode 100644 index ac7abfd8d4..0000000000 --- a/_includes/header/header-fr.html +++ /dev/null @@ -1,130 +0,0 @@ -
-
- -
- - -
- - -
-
diff --git a/_includes/header/header-id.html b/_includes/header/header-id.html deleted file mode 100644 index b7cfe1adb1..0000000000 --- a/_includes/header/header-id.html +++ /dev/null @@ -1,154 +0,0 @@ -
-
- -
- - -
- - -
-
- \ No newline at end of file diff --git a/_includes/header/header-it.html b/_includes/header/header-it.html deleted file mode 100644 index ffee348087..0000000000 --- a/_includes/header/header-it.html +++ /dev/null @@ -1,126 +0,0 @@ -
-
- -
- - -
- - -
-
diff --git a/_includes/header/header-ja.html b/_includes/header/header-ja.html deleted file mode 100644 index 19e5642118..0000000000 --- a/_includes/header/header-ja.html +++ /dev/null @@ -1,129 +0,0 @@ -
-
- -
- - -
- - -
-
diff --git a/_includes/header/header-ko.html b/_includes/header/header-ko.html deleted file mode 100644 index 4c84f0a244..0000000000 --- a/_includes/header/header-ko.html +++ /dev/null @@ -1,129 +0,0 @@ -
-
- -
- - -
- - -
-
diff --git a/_includes/header/header-pt-br.html b/_includes/header/header-pt-br.html deleted file mode 100644 index 0dc280109b..0000000000 --- a/_includes/header/header-pt-br.html +++ /dev/null @@ -1,129 +0,0 @@ -
-
- -
- - -
- - -
-
diff --git a/_includes/header/header-ru.html b/_includes/header/header-ru.html deleted file mode 100644 index 2b5fcd94c6..0000000000 --- a/_includes/header/header-ru.html +++ /dev/null @@ -1,129 +0,0 @@ -
-
- -
- - -
- - -
-
diff --git a/_includes/header/header-sk.html b/_includes/header/header-sk.html deleted file mode 100644 index 443528b389..0000000000 --- a/_includes/header/header-sk.html +++ /dev/null @@ -1,129 +0,0 @@ -
-
- -
- - -
- - -
-
diff --git a/_includes/header/header-th.html b/_includes/header/header-th.html deleted file mode 100644 index 7b07647b86..0000000000 --- a/_includes/header/header-th.html +++ /dev/null @@ -1,143 +0,0 @@ -
-
- -
- - -
- - -
-
diff --git a/_includes/header/header-tr.html b/_includes/header/header-tr.html deleted file mode 100644 index c3e0224d1d..0000000000 --- a/_includes/header/header-tr.html +++ /dev/null @@ -1,143 +0,0 @@ -
-
- -
- - -
- - -
-
diff --git a/_includes/header/header-uk.html b/_includes/header/header-uk.html deleted file mode 100644 index b2dc77df25..0000000000 --- a/_includes/header/header-uk.html +++ /dev/null @@ -1,127 +0,0 @@ -
-
- -
- - -
- - -
-
diff --git a/_includes/header/header-uz.html b/_includes/header/header-uz.html deleted file mode 100644 index b577f9f35f..0000000000 --- a/_includes/header/header-uz.html +++ /dev/null @@ -1,129 +0,0 @@ -
-
- -
- - -
- - -
-
diff --git a/_includes/header/header-zh-cn.html b/_includes/header/header-zh-cn.html deleted file mode 100644 index adddda9453..0000000000 --- a/_includes/header/header-zh-cn.html +++ /dev/null @@ -1,129 +0,0 @@ -
-
- -
- - -
- - -
-
diff --git a/_includes/header/header-zh-tw.html b/_includes/header/header-zh-tw.html deleted file mode 100644 index 9a70af02d7..0000000000 --- a/_includes/header/header-zh-tw.html +++ /dev/null @@ -1,129 +0,0 @@ -
-
- -
- - -
- - -
-
diff --git a/_includes/i18n-notice.html b/_includes/i18n-notice.html deleted file mode 100644 index d5583cf2d1..0000000000 --- a/_includes/i18n-notice.html +++ /dev/null @@ -1,2 +0,0 @@ -

{% include notice/notice-{{ page.lang }}.md %}

-
diff --git a/_includes/icons/announcement.svg b/_includes/icons/announcement.svg deleted file mode 100644 index 460c9522f8..0000000000 --- a/_includes/icons/announcement.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/_includes/icons/arrow.svg b/_includes/icons/arrow.svg deleted file mode 100644 index 3b44d7b7bb..0000000000 --- a/_includes/icons/arrow.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/_includes/icons/github-dark.svg b/_includes/icons/github-dark.svg deleted file mode 100644 index af46af27c3..0000000000 --- a/_includes/icons/github-dark.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - \ No newline at end of file diff --git a/_includes/icons/github-light.svg b/_includes/icons/github-light.svg deleted file mode 100644 index cbce1b55a5..0000000000 --- a/_includes/icons/github-light.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - \ No newline at end of file diff --git a/_includes/icons/opencollective.svg b/_includes/icons/opencollective.svg deleted file mode 100644 index e4c1b67a75..0000000000 --- a/_includes/icons/opencollective.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/_includes/icons/slack.svg b/_includes/icons/slack.svg deleted file mode 100644 index e6bb3f152c..0000000000 --- a/_includes/icons/slack.svg +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - diff --git a/_includes/icons/x-dark.svg b/_includes/icons/x-dark.svg deleted file mode 100644 index ce1ccea551..0000000000 --- a/_includes/icons/x-dark.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/_includes/icons/x-light.svg b/_includes/icons/x-light.svg deleted file mode 100644 index 29be9ba222..0000000000 --- a/_includes/icons/x-light.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/_includes/icons/youtube.svg b/_includes/icons/youtube.svg deleted file mode 100644 index 5968f9b040..0000000000 --- a/_includes/icons/youtube.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/_includes/mw-list.md b/_includes/mw-list.md deleted file mode 100644 index dc30ac643b..0000000000 --- a/_includes/mw-list.md +++ /dev/null @@ -1,17 +0,0 @@ -- [body-parser](/resources/middleware/body-parser.html) -- [compression](/resources/middleware/compression.html) -- [connect-rid](/resources/middleware/connect-rid.html) -- [cookie-parser](/resources/middleware/cookie-parser.html) -- [cookie-session](/resources/middleware/cookie-session.html) -- [cors](/resources/middleware/cors.html) -- [errorhandler](/resources/middleware/errorhandler.html) -- [method-override](/resources/middleware/method-override.html) -- [morgan](/resources/middleware/morgan.html) -- [multer](/resources/middleware/multer.html) -- [response-time](/resources/middleware/response-time.html) -- [serve-favicon](/resources/middleware/serve-favicon.html) -- [serve-index](/resources/middleware/serve-index.html) -- [serve-static](/resources/middleware/serve-static.html) -- [session](/resources/middleware/session.html) -- [timeout](/resources/middleware/timeout.html) -- [vhost](/resources/middleware/vhost.html) diff --git a/_includes/notice/notice-de.md b/_includes/notice/notice-de.md deleted file mode 100755 index f0732c6bc9..0000000000 --- a/_includes/notice/notice-de.md +++ /dev/null @@ -1,3 +0,0 @@ -

Diese Übersetzung zur Verfügung gestellt von StrongLoop / IBM.

- -Dieses Dokument kann im Vergleich zur englischen Dokumentation veraltet sein. Aktuelle Updates finden Sie in der englischen Dokumentation. diff --git a/_includes/notice/notice-en.md b/_includes/notice/notice-en.md deleted file mode 100755 index 45a9b98ef3..0000000000 --- a/_includes/notice/notice-en.md +++ /dev/null @@ -1 +0,0 @@ -This document might be outdated relative to the documentation in English. For the latest updates, please refer to the documentation in English. diff --git a/_includes/notice/notice-es.md b/_includes/notice/notice-es.md deleted file mode 100755 index 469330d2f9..0000000000 --- a/_includes/notice/notice-es.md +++ /dev/null @@ -1,3 +0,0 @@ -

Esta traducción proporcionada por StrongLoop / IBM.

- -Este documento puede estar desfasado respecto a la documentación en inglés. Para ver las últimas actualizaciones, consulte la documentación en inglés. diff --git a/_includes/notice/notice-fr.md b/_includes/notice/notice-fr.md deleted file mode 100755 index adc6d8db41..0000000000 --- a/_includes/notice/notice-fr.md +++ /dev/null @@ -1,3 +0,0 @@ -

Cette traduction fournie par StrongLoop / IBM.

- -Il se peut que ce document soit obsolète par rapport à la documentation en anglais. Pour connaître les mises à jour les plus récentes, reportez-vous à la documentation en anglais. diff --git a/_includes/notice/notice-id.md b/_includes/notice/notice-id.md deleted file mode 100644 index cb199469fd..0000000000 --- a/_includes/notice/notice-id.md +++ /dev/null @@ -1 +0,0 @@ -Dokumen ini mungkin sudah ketinggalan zaman jika dibandingkan dengan dokumentasi dalam bahasa Inggris. Untuk informasi terkini, lihat dokumentasi dalam bahasa Inggris. diff --git a/_includes/notice/notice-it.md b/_includes/notice/notice-it.md deleted file mode 100755 index d6c3330511..0000000000 --- a/_includes/notice/notice-it.md +++ /dev/null @@ -1,3 +0,0 @@ -

Questa traduzione fornita da StrongLoop / IBM.

- -È possibile che questo documento non sia aggiornato poiché la documentazione è in inglese. Per gli ultimi aggiornamenti, fare riferimento alla documentazione in inglese. diff --git a/_includes/notice/notice-ja.md b/_includes/notice/notice-ja.md deleted file mode 100755 index e4426baf5e..0000000000 --- a/_includes/notice/notice-ja.md +++ /dev/null @@ -1,3 +0,0 @@ -

StrongLoop / IBMによって提供されるこの翻訳.

- -本書は、英語の資料と比較すると古くなっている可能性があります。最新の更新については、英語版の資料を参照してください。 diff --git a/_includes/notice/notice-ko.md b/_includes/notice/notice-ko.md deleted file mode 100755 index 5bcea4687a..0000000000 --- a/_includes/notice/notice-ko.md +++ /dev/null @@ -1,3 +0,0 @@ -

StrongLoop / IBM에 의해 제공이 번역.

- -이 문서는 영문판 문서에 비해 더 오래된 버전일 수도 있습니다. 최신 업데이트를 확인하려면 영문판 문서를 참조하십시오. diff --git a/_includes/notice/notice-pt-br.md b/_includes/notice/notice-pt-br.md deleted file mode 100755 index 2244fbf2ae..0000000000 --- a/_includes/notice/notice-pt-br.md +++ /dev/null @@ -1,3 +0,0 @@ -

Esta tradução fornecida pelo StrongLoop / IBM.

- -Este documento pode estar desatualizado em relação à documentação em Inglês. Para obter as atualizações mais recentes, consulte a documentação em Inglês. diff --git a/_includes/notice/notice-ru.md b/_includes/notice/notice-ru.md deleted file mode 100755 index 0f6dde4da0..0000000000 --- a/_includes/notice/notice-ru.md +++ /dev/null @@ -1,3 +0,0 @@ -

Этот перевод обеспечивается StrongLoop / IBM.

- -Этот документ может быть устаревшим по отношению к документации на английском языке. Последние обновления содержатся в документации на английском языке. diff --git a/_includes/notice/notice-sk.md b/_includes/notice/notice-sk.md deleted file mode 100644 index 268b201d7e..0000000000 --- a/_includes/notice/notice-sk.md +++ /dev/null @@ -1 +0,0 @@ -Tento dokument môže byť v porovnaní s dokumentáciou v angličtine zastaralý. Aktuálne informácie nájdete v dokumentácii v angličtine. diff --git a/_includes/notice/notice-th.md b/_includes/notice/notice-th.md deleted file mode 100755 index 8dc82ef2c9..0000000000 --- a/_includes/notice/notice-th.md +++ /dev/null @@ -1 +0,0 @@ -ในเอกสารนี้อาจจะเก่าไปแล้วที่เกี่ยวเนื่องกับรุ่นของเอกสารในภาษาอังกฤษ สำหรับรุ่นล่าสุดโปรดอ้างอิงจาก เอกสารในภาษาอังกฤษ. diff --git a/_includes/notice/notice-tr.md b/_includes/notice/notice-tr.md deleted file mode 100644 index cb09be114a..0000000000 --- a/_includes/notice/notice-tr.md +++ /dev/null @@ -1 +0,0 @@ -Bu doküman ingilizce dokümana göre eski olabilir. Son güncellemeler için lütfen İngilizce Dokümanı. ziyaret edin diff --git a/_includes/notice/notice-uk.md b/_includes/notice/notice-uk.md deleted file mode 100755 index 9192cc6e97..0000000000 --- a/_includes/notice/notice-uk.md +++ /dev/null @@ -1 +0,0 @@ -Цей документ може бути застарілим, в порівнянні з оригінальною англійською версією документації. diff --git a/_includes/notice/notice-uz.md b/_includes/notice/notice-uz.md deleted file mode 100755 index 3d46d9600f..0000000000 --- a/_includes/notice/notice-uz.md +++ /dev/null @@ -1 +0,0 @@ -This document might be outdated relative to the documentation in English. For the latest updates, please refer to the documentation in English. diff --git a/_includes/notice/notice-zh-cn.md b/_includes/notice/notice-zh-cn.md deleted file mode 100755 index 81739b9f46..0000000000 --- a/_includes/notice/notice-zh-cn.md +++ /dev/null @@ -1,3 +0,0 @@ -

这个翻译StrongLoop / IBM提供.

- -相对于英文版的文档,本文档可能已过时。要了解最近的更新,请参阅英文版文档。 diff --git a/_includes/notice/notice-zh-tw.md b/_includes/notice/notice-zh-tw.md deleted file mode 100755 index 031eef076a..0000000000 --- a/_includes/notice/notice-zh-tw.md +++ /dev/null @@ -1,3 +0,0 @@ -

這個翻譯StrongLoop / IBM提供.

- -相對於英文版說明文件,本文件可能已不合時宜。如需最新的更新,請參閱英文版說明文件。 diff --git a/_includes/readmes/body-parser.md b/_includes/readmes/body-parser.md deleted file mode 100644 index 1eebdffd5f..0000000000 --- a/_includes/readmes/body-parser.md +++ /dev/null @@ -1,491 +0,0 @@ -# body-parser - -[![NPM Version][npm-version-image]][npm-url] -[![NPM Downloads][npm-downloads-image]][npm-url] -[![Build Status][ci-image]][ci-url] -[![Test Coverage][coveralls-image]][coveralls-url] -[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer] - -Node.js body parsing middleware. - -Parse incoming request bodies in a middleware before your handlers, available -under the `req.body` property. - -**Note** As `req.body`'s shape is based on user-controlled input, all -properties and values in this object are untrusted and should be validated -before trusting. For example, `req.body.foo.toString()` may fail in multiple -ways, for example the `foo` property may not be there or may not be a string, -and `toString` may not be a function and instead a string or other user input. - -[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/). - -_This does not handle multipart bodies_, due to their complex and typically -large nature. For multipart bodies, you may be interested in the following -modules: - - * [busboy](https://www.npmjs.org/package/busboy#readme) and - [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) - * [multiparty](https://www.npmjs.org/package/multiparty#readme) and - [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) - * [formidable](https://www.npmjs.org/package/formidable#readme) - * [multer](https://www.npmjs.org/package/multer#readme) - -This module provides the following parsers: - - * [JSON body parser](#bodyparserjsonoptions) - * [Raw body parser](#bodyparserrawoptions) - * [Text body parser](#bodyparsertextoptions) - * [URL-encoded form body parser](#bodyparserurlencodedoptions) - -Other body parsers you might be interested in: - -- [body](https://www.npmjs.org/package/body#readme) -- [co-body](https://www.npmjs.org/package/co-body#readme) - -## Installation - -```sh -$ npm install body-parser -``` - -## API - -```js -var bodyParser = require('body-parser') -``` - -The `bodyParser` object exposes various factories to create middlewares. All -middlewares will populate the `req.body` property with the parsed body when -the `Content-Type` request header matches the `type` option. - -The various errors returned by this module are described in the -[errors section](#errors). - -### bodyParser.json([options]) - -Returns middleware that only parses `json` and only looks at requests where -the `Content-Type` header matches the `type` option. This parser accepts any -Unicode encoding of the body and supports automatic inflation of `gzip`, -`br` (brotli) and `deflate` encodings. - -A new `body` object containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`). - -#### Options - -The `json` function takes an optional `options` object that may contain any of -the following keys: - -##### inflate - -When set to `true`, then deflated (compressed) bodies will be inflated; when -`false`, deflated bodies are rejected. Defaults to `true`. - -##### limit - -Controls the maximum request body size. If this is a number, then the value -specifies the number of bytes; if it is a string, the value is passed to the -[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults -to `'100kb'`. - -##### reviver - -The `reviver` option is passed directly to `JSON.parse` as the second -argument. You can find more information on this argument -[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). - -##### strict - -When set to `true`, will only accept arrays and objects; when `false` will -accept anything `JSON.parse` accepts. Defaults to `true`. - -##### type - -The `type` option is used to determine what media type the middleware will -parse. This option can be a string, array of strings, or a function. If not a -function, `type` option is passed directly to the -[type-is](https://www.npmjs.org/package/type-is#readme) library and this can -be an extension name (like `json`), a mime type (like `application/json`), or -a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` -option is called as `fn(req)` and the request is parsed if it returns a truthy -value. Defaults to `application/json`. - -##### verify - -The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, -where `buf` is a `Buffer` of the raw request body and `encoding` is the -encoding of the request. The parsing can be aborted by throwing an error. - -### bodyParser.raw([options]) - -Returns middleware that parses all bodies as a `Buffer` and only looks at -requests where the `Content-Type` header matches the `type` option. This -parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate` -encodings. - -A new `body` object containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`). This will be a `Buffer` object -of the body. - -#### Options - -The `raw` function takes an optional `options` object that may contain any of -the following keys: - -##### inflate - -When set to `true`, then deflated (compressed) bodies will be inflated; when -`false`, deflated bodies are rejected. Defaults to `true`. - -##### limit - -Controls the maximum request body size. If this is a number, then the value -specifies the number of bytes; if it is a string, the value is passed to the -[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults -to `'100kb'`. - -##### type - -The `type` option is used to determine what media type the middleware will -parse. This option can be a string, array of strings, or a function. -If not a function, `type` option is passed directly to the -[type-is](https://www.npmjs.org/package/type-is#readme) library and this -can be an extension name (like `bin`), a mime type (like -`application/octet-stream`), or a mime type with a wildcard (like `*/*` or -`application/*`). If a function, the `type` option is called as `fn(req)` -and the request is parsed if it returns a truthy value. Defaults to -`application/octet-stream`. - -##### verify - -The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, -where `buf` is a `Buffer` of the raw request body and `encoding` is the -encoding of the request. The parsing can be aborted by throwing an error. - -### bodyParser.text([options]) - -Returns middleware that parses all bodies as a string and only looks at -requests where the `Content-Type` header matches the `type` option. This -parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate` -encodings. - -A new `body` string containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`). This will be a string of the -body. - -#### Options - -The `text` function takes an optional `options` object that may contain any of -the following keys: - -##### defaultCharset - -Specify the default character set for the text content if the charset is not -specified in the `Content-Type` header of the request. Defaults to `utf-8`. - -##### inflate - -When set to `true`, then deflated (compressed) bodies will be inflated; when -`false`, deflated bodies are rejected. Defaults to `true`. - -##### limit - -Controls the maximum request body size. If this is a number, then the value -specifies the number of bytes; if it is a string, the value is passed to the -[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults -to `'100kb'`. - -##### type - -The `type` option is used to determine what media type the middleware will -parse. This option can be a string, array of strings, or a function. If not -a function, `type` option is passed directly to the -[type-is](https://www.npmjs.org/package/type-is#readme) library and this can -be an extension name (like `txt`), a mime type (like `text/plain`), or a mime -type with a wildcard (like `*/*` or `text/*`). If a function, the `type` -option is called as `fn(req)` and the request is parsed if it returns a -truthy value. Defaults to `text/plain`. - -##### verify - -The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, -where `buf` is a `Buffer` of the raw request body and `encoding` is the -encoding of the request. The parsing can be aborted by throwing an error. - -### bodyParser.urlencoded([options]) - -Returns middleware that only parses `urlencoded` bodies and only looks at -requests where the `Content-Type` header matches the `type` option. This -parser accepts only UTF-8 encoding of the body and supports automatic -inflation of `gzip`, `br` (brotli) and `deflate` encodings. - -A new `body` object containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`). This object will contain -key-value pairs, where the value can be a string or array (when `extended` is -`false`), or any type (when `extended` is `true`). - -#### Options - -The `urlencoded` function takes an optional `options` object that may contain -any of the following keys: - -##### extended - -The "extended" syntax allows for rich objects and arrays to be encoded into the -URL-encoded format, allowing for a JSON-like experience with URL-encoded. For -more information, please [see the qs -library](https://www.npmjs.org/package/qs#readme). - -Defaults to `false`. - -##### inflate - -When set to `true`, then deflated (compressed) bodies will be inflated; when -`false`, deflated bodies are rejected. Defaults to `true`. - -##### limit - -Controls the maximum request body size. If this is a number, then the value -specifies the number of bytes; if it is a string, the value is passed to the -[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults -to `'100kb'`. - -##### parameterLimit - -The `parameterLimit` option controls the maximum number of parameters that -are allowed in the URL-encoded data. If a request contains more parameters -than this value, a 413 will be returned to the client. Defaults to `1000`. - -##### type - -The `type` option is used to determine what media type the middleware will -parse. This option can be a string, array of strings, or a function. If not -a function, `type` option is passed directly to the -[type-is](https://www.npmjs.org/package/type-is#readme) library and this can -be an extension name (like `urlencoded`), a mime type (like -`application/x-www-form-urlencoded`), or a mime type with a wildcard (like -`*/x-www-form-urlencoded`). If a function, the `type` option is called as -`fn(req)` and the request is parsed if it returns a truthy value. Defaults -to `application/x-www-form-urlencoded`. - -##### verify - -The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, -where `buf` is a `Buffer` of the raw request body and `encoding` is the -encoding of the request. The parsing can be aborted by throwing an error. - -##### defaultCharset - -The default charset to parse as, if not specified in content-type. Must be -either `utf-8` or `iso-8859-1`. Defaults to `utf-8`. - -##### charsetSentinel - -Whether to let the value of the `utf8` parameter take precedence as the charset -selector. It requires the form to contain a parameter named `utf8` with a value -of `✓`. Defaults to `false`. - -##### interpretNumericEntities - -Whether to decode numeric entities such as `☺` when parsing an iso-8859-1 -form. Defaults to `false`. - - -#### depth - -The `depth` option is used to configure the maximum depth of the `qs` library when `extended` is `true`. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to `32`. It is recommended to keep this value as low as possible. - -## Errors - -The middlewares provided by this module create errors using the -[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors -will typically have a `status`/`statusCode` property that contains the suggested -HTTP response code, an `expose` property to determine if the `message` property -should be displayed to the client, a `type` property to determine the type of -error without matching against the `message`, and a `body` property containing -the read body, if available. - -The following are the common errors created, though any error can come through -for various reasons. - -### content encoding unsupported - -This error will occur when the request had a `Content-Encoding` header that -contained an encoding but the "inflation" option was set to `false`. The -`status` property is set to `415`, the `type` property is set to -`'encoding.unsupported'`, and the `charset` property will be set to the -encoding that is unsupported. - -### entity parse failed - -This error will occur when the request contained an entity that could not be -parsed by the middleware. The `status` property is set to `400`, the `type` -property is set to `'entity.parse.failed'`, and the `body` property is set to -the entity value that failed parsing. - -### entity verify failed - -This error will occur when the request contained an entity that could not be -failed verification by the defined `verify` option. The `status` property is -set to `403`, the `type` property is set to `'entity.verify.failed'`, and the -`body` property is set to the entity value that failed verification. - -### request aborted - -This error will occur when the request is aborted by the client before reading -the body has finished. The `received` property will be set to the number of -bytes received before the request was aborted and the `expected` property is -set to the number of expected bytes. The `status` property is set to `400` -and `type` property is set to `'request.aborted'`. - -### request entity too large - -This error will occur when the request body's size is larger than the "limit" -option. The `limit` property will be set to the byte limit and the `length` -property will be set to the request body's length. The `status` property is -set to `413` and the `type` property is set to `'entity.too.large'`. - -### request size did not match content length - -This error will occur when the request's length did not match the length from -the `Content-Length` header. This typically occurs when the request is malformed, -typically when the `Content-Length` header was calculated based on characters -instead of bytes. The `status` property is set to `400` and the `type` property -is set to `'request.size.invalid'`. - -### stream encoding should not be set - -This error will occur when something called the `req.setEncoding` method prior -to this middleware. This module operates directly on bytes only and you cannot -call `req.setEncoding` when using this module. The `status` property is set to -`500` and the `type` property is set to `'stream.encoding.set'`. - -### stream is not readable - -This error will occur when the request is no longer readable when this middleware -attempts to read it. This typically means something other than a middleware from -this module read the request body already and the middleware was also configured to -read the same request. The `status` property is set to `500` and the `type` -property is set to `'stream.not.readable'`. - -### too many parameters - -This error will occur when the content of the request exceeds the configured -`parameterLimit` for the `urlencoded` parser. The `status` property is set to -`413` and the `type` property is set to `'parameters.too.many'`. - -### unsupported charset "BOGUS" - -This error will occur when the request had a charset parameter in the -`Content-Type` header, but the `iconv-lite` module does not support it OR the -parser does not support it. The charset is contained in the message as well -as in the `charset` property. The `status` property is set to `415`, the -`type` property is set to `'charset.unsupported'`, and the `charset` property -is set to the charset that is unsupported. - -### unsupported content encoding "bogus" - -This error will occur when the request had a `Content-Encoding` header that -contained an unsupported encoding. The encoding is contained in the message -as well as in the `encoding` property. The `status` property is set to `415`, -the `type` property is set to `'encoding.unsupported'`, and the `encoding` -property is set to the encoding that is unsupported. - -### The input exceeded the depth - -This error occurs when using `bodyParser.urlencoded` with the `extended` property set to `true` and the input exceeds the configured `depth` option. The `status` property is set to `400`. It is recommended to review the `depth` option and evaluate if it requires a higher value. When the `depth` option is set to `32` (default value), the error will not be thrown. - -## Examples - -### Express/Connect top-level generic - -This example demonstrates adding a generic JSON and URL-encoded parser as a -top-level middleware, which will parse the bodies of all incoming requests. -This is the simplest setup. - -```js -var express = require('express') -var bodyParser = require('body-parser') - -var app = express() - -// parse application/x-www-form-urlencoded -app.use(bodyParser.urlencoded()) - -// parse application/json -app.use(bodyParser.json()) - -app.use(function (req, res) { - res.setHeader('Content-Type', 'text/plain') - res.write('you posted:\n') - res.end(String(JSON.stringify(req.body, null, 2))) -}) -``` - -### Express route-specific - -This example demonstrates adding body parsers specifically to the routes that -need them. In general, this is the most recommended way to use body-parser with -Express. - -```js -var express = require('express') -var bodyParser = require('body-parser') - -var app = express() - -// create application/json parser -var jsonParser = bodyParser.json() - -// create application/x-www-form-urlencoded parser -var urlencodedParser = bodyParser.urlencoded() - -// POST /login gets urlencoded bodies -app.post('/login', urlencodedParser, function (req, res) { - if (!req.body || !req.body.username) res.sendStatus(400) - res.send('welcome, ' + req.body.username) -}) - -// POST /api/users gets JSON bodies -app.post('/api/users', jsonParser, function (req, res) { - if (!req.body) res.sendStatus(400) - // create user in req.body -}) -``` - -### Change accepted type for parsers - -All the parsers accept a `type` option which allows you to change the -`Content-Type` that the middleware will parse. - -```js -var express = require('express') -var bodyParser = require('body-parser') - -var app = express() - -// parse various different custom JSON types as JSON -app.use(bodyParser.json({ type: 'application/*+json' })) - -// parse some custom thing into a Buffer -app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) - -// parse an HTML body into a string -app.use(bodyParser.text({ type: 'text/html' })) -``` - -## License - -[MIT](LICENSE) - -[ci-image]: https://badgen.net/github/checks/expressjs/body-parser/master?label=ci -[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml -[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/body-parser/master -[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master -[node-version-image]: https://badgen.net/npm/node/body-parser -[node-version-url]: https://nodejs.org/en/download -[npm-downloads-image]: https://badgen.net/npm/dm/body-parser -[npm-url]: https://npmjs.org/package/body-parser -[npm-version-image]: https://badgen.net/npm/v/body-parser -[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge -[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser \ No newline at end of file diff --git a/_includes/readmes/compression.md b/_includes/readmes/compression.md deleted file mode 100644 index 16bde0ad2f..0000000000 --- a/_includes/readmes/compression.md +++ /dev/null @@ -1,311 +0,0 @@ -# compression - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Build Status][github-actions-ci-image]][github-actions-ci-url] -[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer] -[![Funding][funding-image]][funding-url] - - -Node.js compression middleware. - -The following compression codings are supported: - - - deflate - - gzip - - br (brotli) - -**Note** Brotli is supported only since Node.js versions v11.7.0 and v10.16.0. - -## Install - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```bash -$ npm install compression -``` - -## API - -```js -var compression = require('compression') -``` - -### compression([options]) - -Returns the compression middleware using the given `options`. The middleware -will attempt to compress response bodies for all requests that traverse through -the middleware, based on the given `options`. - -This middleware will never compress responses that include a `Cache-Control` -header with the [`no-transform` directive](https://tools.ietf.org/html/rfc7234#section-5.2.2.4), -as compressing will transform the body. - -#### Options - -`compression()` accepts these properties in the options object. In addition to -those listed below, [zlib](http://nodejs.org/api/zlib.html) options may be -passed in to the options object or -[brotli](https://nodejs.org/api/zlib.html#zlib_class_brotlioptions) options. - -##### chunkSize - -Type: `Number`
-Default: `zlib.constants.Z_DEFAULT_CHUNK`, or `16384`. - -See [Node.js documentation](http://nodejs.org/api/zlib.html#zlib_memory_usage_tuning) -regarding the usage. - -##### filter - -Type: `Function` - -A function to decide if the response should be considered for compression. -This function is called as `filter(req, res)` and is expected to return -`true` to consider the response for compression, or `false` to not compress -the response. - -The default filter function uses the [compressible](https://www.npmjs.com/package/compressible) -module to determine if `res.getHeader('Content-Type')` is compressible. - -##### level - -Type: `Number`
-Default: `zlib.constants.Z_DEFAULT_COMPRESSION`, or `-1` - -The level of zlib compression to apply to responses. A higher level will result -in better compression, but will take longer to complete. A lower level will -result in less compression, but will be much faster. - -This is an integer in the range of `0` (no compression) to `9` (maximum -compression). The special value `-1` can be used to mean the "default -compression level", which is a default compromise between speed and -compression (currently equivalent to level 6). - - - `-1` Default compression level (also `zlib.constants.Z_DEFAULT_COMPRESSION`). - - `0` No compression (also `zlib.constants.Z_NO_COMPRESSION`). - - `1` Fastest compression (also `zlib.constants.Z_BEST_SPEED`). - - `2` - - `3` - - `4` - - `5` - - `6` (currently what `zlib.constants.Z_DEFAULT_COMPRESSION` points to). - - `7` - - `8` - - `9` Best compression (also `zlib.constants.Z_BEST_COMPRESSION`). - -**Note** in the list above, `zlib` is from `zlib = require('zlib')`. - -##### memLevel - -Type: `Number`
-Default: `zlib.constants.Z_DEFAULT_MEMLEVEL`, or `8` - -This specifies how much memory should be allocated for the internal compression -state and is an integer in the range of `1` (minimum level) and `9` (maximum -level). - -See [Node.js documentation](http://nodejs.org/api/zlib.html#zlib_memory_usage_tuning) -regarding the usage. - -##### brotli - -Type: `Object` - -This specifies the options for configuring Brotli. See [Node.js documentation](https://nodejs.org/api/zlib.html#class-brotlioptions) for a complete list of available options. - - -##### strategy - -Type: `Number`
-Default: `zlib.constants.Z_DEFAULT_STRATEGY` - -This is used to tune the compression algorithm. This value only affects the -compression ratio, not the correctness of the compressed output, even if it -is not set appropriately. - - - `zlib.constants.Z_DEFAULT_STRATEGY` Use for normal data. - - `zlib.constants.Z_FILTERED` Use for data produced by a filter (or predictor). - Filtered data consists mostly of small values with a somewhat random - distribution. In this case, the compression algorithm is tuned to - compress them better. The effect is to force more Huffman coding and less - string matching; it is somewhat intermediate between `zlib.constants.Z_DEFAULT_STRATEGY` - and `zlib.constants.Z_HUFFMAN_ONLY`. - - `zlib.constants.Z_FIXED` Use to prevent the use of dynamic Huffman codes, allowing - for a simpler decoder for special applications. - - `zlib.constants.Z_HUFFMAN_ONLY` Use to force Huffman encoding only (no string match). - - `zlib.constants.Z_RLE` Use to limit match distances to one (run-length encoding). - This is designed to be almost as fast as `zlib.constants.Z_HUFFMAN_ONLY`, but give - better compression for PNG image data. - -**Note** in the list above, `zlib` is from `zlib = require('zlib')`. - -##### threshold - -Type: `Number` or `String`
-Default: `1kb` - -The byte threshold for the response body size before compression is considered -for the response. This is a number of bytes or any string -accepted by the [bytes](https://www.npmjs.com/package/bytes) module. - -**Note** this is only an advisory setting; if the response size cannot be determined -at the time the response headers are written, then it is assumed the response is -_over_ the threshold. To guarantee the response size can be determined, be sure -set a `Content-Length` response header. - -##### windowBits - -Type: `Number`
-Default: `zlib.constants.Z_DEFAULT_WINDOWBITS`, or `15` - -See [Node.js documentation](http://nodejs.org/api/zlib.html#zlib_memory_usage_tuning) -regarding the usage. - -##### enforceEncoding - -Type: `String`
-Default: `identity` - -This is the default encoding to use when the client does not specify an encoding in the request's [Accept-Encoding](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding) header. - -#### .filter - -The default `filter` function. This is used to construct a custom filter -function that is an extension of the default function. - -```js -var compression = require('compression') -var express = require('express') - -var app = express() - -app.use(compression({ filter: shouldCompress })) - -function shouldCompress (req, res) { - if (req.headers['x-no-compression']) { - // don't compress responses with this request header - return false - } - - // fallback to standard filter function - return compression.filter(req, res) -} -``` - -### res.flush - -This module adds a `res.flush()` method to force the partially-compressed -response to be flushed to the client. - -## Examples - -### express - -When using this module with express, simply `app.use` the module as -high as you like. Requests that pass through the middleware will be compressed. - -```js -var compression = require('compression') -var express = require('express') - -var app = express() - -// compress all responses -app.use(compression()) - -// add all routes -``` - -### Node.js HTTP server - -```js -var compression = require('compression')({ threshold: 0 }) -var http = require('http') - -function createServer (fn) { - return http.createServer(function (req, res) { - compression(req, res, function (err) { - if (err) { - res.statusCode = err.status || 500 - res.end(err.message) - return - } - - fn(req, res) - }) - }) -} - -var server = createServer(function (req, res) { - res.setHeader('Content-Type', 'text/plain') - res.end('hello world!') -}) - -server.listen(3000, () => { - console.log('> Listening at http://localhost:3000') -}) -``` - -### Server-Sent Events - -Because of the nature of compression this module does not work out of the box -with server-sent events. To compress content, a window of the output needs to -be buffered up in order to get good compression. Typically when using server-sent -events, there are certain block of data that need to reach the client. - -You can achieve this by calling `res.flush()` when you need the data written to -actually make it to the client. - -```js -var compression = require('compression') -var express = require('express') - -var app = express() - -// compress responses -app.use(compression()) - -// server-sent event stream -app.get('/events', function (req, res) { - res.setHeader('Content-Type', 'text/event-stream') - res.setHeader('Cache-Control', 'no-cache') - - // send a ping approx every 2 seconds - var timer = setInterval(function () { - res.write('data: ping\n\n') - - // !!! this is the important part - res.flush() - }, 2000) - - res.on('close', function () { - clearInterval(timer) - }) -}) -``` - -## Contributing - -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](https://github.com/expressjs/express/blob/master/Contributing.md) for more technical details on contributing. - -## License - -[MIT](LICENSE) - -[npm-image]: https://badgen.net/npm/v/compression -[npm-url]: https://npmjs.org/package/compression -[downloads-image]: https://badgen.net/npm/dm/compression -[downloads-url]: https://npmcharts.com/compare/compression?minimal=true -[github-actions-ci-image]: https://badgen.net/github/checks/expressjs/compression/master?label=CI -[github-actions-ci-url]: https://github.com/expressjs/compression/actions?query=workflow%3Aci -[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/compression/badge -[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/compression -[funding-url]: https://opencollective.com/express -[funding-image]: https://badgen.net/badge/icon/sponsor/pink?icon=github&label=Open%20Collective \ No newline at end of file diff --git a/_includes/readmes/connect-rid.md b/_includes/readmes/connect-rid.md deleted file mode 100644 index 207cc44157..0000000000 --- a/_includes/readmes/connect-rid.md +++ /dev/null @@ -1,51 +0,0 @@ -connect-rid -======= - -[![Build Status](https://secure.travis-ci.org/fengmk2/connect-rid.png)](http://travis-ci.org/fengmk2/connect-rid) [![Coverage Status](https://coveralls.io/repos/fengmk2/connect-rid/badge.png)](https://coveralls.io/r/fengmk2/connect-rid) [![Dependency Status](https://gemnasium.com/fengmk2/connect-rid.png)](https://gemnasium.com/fengmk2/connect-rid) - -[![NPM](https://nodei.co/npm/connect-rid.png?downloads=true&stars=true)](https://nodei.co/npm/connect-rid/) - -![logo](https://raw.github.com/fengmk2/connect-rid/master/logo.png) - -connect request id middleware, base on [rid](https://github.com/fengmk2/rid). - -## Install - -```bash -$ npm install connect-rid -``` - -## Usage - -```js -var rid = require('connect-rid'); - -app.use(rid({ - // headerName: 'X-RID' -})); -``` - -## License - -(The MIT License) - -Copyright (c) 2014 fengmk2 <fengmk2@gmail.com> and other contributors - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/_includes/readmes/cookie-parser.md b/_includes/readmes/cookie-parser.md deleted file mode 100644 index b8ecd7b24e..0000000000 --- a/_includes/readmes/cookie-parser.md +++ /dev/null @@ -1,119 +0,0 @@ -# cookie-parser - -[![NPM Version][npm-version-image]][npm-url] -[![NPM Downloads][npm-downloads-image]][npm-url] -[![Build Status][ci-image]][ci-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Parse `Cookie` header and populate `req.cookies` with an object keyed by the -cookie names. Optionally you may enable signed cookie support by passing a -`secret` string, which assigns `req.secret` so it may be used by other -middleware. - -## Installation - -```sh -$ npm install cookie-parser -``` - -## API - -```js -var cookieParser = require('cookie-parser') -``` - -### cookieParser(secret, options) - -Create a new cookie parser middleware function using the given `secret` and -`options`. - -- `secret` a string or array used for signing cookies. This is optional and if - not specified, will not parse signed cookies. If a string is provided, this - is used as the secret. If an array is provided, an attempt will be made to - unsign the cookie with each secret in order. -- `options` an object that is passed to `cookie.parse` as the second option. See - [cookie](https://www.npmjs.org/package/cookie) for more information. - - `decode` a function to decode the value of the cookie - -The middleware will parse the `Cookie` header on the request and expose the -cookie data as the property `req.cookies` and, if a `secret` was provided, as -the property `req.signedCookies`. These properties are name value pairs of the -cookie name to cookie value. - -When `secret` is provided, this module will unsign and validate any signed cookie -values and move those name value pairs from `req.cookies` into `req.signedCookies`. -A signed cookie is a cookie that has a value prefixed with `s:`. Signed cookies -that fail signature validation will have the value `false` instead of the tampered -value. - -In addition, this module supports special "JSON cookies". These are cookie where -the value is prefixed with `j:`. When these values are encountered, the value will -be exposed as the result of `JSON.parse`. If parsing fails, the original value will -remain. - -### cookieParser.JSONCookie(str) - -Parse a cookie value as a JSON cookie. This will return the parsed JSON value -if it was a JSON cookie, otherwise, it will return the passed value. - -### cookieParser.JSONCookies(cookies) - -Given an object, this will iterate over the keys and call `JSONCookie` on each -value, replacing the original value with the parsed value. This returns the -same object that was passed in. - -### cookieParser.signedCookie(str, secret) - -Parse a cookie value as a signed cookie. This will return the parsed unsigned -value if it was a signed cookie and the signature was valid. If the value was -not signed, the original value is returned. If the value was signed but the -signature could not be validated, `false` is returned. - -The `secret` argument can be an array or string. If a string is provided, this -is used as the secret. If an array is provided, an attempt will be made to -unsign the cookie with each secret in order. - -### cookieParser.signedCookies(cookies, secret) - -Given an object, this will iterate over the keys and check if any value is a -signed cookie. If it is a signed cookie and the signature is valid, the key -will be deleted from the object and added to the new object that is returned. - -The `secret` argument can be an array or string. If a string is provided, this -is used as the secret. If an array is provided, an attempt will be made to -unsign the cookie with each secret in order. - -## Example - -```js -var express = require('express') -var cookieParser = require('cookie-parser') - -var app = express() -app.use(cookieParser()) - -app.get('/', function (req, res) { - // Cookies that have not been signed - console.log('Cookies: ', req.cookies) - - // Cookies that have been signed - console.log('Signed Cookies: ', req.signedCookies) -}) - -app.listen(8080) - -// curl command that sends an HTTP request with two cookies -// curl http://127.0.0.1:8080 --cookie "Cho=Kim;Greet=Hello" -``` - -## License - -[MIT](LICENSE) - -[ci-image]: https://badgen.net/github/checks/expressjs/cookie-parser/master?label=ci -[ci-url]: https://github.com/expressjs/cookie-parser/actions?query=workflow%3Aci -[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/cookie-parser/master -[coveralls-url]: https://coveralls.io/r/expressjs/cookie-parser?branch=master -[npm-downloads-image]: https://badgen.net/npm/dm/cookie-parser -[npm-url]: https://npmjs.org/package/cookie-parser -[npm-version-image]: https://badgen.net/npm/v/cookie-parser diff --git a/_includes/readmes/cookie-session.md b/_includes/readmes/cookie-session.md deleted file mode 100644 index e1f0d0a0b1..0000000000 --- a/_includes/readmes/cookie-session.md +++ /dev/null @@ -1,290 +0,0 @@ -# cookie-session - -[![NPM Version][npm-version-image]][npm-url] -[![NPM Downloads][npm-downloads-image]][npm-url] -[![Build Status][ci-image]][ci-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Simple cookie-based session middleware. - -A user session can be stored in two main ways with cookies: on the server or on -the client. This module stores the session data on the client within a cookie, -while a module like [express-session](https://www.npmjs.com/package/express-session) -stores only a session identifier on the client within a cookie and stores the -session data on the server, typically in a database. - -The following points can help you choose which to use: - - * `cookie-session` does not require any database / resources on the server side, - though the total session data cannot exceed the browser's max cookie size. - * `cookie-session` can simplify certain load-balanced scenarios. - * `cookie-session` can be used to store a "light" session and include an identifier - to look up a database-backed secondary store to reduce database lookups. - -**NOTE** This module does not encrypt the session contents in the cookie, only provides -signing to prevent tampering. The client will be able to read the session data by -examining the cookie's value. Secret data should not be set in `req.session` without -encrypting it, or use a server-side session instead. - -**NOTE** This module does not prevent session replay, as the expiration set is that -of the cookie only; if that is a concern of your application, you can store an expiration -date in `req.session` object and validate it on the sever, and implement any other logic -to extend the session as your application needs. - -## Install - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install cookie-session -``` - -## API - -```js -var cookieSession = require('cookie-session') -var express = require('express') - -var app = express() - -app.use(cookieSession({ - name: 'session', - keys: [/* secret keys */], - - // Cookie Options - maxAge: 24 * 60 * 60 * 1000 // 24 hours -})) -``` - -### cookieSession(options) - -Create a new cookie session middleware with the provided options. This middleware -will attach the property `session` to `req`, which provides an object representing -the loaded session. This session is either a new session if no valid session was -provided in the request, or a loaded session from the request. - -The middleware will automatically add a `Set-Cookie` header to the response if the -contents of `req.session` were altered. _Note_ that no `Set-Cookie` header will be -in the response (and thus no session created for a specific user) unless there are -contents in the session, so be sure to add something to `req.session` as soon as -you have identifying information to store for the session. - -#### Options - -Cookie session accepts these properties in the options object. - -##### name - -The name of the cookie to set, defaults to `session`. - -##### keys - -The list of keys to use to sign & verify cookie values, or a configured -[`Keygrip`](https://www.npmjs.com/package/keygrip) instance. Set cookies are always -signed with `keys[0]`, while the other keys are valid for verification, allowing -for key rotation. If a `Keygrip` instance is provided, it can be used to -change signature parameters like the algorithm of the signature. - -##### secret - -A string which will be used as single key if `keys` is not provided. - -##### Cookie Options - -Other options are passed to `cookies.get()` and `cookies.set()` allowing you -to control security, domain, path, and signing among other settings. - -The options can also contain any of the following (for the full list, see -[cookies module documentation](https://www.npmjs.org/package/cookies#readme): - - - `maxAge`: a number representing the milliseconds from `Date.now()` for expiry - - `expires`: a `Date` object indicating the cookie's expiration date (expires at the end of session by default). - - `path`: a string indicating the path of the cookie (`/` by default). - - `domain`: a string indicating the domain of the cookie (no default). - - `partitioned`: a boolean indicating whether to partition the cookie in Chrome for the [CHIPS Update](https://developers.google.com/privacy-sandbox/3pcd/chips) (`false` by default). If this is true, Cookies from embedded sites will be partitioned and only readable from the same top level site from which it was created. - - `priority`: a string indicating the cookie priority. This can be set to `'low'`, `'medium'`, or `'high'`. - - `sameSite`: a boolean or string indicating whether the cookie is a "same site" cookie (`false` by default). This can be set to `'strict'`, `'lax'`, `'none'`, or `true` (which maps to `'strict'`). - - `secure`: a boolean indicating whether the cookie is only to be sent over HTTPS (`false` by default for HTTP, `true` by default for HTTPS). If this is set to `true` and Node.js is not directly over a TLS connection, be sure to read how to [setup Express behind proxies](https://expressjs.com/en/guide/behind-proxies.html) or the cookie may not ever set correctly. - - `httpOnly`: a boolean indicating whether the cookie is only to be sent over HTTP(S), and not made available to client JavaScript (`true` by default). - - `signed`: a boolean indicating whether the cookie is to be signed (`true` by default). - - `overwrite`: a boolean indicating whether to overwrite previously set cookies of the same name (`true` by default). - -### req.session - -Represents the session for the given request. - -#### .isChanged - -Is `true` if the session has been changed during the request. - -#### .isNew - -Is `true` if the session is new. - -#### .isPopulated - -Determine if the session has been populated with data or is empty. - -### req.sessionOptions - -Represents the session options for the current request. These options are a -shallow clone of what was provided at middleware construction and can be -altered to change cookie setting behavior on a per-request basis. - -### Destroying a session - -To destroy a session simply set it to `null`: - -```js -req.session = null -``` - -### Saving a session - -Since the entire contents of the session is kept in a client-side cookie, the -session is "saved" by writing a cookie out in a `Set-Cookie` response header. -This is done automatically if there has been a change made to the session when -the Node.js response headers are being written to the client and the session -was not destroyed. - -## Examples - -### Simple view counter example - -```js -var cookieSession = require('cookie-session') -var express = require('express') - -var app = express() - -app.set('trust proxy', 1) // trust first proxy - -app.use(cookieSession({ - name: 'session', - keys: ['key1', 'key2'] -})) - -app.get('/', function (req, res, next) { - // Update views - req.session.views = (req.session.views || 0) + 1 - - // Write response - res.end(req.session.views + ' views') -}) - -app.listen(3000) -``` - -### Per-user sticky max age - -```js -var cookieSession = require('cookie-session') -var express = require('express') - -var app = express() - -app.set('trust proxy', 1) // trust first proxy - -app.use(cookieSession({ - name: 'session', - keys: ['key1', 'key2'] -})) - -// This allows you to set req.session.maxAge to let certain sessions -// have a different value than the default. -app.use(function (req, res, next) { - req.sessionOptions.maxAge = req.session.maxAge || req.sessionOptions.maxAge - next() -}) - -// ... your logic here ... -``` - -### Extending the session expiration - -This module does not send a `Set-Cookie` header if the contents of the session -have not changed. This means that to extend the expiration of a session in the -user's browser (in response to user activity, for example) some kind of -modification to the session needs be made. - -```js -var cookieSession = require('cookie-session') -var express = require('express') - -var app = express() - -app.use(cookieSession({ - name: 'session', - keys: ['key1', 'key2'] -})) - -// Update a value in the cookie so that the set-cookie will be sent. -// Only changes every minute so that it's not sent with every request. -app.use(function (req, res, next) { - req.session.nowInMinutes = Math.floor(Date.now() / 60e3) - next() -}) - -// ... your logic here ... -``` - -### Using a custom signature algorithm - -This example shows creating a custom `Keygrip` instance as the `keys` option -to provide keys and additional signature configuration. - -```js -var cookieSession = require('cookie-session') -var express = require('express') -var Keygrip = require('keygrip') - -var app = express() - -app.use(cookieSession({ - name: 'session', - keys: new Keygrip(['key1', 'key2'], 'SHA384', 'base64') -})) - -// ... your logic here ... -``` - -## Usage Limitations - -### Max Cookie Size - -Because the entire session object is encoded and stored in a cookie, it is -possible to exceed the maximum cookie size limits on different browsers. The -[RFC6265 specification](https://tools.ietf.org/html/rfc6265#section-6.1) -recommends that a browser **SHOULD** allow - -> At least 4096 bytes per cookie (as measured by the sum of the length of -> the cookie's name, value, and attributes) - -In practice this limit differs slightly across browsers. See a list of -[browser limits here](http://browsercookielimits.iain.guru). As a rule -of thumb **don't exceed 4093 bytes per domain**. - -If your session object is large enough to exceed a browser limit when encoded, -in most cases the browser will refuse to store the cookie. This will cause the -following requests from the browser to either a) not have any session -information or b) use old session information that was small enough to not -exceed the cookie limit. - -If you find your session object is hitting these limits, it is best to -consider if data in your session should be loaded from a database on the -server instead of transmitted to/from the browser with every request. Or -move to an [alternative session strategy](https://github.com/expressjs/session#compatible-session-stores) - -## License - -[MIT](LICENSE) - -[ci-image]: https://badgen.net/github/checks/expressjs/cookie-session/master?label=ci -[ci-url]: https://github.com/expressjs/cookie-session/actions?query=workflow%3Aci -[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/cookie-session/master -[coveralls-url]: https://coveralls.io/r/expressjs/cookie-session?branch=master -[npm-downloads-image]: https://badgen.net/npm/dm/cookie-session -[npm-url]: https://npmjs.org/package/cookie-session -[npm-version-image]: https://badgen.net/npm/v/cookie-session diff --git a/_includes/readmes/cors.md b/_includes/readmes/cors.md deleted file mode 100644 index 37ab8cffbf..0000000000 --- a/_includes/readmes/cors.md +++ /dev/null @@ -1,245 +0,0 @@ -# cors - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Build Status][github-actions-ci-image]][github-actions-ci-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -CORS is a node.js package for providing a [Connect](http://www.senchalabs.org/connect/)/[Express](http://expressjs.com/) middleware that can be used to enable [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) with various options. - -**[Follow me (@troygoode) on Twitter!](https://twitter.com/intent/user?screen_name=troygoode)** - -* [Installation](#installation) -* [Usage](#usage) - * [Simple Usage](#simple-usage-enable-all-cors-requests) - * [Enable CORS for a Single Route](#enable-cors-for-a-single-route) - * [Configuring CORS](#configuring-cors) - * [Configuring CORS w/ Dynamic Origin](#configuring-cors-w-dynamic-origin) - * [Enabling CORS Pre-Flight](#enabling-cors-pre-flight) - * [Configuring CORS Asynchronously](#configuring-cors-asynchronously) -* [Configuration Options](#configuration-options) -* [Demo](#demo) -* [License](#license) -* [Author](#author) - -## Installation - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install cors -``` - -## Usage - -### Simple Usage (Enable *All* CORS Requests) - -```javascript -var express = require('express') -var cors = require('cors') -var app = express() - -app.use(cors()) - -app.get('/products/:id', function (req, res, next) { - res.json({msg: 'This is CORS-enabled for all origins!'}) -}) - -app.listen(80, function () { - console.log('CORS-enabled web server listening on port 80') -}) -``` - -### Enable CORS for a Single Route - -```javascript -var express = require('express') -var cors = require('cors') -var app = express() - -app.get('/products/:id', cors(), function (req, res, next) { - res.json({msg: 'This is CORS-enabled for a Single Route'}) -}) - -app.listen(80, function () { - console.log('CORS-enabled web server listening on port 80') -}) -``` - -### Configuring CORS - -```javascript -var express = require('express') -var cors = require('cors') -var app = express() - -var corsOptions = { - origin: 'http://example.com', - optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204 -} - -app.get('/products/:id', cors(corsOptions), function (req, res, next) { - res.json({msg: 'This is CORS-enabled for only example.com.'}) -}) - -app.listen(80, function () { - console.log('CORS-enabled web server listening on port 80') -}) -``` - -### Configuring CORS w/ Dynamic Origin - -This module supports validating the origin dynamically using a function provided -to the `origin` option. This function will be passed a string that is the origin -(or `undefined` if the request has no origin), and a `callback` with the signature -`callback(error, origin)`. - -The `origin` argument to the callback can be any value allowed for the `origin` -option of the middleware, except a function. See the -[configuration options](#configuration-options) section for more information on all -the possible value types. - -This function is designed to allow the dynamic loading of allowed origin(s) from -a backing datasource, like a database. - -```javascript -var express = require('express') -var cors = require('cors') -var app = express() - -var corsOptions = { - origin: function (origin, callback) { - // db.loadOrigins is an example call to load - // a list of origins from a backing database - db.loadOrigins(function (error, origins) { - callback(error, origins) - }) - } -} - -app.get('/products/:id', cors(corsOptions), function (req, res, next) { - res.json({msg: 'This is CORS-enabled for an allowed domain.'}) -}) - -app.listen(80, function () { - console.log('CORS-enabled web server listening on port 80') -}) -``` - -### Enabling CORS Pre-Flight - -Certain CORS requests are considered 'complex' and require an initial -`OPTIONS` request (called the "pre-flight request"). An example of a -'complex' CORS request is one that uses an HTTP verb other than -GET/HEAD/POST (such as DELETE) or that uses custom headers. To enable -pre-flighting, you must add a new OPTIONS handler for the route you want -to support: - -```javascript -var express = require('express') -var cors = require('cors') -var app = express() - -app.options('/products/:id', cors()) // enable pre-flight request for DELETE request -app.del('/products/:id', cors(), function (req, res, next) { - res.json({msg: 'This is CORS-enabled for all origins!'}) -}) - -app.listen(80, function () { - console.log('CORS-enabled web server listening on port 80') -}) -``` - -You can also enable pre-flight across-the-board like so: - -```javascript -app.options('*', cors()) // include before other routes -``` - -NOTE: When using this middleware as an application level middleware (for -example, `app.use(cors())`), pre-flight requests are already handled for all -routes. - -### Configuring CORS Asynchronously - -```javascript -var express = require('express') -var cors = require('cors') -var app = express() - -var allowlist = ['http://example1.com', 'http://example2.com'] -var corsOptionsDelegate = function (req, callback) { - var corsOptions; - if (allowlist.indexOf(req.header('Origin')) !== -1) { - corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response - } else { - corsOptions = { origin: false } // disable CORS for this request - } - callback(null, corsOptions) // callback expects two parameters: error and options -} - -app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) { - res.json({msg: 'This is CORS-enabled for an allowed domain.'}) -}) - -app.listen(80, function () { - console.log('CORS-enabled web server listening on port 80') -}) -``` - -## Configuration Options - -* `origin`: Configures the **Access-Control-Allow-Origin** CORS header. Possible values: - - `Boolean` - set `origin` to `true` to reflect the [request origin](http://tools.ietf.org/html/draft-abarth-origin-09), as defined by `req.header('Origin')`, or set it to `false` to disable CORS. - - `String` - set `origin` to a specific origin. For example if you set it to `"http://example.com"` only requests from "http://example.com" will be allowed. - - `RegExp` - set `origin` to a regular expression pattern which will be used to test the request origin. If it's a match, the request origin will be reflected. For example the pattern `/example\.com$/` will reflect any request that is coming from an origin ending with "example.com". - - `Array` - set `origin` to an array of valid origins. Each origin can be a `String` or a `RegExp`. For example `["http://example1.com", /\.example2\.com$/]` will accept any request from "http://example1.com" or from a subdomain of "example2.com". - - `Function` - set `origin` to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback (called as `callback(err, origin)`, where `origin` is a non-function value of the `origin` option) as the second. -* `methods`: Configures the **Access-Control-Allow-Methods** CORS header. Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: `['GET', 'PUT', 'POST']`). -* `allowedHeaders`: Configures the **Access-Control-Allow-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Type,Authorization') or an array (ex: `['Content-Type', 'Authorization']`). If not specified, defaults to reflecting the headers specified in the request's **Access-Control-Request-Headers** header. -* `exposedHeaders`: Configures the **Access-Control-Expose-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') or an array (ex: `['Content-Range', 'X-Content-Range']`). If not specified, no custom headers are exposed. -* `credentials`: Configures the **Access-Control-Allow-Credentials** CORS header. Set to `true` to pass the header, otherwise it is omitted. -* `maxAge`: Configures the **Access-Control-Max-Age** CORS header. Set to an integer to pass the header, otherwise it is omitted. -* `preflightContinue`: Pass the CORS preflight response to the next handler. -* `optionsSuccessStatus`: Provides a status code to use for successful `OPTIONS` requests, since some legacy browsers (IE11, various SmartTVs) choke on `204`. - -The default configuration is the equivalent of: - -```json -{ - "origin": "*", - "methods": "GET,HEAD,PUT,PATCH,POST,DELETE", - "preflightContinue": false, - "optionsSuccessStatus": 204 -} -``` - -For details on the effect of each CORS header, read [this](https://web.dev/cross-origin-resource-sharing/) article on web.dev. - -## Demo - -A demo that illustrates CORS working (and not working) using React is available here: [https://node-cors-client.netlify.com](https://node-cors-client.netlify.com) - -Code for that demo can be found here: - -* Client: [https://github.com/troygoode/node-cors-client](https://github.com/troygoode/node-cors-client) -* Server: [https://github.com/troygoode/node-cors-server](https://github.com/troygoode/node-cors-server) - -## License - -[MIT License](http://www.opensource.org/licenses/mit-license.php) - -## Author - -[Troy Goode](https://github.com/TroyGoode) ([troygoode@gmail.com](mailto:troygoode@gmail.com)) - -[coveralls-image]: https://img.shields.io/coveralls/expressjs/cors/master.svg -[coveralls-url]: https://coveralls.io/r/expressjs/cors?branch=master -[downloads-image]: https://img.shields.io/npm/dm/cors.svg -[downloads-url]: https://npmjs.org/package/cors -[github-actions-ci-image]: https://img.shields.io/github/actions/workflow/status/expressjs/cors/ci.yml?branch=master&label=ci -[github-actions-ci-url]: https://github.com/expressjs/cors?query=workflow%3Aci -[npm-image]: https://img.shields.io/npm/v/cors.svg -[npm-url]: https://npmjs.org/package/cors diff --git a/_includes/readmes/errorhandler.md b/_includes/readmes/errorhandler.md deleted file mode 100644 index 0f2661ca30..0000000000 --- a/_includes/readmes/errorhandler.md +++ /dev/null @@ -1,130 +0,0 @@ -# errorhandler - -[![NPM Version][npm-version-image]][npm-url] -[![NPM Downloads][npm-downloads-image]][npm-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Development-only error handler middleware. - -This middleware is only intended to be used in a development environment, as -the _full error stack traces and internal details of any object passed to this -module_ will be sent back to the client when an error occurs. - -When an object is provided to Express as an error, this module will display -as much about this object as possible, and will do so by using content negotiation -for the response between HTML, JSON, and plain text. - - * When the object is a standard `Error` object, the string provided by the - `stack` property will be returned in HTML/text responses. - * When the object is a non-`Error` object, the result of - [util.inspect](https://nodejs.org/api/util.html#util_util_inspect_object_options) - will be returned in HTML/text responses. - * For JSON responses, the result will be an object with all enumerable properties - from the object in the response. - -## Install - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install errorhandler -``` - -## API - - - -```js -var errorhandler = require('errorhandler') -``` - -### errorhandler(options) - -Create new middleware to handle errors and respond with content negotiation. - -#### Options - -Error handler accepts these properties in the options object. - -##### log - -Provide a function to be called with the error and a string representation of -the error. Can be used to write the error to any desired location, or set to -`false` to only send the error back in the response. Called as -`log(err, str, req, res)` where `err` is the `Error` object, `str` is a string -representation of the error, `req` is the request object and `res` is the -response object (note, this function is invoked _after_ the response has been -written). - -The default value for this option is `true` unless `process.env.NODE_ENV === 'test'`. - -Possible values: - - * `true`: Log errors using `console.error(str)`. - * `false`: Only send the error back in the response. - * A function: pass the error to a function for handling. - -## Examples - -### Simple example - -Basic example of adding this middleware as the error handler only in development -with `connect` (`express` also can be used in this example). - -```js -var connect = require('connect') -var errorhandler = require('errorhandler') - -var app = connect() - -// assumes NODE_ENV is set by the user -if (process.env.NODE_ENV === 'development') { - // only use in development - app.use(errorhandler()) -} -``` - -### Custom output location - -Sometimes you may want to output the errors to a different location than STDERR -during development, like a system notification, for example. - - - -```js -var connect = require('connect') -var errorhandler = require('errorhandler') -var notifier = require('node-notifier') - -var app = connect() - -// assumes NODE_ENV is set by the user -if (process.env.NODE_ENV === 'development') { - // only use in development - app.use(errorhandler({ log: errorNotification })) -} - -function errorNotification (err, str, req) { - var title = 'Error in ' + req.method + ' ' + req.url - - notifier.notify({ - title: title, - message: str - }) -} -``` - -## License - -[MIT](LICENSE) - -[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/errorhandler/master -[coveralls-url]: https://coveralls.io/r/expressjs/errorhandler?branch=master -[npm-downloads-image]: https://badgen.net/npm/dm/errorhandler -[npm-url]: https://npmjs.org/package/errorhandler -[npm-version-image]: https://badgen.net/npm/v/errorhandler -[travis-image]: https://badgen.net/travis/expressjs/errorhandler/master -[travis-url]: https://travis-ci.org/expressjs/errorhandler diff --git a/_includes/readmes/express-master/examples.md b/_includes/readmes/express-master/examples.md deleted file mode 100644 index bd1f1f6310..0000000000 --- a/_includes/readmes/express-master/examples.md +++ /dev/null @@ -1,29 +0,0 @@ -# Express examples - -This page contains list of examples using Express. - -- [auth](./auth) - Authentication with login and password -- [content-negotiation](./content-negotiation) - HTTP content negotiation -- [cookie-sessions](./cookie-sessions) - Working with cookie-based sessions -- [cookies](./cookies) - Working with cookies -- [downloads](./downloads) - Transferring files to client -- [ejs](./ejs) - Working with Embedded JavaScript templating (ejs) -- [error-pages](./error-pages) - Creating error pages -- [error](./error) - Working with error middleware -- [hello-world](./hello-world) - Simple request handler -- [markdown](./markdown) - Markdown as template engine -- [multi-router](./multi-router) - Working with multiple Express routers -- [mvc](./mvc) - MVC-style controllers -- [online](./online) - Tracking online user activity with `online` and `redis` packages -- [params](./params) - Working with route parameters -- [resource](./resource) - Multiple HTTP operations on the same resource -- [route-map](./route-map) - Organizing routes using a map -- [route-middleware](./route-middleware) - Working with route middleware -- [route-separation](./route-separation) - Organizing routes per each resource -- [search](./search) - Search API -- [session](./session) - User sessions -- [static-files](./static-files) - Serving static files -- [vhost](./vhost) - Working with virtual hosts -- [view-constructor](./view-constructor) - Rendering views dynamically -- [view-locals](./view-locals) - Saving data in request object between middleware calls -- [web-service](./web-service) - Simple API service diff --git a/_includes/readmes/method-override.md b/_includes/readmes/method-override.md deleted file mode 100644 index 830b2ee0a9..0000000000 --- a/_includes/readmes/method-override.md +++ /dev/null @@ -1,180 +0,0 @@ -# method-override - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it. - -## Install - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install method-override -``` - -## API - -**NOTE** It is very important that this module is used **before** any module that -needs to know the method of the request (for example, it _must_ be used prior to -the `csurf` module). - -### methodOverride(getter, options) - -Create a new middleware function to override the `req.method` property with a new -value. This value will be pulled from the provided `getter`. - -- `getter` - The getter to use to look up the overridden request method for the request. (default: `X-HTTP-Method-Override`) -- `options.methods` - The allowed methods the original request must be in to check for a method override value. (default: `['POST']`) - -If the found method is supported by node.js core, then `req.method` will be set to -this value, as if it has originally been that value. The previous `req.method` -value will be stored in `req.originalMethod`. - -#### getter - -This is the method of getting the override value from the request. If a function is provided, -the `req` is passed as the first argument, the `res` as the second argument and the method is -expected to be returned. If a string is provided, the string is used to look up the method -with the following rules: - -- If the string starts with `X-`, then it is treated as the name of a header and that header - is used for the method override. If the request contains the same header multiple times, the - first occurrence is used. -- All other strings are treated as a key in the URL query string. - -#### options.methods - -This allows the specification of what methods(s) the request *MUST* be in in order to check for -the method override value. This defaults to only `POST` methods, which is the only method the -override should arrive in. More methods may be specified here, but it may introduce security -issues and cause weird behavior when requests travel through caches. This value is an array -of methods in upper-case. `null` can be specified to allow all methods. - -## Examples - -### override using a header - -To use a header to override the method, specify the header name -as a string argument to the `methodOverride` function. To then make -the call, send a `POST` request to a URL with the overridden method -as the value of that header. This method of using a header would -typically be used in conjunction with `XMLHttpRequest` on implementations -that do not support the method you are trying to use. - -```js -var express = require('express') -var methodOverride = require('method-override') -var app = express() - -// override with the X-HTTP-Method-Override header in the request -app.use(methodOverride('X-HTTP-Method-Override')) -``` - -Example call with header override using `XMLHttpRequest`: - - - -```js -var xhr = new XMLHttpRequest() -xhr.onload = onload -xhr.open('post', '/resource', true) -xhr.setRequestHeader('X-HTTP-Method-Override', 'DELETE') -xhr.send() - -function onload () { - alert('got response: ' + this.responseText) -} -``` - -### override using a query value - -To use a query string value to override the method, specify the query -string key as a string argument to the `methodOverride` function. To -then make the call, send a `POST` request to a URL with the overridden -method as the value of that query string key. This method of using a -query value would typically be used in conjunction with plain HTML -`
` elements when trying to support legacy browsers but still use -newer methods. - -```js -var express = require('express') -var methodOverride = require('method-override') -var app = express() - -// override with POST having ?_method=DELETE -app.use(methodOverride('_method')) -``` - -Example call with query override using HTML ``: - -```html - - -
-``` - -### multiple format support - -```js -var express = require('express') -var methodOverride = require('method-override') -var app = express() - -// override with different headers; last one takes precedence -app.use(methodOverride('X-HTTP-Method')) // Microsoft -app.use(methodOverride('X-HTTP-Method-Override')) // Google/GData -app.use(methodOverride('X-Method-Override')) // IBM -``` - -### custom logic - -You can implement any kind of custom logic with a function for the `getter`. The following -implements the logic for looking in `req.body` that was in `method-override@1`: - -```js -var bodyParser = require('body-parser') -var express = require('express') -var methodOverride = require('method-override') -var app = express() - -// NOTE: when using req.body, you must fully parse the request body -// before you call methodOverride() in your middleware stack, -// otherwise req.body will not be populated. -app.use(bodyParser.urlencoded()) -app.use(methodOverride(function (req, res) { - if (req.body && typeof req.body === 'object' && '_method' in req.body) { - // look in urlencoded POST bodies and delete it - var method = req.body._method - delete req.body._method - return method - } -})) -``` - -Example call with query override using HTML `
`: - -```html - - - - -
-``` - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/method-override.svg -[npm-url]: https://npmjs.org/package/method-override -[travis-image]: https://img.shields.io/travis/expressjs/method-override/master.svg -[travis-url]: https://travis-ci.org/expressjs/method-override -[coveralls-image]: https://img.shields.io/coveralls/expressjs/method-override/master.svg -[coveralls-url]: https://coveralls.io/r/expressjs/method-override?branch=master -[downloads-image]: https://img.shields.io/npm/dm/method-override.svg -[downloads-url]: https://npmjs.org/package/method-override diff --git a/_includes/readmes/morgan.md b/_includes/readmes/morgan.md deleted file mode 100644 index cc6379790c..0000000000 --- a/_includes/readmes/morgan.md +++ /dev/null @@ -1,436 +0,0 @@ -# morgan - -[![NPM Version][npm-version-image]][npm-url] -[![NPM Downloads][npm-downloads-image]][npm-url] -[![Build Status][ci-image]][ci-url] -[![Coverage Status][coveralls-image]][coveralls-url] - -HTTP request logger middleware for node.js - -> Named after [Dexter](http://en.wikipedia.org/wiki/Dexter_Morgan), a show you should not watch until completion. - -## Installation - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install morgan -``` - -## API - - - -```js -var morgan = require('morgan') -``` - -### morgan(format, options) - -Create a new morgan logger middleware function using the given `format` and `options`. -The `format` argument may be a string of a predefined name (see below for the names), -a string of a format string, or a function that will produce a log entry. - -The `format` function will be called with three arguments `tokens`, `req`, and `res`, -where `tokens` is an object with all defined tokens, `req` is the HTTP request and `res` -is the HTTP response. The function is expected to return a string that will be the log -line, or `undefined` / `null` to skip logging. - -#### Using a predefined format string - - - -```js -morgan('tiny') -``` - -#### Using format string of predefined tokens - - - -```js -morgan(':method :url :status :res[content-length] - :response-time ms') -``` - -#### Using a custom format function - - - -``` js -morgan(function (tokens, req, res) { - return [ - tokens.method(req, res), - tokens.url(req, res), - tokens.status(req, res), - tokens.res(req, res, 'content-length'), '-', - tokens['response-time'](req, res), 'ms' - ].join(' ') -}) -``` - -#### Options - -Morgan accepts these properties in the options object. - -##### immediate - -Write log line on request instead of response. This means that a requests will -be logged even if the server crashes, _but data from the response (like the -response code, content length, etc.) cannot be logged_. - -##### skip - -Function to determine if logging is skipped, defaults to `false`. This function -will be called as `skip(req, res)`. - - - -```js -// EXAMPLE: only log error responses -morgan('combined', { - skip: function (req, res) { return res.statusCode < 400 } -}) -``` - -##### stream - -Output stream for writing log lines, defaults to `process.stdout`. - -#### Predefined Formats - -There are various pre-defined formats provided: - -##### combined - -Standard Apache combined log output. -``` -:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" -# will output -::1 - - [27/Nov/2024:06:21:42 +0000] "GET /combined HTTP/1.1" 200 2 "-" "curl/8.7.1" -``` - -##### common - -Standard Apache common log output. - -``` -:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] -# will output -::1 - - [27/Nov/2024:06:21:46 +0000] "GET /common HTTP/1.1" 200 2 -``` - -##### dev - -Concise output colored by response status for development use. The `:status` -token will be colored green for success codes, red for server error codes, -yellow for client error codes, cyan for redirection codes, and uncolored -for information codes. - -``` -:method :url :status :response-time ms - :res[content-length] -# will output -GET /dev 200 0.224 ms - 2 -``` - -##### short - -Shorter than default, also including response time. - -``` -:remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms -# will output -::1 - GET /short HTTP/1.1 200 2 - 0.283 ms -``` - -##### tiny - -The minimal output. - -``` -:method :url :status :res[content-length] - :response-time ms -# will output -GET /tiny 200 2 - 0.188 ms -``` - -#### Tokens - -##### Creating new tokens - -To define a token, simply invoke `morgan.token()` with the name and a callback function. -This callback function is expected to return a string value. The value returned is then -available as ":type" in this case: - - - -```js -morgan.token('type', function (req, res) { return req.headers['content-type'] }) -``` - -Calling `morgan.token()` using the same name as an existing token will overwrite that -token definition. - -The token function is expected to be called with the arguments `req` and `res`, representing -the HTTP request and HTTP response. Additionally, the token can accept further arguments of -it's choosing to customize behavior. - -##### :date[format] - -The current date and time in UTC. The available formats are: - - - `clf` for the common log format (`"10/Oct/2000:13:55:36 +0000"`) - - `iso` for the common ISO 8601 date time format (`2000-10-10T13:55:36.000Z`) - - `web` for the common RFC 1123 date time format (`Tue, 10 Oct 2000 13:55:36 GMT`) - -If no format is given, then the default is `web`. - -##### :http-version - -The HTTP version of the request. - -##### :method - -The HTTP method of the request. - -##### :referrer - -The Referrer header of the request. This will use the standard mis-spelled Referer header if exists, otherwise Referrer. - -##### :remote-addr - -The remote address of the request. This will use `req.ip`, otherwise the standard `req.connection.remoteAddress` value (socket address). - -##### :remote-user - -The user authenticated as part of Basic auth for the request. - -##### :req[header] - -The given `header` of the request. If the header is not present, the -value will be displayed as `"-"` in the log. - -##### :res[header] - -The given `header` of the response. If the header is not present, the -value will be displayed as `"-"` in the log. - -##### :response-time[digits] - -The time between the request coming into `morgan` and when the response -headers are written, in milliseconds. - -The `digits` argument is a number that specifies the number of digits to -include on the number, defaulting to `3`, which provides microsecond precision. - -##### :status - -The status code of the response. - -If the request/response cycle completes before a response was sent to the -client (for example, the TCP socket closed prematurely by a client aborting -the request), then the status will be empty (displayed as `"-"` in the log). - -##### :total-time[digits] - -The time between the request coming into `morgan` and when the response -has finished being written out to the connection, in milliseconds. - -The `digits` argument is a number that specifies the number of digits to -include on the number, defaulting to `3`, which provides microsecond precision. - -##### :url - -The URL of the request. This will use `req.originalUrl` if exists, otherwise `req.url`. - -##### :user-agent - -The contents of the User-Agent header of the request. - -### morgan.compile(format) - -Compile a format string into a `format` function for use by `morgan`. A format string -is a string that represents a single log line and can utilize token syntax. -Tokens are references by `:token-name`. If tokens accept arguments, they can -be passed using `[]`, for example: `:token-name[pretty]` would pass the string -`'pretty'` as an argument to the token `token-name`. - -The function returned from `morgan.compile` takes three arguments `tokens`, `req`, and -`res`, where `tokens` is object with all defined tokens, `req` is the HTTP request and -`res` is the HTTP response. The function will return a string that will be the log line, -or `undefined` / `null` to skip logging. - -Normally formats are defined using `morgan.format(name, format)`, but for certain -advanced uses, this compile function is directly available. - -## Examples - -### express/connect - -Sample app that will log all request in the Apache combined format to STDOUT - -```js -var express = require('express') -var morgan = require('morgan') - -var app = express() - -app.use(morgan('combined')) - -app.get('/', function (req, res) { - res.send('hello, world!') -}) -``` - -### vanilla http server - -Sample app that will log all request in the Apache combined format to STDOUT - -```js -var finalhandler = require('finalhandler') -var http = require('http') -var morgan = require('morgan') - -// create "middleware" -var logger = morgan('combined') - -http.createServer(function (req, res) { - var done = finalhandler(req, res) - logger(req, res, function (err) { - if (err) return done(err) - - // respond to request - res.setHeader('content-type', 'text/plain') - res.end('hello, world!') - }) -}) -``` - -### write logs to a file - -#### single file - -Sample app that will log all requests in the Apache combined format to the file -`access.log`. - -```js -var express = require('express') -var fs = require('fs') -var morgan = require('morgan') -var path = require('path') - -var app = express() - -// create a write stream (in append mode) -var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' }) - -// setup the logger -app.use(morgan('combined', { stream: accessLogStream })) - -app.get('/', function (req, res) { - res.send('hello, world!') -}) -``` - -#### log file rotation - -Sample app that will log all requests in the Apache combined format to one log -file per day in the `log/` directory using the -[rotating-file-stream module](https://www.npmjs.com/package/rotating-file-stream). - -```js -var express = require('express') -var morgan = require('morgan') -var path = require('path') -var rfs = require('rotating-file-stream') // version 2.x - -var app = express() - -// create a rotating write stream -var accessLogStream = rfs.createStream('access.log', { - interval: '1d', // rotate daily - path: path.join(__dirname, 'log') -}) - -// setup the logger -app.use(morgan('combined', { stream: accessLogStream })) - -app.get('/', function (req, res) { - res.send('hello, world!') -}) -``` - -### split / dual logging - -The `morgan` middleware can be used as many times as needed, enabling -combinations like: - - * Log entry on request and one on response - * Log all requests to file, but errors to console - * ... and more! - -Sample app that will log all requests to a file using Apache format, but -error responses are logged to the console: - -```js -var express = require('express') -var fs = require('fs') -var morgan = require('morgan') -var path = require('path') - -var app = express() - -// log only 4xx and 5xx responses to console -app.use(morgan('dev', { - skip: function (req, res) { return res.statusCode < 400 } -})) - -// log all requests to access.log -app.use(morgan('common', { - stream: fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' }) -})) - -app.get('/', function (req, res) { - res.send('hello, world!') -}) -``` - -### use custom token formats - -Sample app that will use custom token formats. This adds an ID to all requests and displays it using the `:id` token. - -```js -var express = require('express') -var morgan = require('morgan') -var uuid = require('node-uuid') - -morgan.token('id', function getId (req) { - return req.id -}) - -var app = express() - -app.use(assignId) -app.use(morgan(':id :method :url :response-time')) - -app.get('/', function (req, res) { - res.send('hello, world!') -}) - -function assignId (req, res, next) { - req.id = uuid.v4() - next() -} -``` - -## License - -[MIT](LICENSE) - -[ci-image]: https://badgen.net/github/checks/expressjs/morgan/master?label=ci -[ci-url]: https://github.com/expressjs/morgan/actions/workflows/ci.yml -[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/morgan/master -[coveralls-url]: https://coveralls.io/r/expressjs/morgan?branch=master -[npm-downloads-image]: https://badgen.net/npm/dm/morgan -[npm-url]: https://npmjs.org/package/morgan -[npm-version-image]: https://badgen.net/npm/v/morgan diff --git a/_includes/readmes/multer.md b/_includes/readmes/multer.md deleted file mode 100644 index a52a9aabce..0000000000 --- a/_includes/readmes/multer.md +++ /dev/null @@ -1,336 +0,0 @@ -# Multer [![Build Status](https://badgen.net/github/checks/expressjs/multer/master?label=ci)](https://github.com/expressjs/multer/actions/workflows/ci.yml) [![Test Coverage](https://badgen.net/coveralls/c/github/expressjs/multer/master)](https://coveralls.io/r/expressjs/multer?branch=master) [![NPM version](https://badge.fury.io/js/multer.svg)](https://badge.fury.io/js/multer) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard) - -Multer is a node.js middleware for handling `multipart/form-data`, which is primarily used for uploading files. It is written -on top of [busboy](https://github.com/mscdex/busboy) for maximum efficiency. - -**NOTE**: Multer will not process any form which is not multipart (`multipart/form-data`). - -## Translations - -This README is also available in other languages: - -- [العربية](https://github.com/expressjs/multer/blob/master/doc/README-ar.md) (Arabic) -- [Español](https://github.com/expressjs/multer/blob/master/doc/README-es.md) (Spanish) -- [简体中文](https://github.com/expressjs/multer/blob/master/doc/README-zh-cn.md) (Chinese) -- [한국어](https://github.com/expressjs/multer/blob/master/doc/README-ko.md) (Korean) -- [Русский язык](https://github.com/expressjs/multer/blob/master/doc/README-ru.md) (Russian) -- [Việt Nam](https://github.com/expressjs/multer/blob/master/doc/README-vi.md) (Vietnam) -- [Português](https://github.com/expressjs/multer/blob/master/doc/README-pt-br.md) (Portuguese Brazil) -- [Français](https://github.com/expressjs/multer/blob/master/doc/README-fr.md) (French) -- [O'zbek tili](https://github.com/expressjs/multer/blob/master/doc/README-uz.md) (Uzbek) - -## Installation - -```sh -$ npm install --save multer -``` - -## Usage - -Multer adds a `body` object and a `file` or `files` object to the `request` object. The `body` object contains the values of the text fields of the form, the `file` or `files` object contains the files uploaded via the form. - -Basic usage example: - -Don't forget the `enctype="multipart/form-data"` in your form. - -```html -
- -
-``` - -```javascript -const express = require('express') -const multer = require('multer') -const upload = multer({ dest: 'uploads/' }) - -const app = express() - -app.post('/profile', upload.single('avatar'), function (req, res, next) { - // req.file is the `avatar` file - // req.body will hold the text fields, if there were any -}) - -app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) { - // req.files is array of `photos` files - // req.body will contain the text fields, if there were any -}) - -const cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]) -app.post('/cool-profile', cpUpload, function (req, res, next) { - // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files - // - // e.g. - // req.files['avatar'][0] -> File - // req.files['gallery'] -> Array - // - // req.body will contain the text fields, if there were any -}) -``` - -In case you need to handle a text-only multipart form, you should use the `.none()` method: - -```javascript -const express = require('express') -const app = express() -const multer = require('multer') -const upload = multer() - -app.post('/profile', upload.none(), function (req, res, next) { - // req.body contains the text fields -}) -``` - -Here's an example on how multer is used in a HTML form. Take special note of the `enctype="multipart/form-data"` and `name="uploaded_file"` fields: - -```html -
-
- - - -
-
-``` - -Then in your javascript file you would add these lines to access both the file and the body. It is important that you use the `name` field value from the form in your upload function. This tells multer which field on the request it should look for the files in. If these fields aren't the same in the HTML form and on your server, your upload will fail: - -```javascript -const multer = require('multer') -const upload = multer({ dest: './public/data/uploads/' }) -app.post('/stats', upload.single('uploaded_file'), function (req, res) { - // req.file is the name of your file in the form above, here 'uploaded_file' - // req.body will hold the text fields, if there were any - console.log(req.file, req.body) -}); -``` - - - -## API - -### File information - -Each file contains the following information: - -Key | Description | Note ---- | --- | --- -`fieldname` | Field name specified in the form | -`originalname` | Name of the file on the user's computer | -`encoding` | Encoding type of the file | -`mimetype` | Mime type of the file | -`size` | Size of the file in bytes | -`destination` | The folder to which the file has been saved | `DiskStorage` -`filename` | The name of the file within the `destination` | `DiskStorage` -`path` | The full path to the uploaded file | `DiskStorage` -`buffer` | A `Buffer` of the entire file | `MemoryStorage` - -### `multer(opts)` - -Multer accepts an options object, the most basic of which is the `dest` -property, which tells Multer where to upload the files. In case you omit the -options object, the files will be kept in memory and never written to disk. - -By default, Multer will rename the files so as to avoid naming conflicts. The -renaming function can be customized according to your needs. - -The following are the options that can be passed to Multer. - -Key | Description ---- | --- -`dest` or `storage` | Where to store the files -`fileFilter` | Function to control which files are accepted -`limits` | Limits of the uploaded data -`preservePath` | Keep the full path of files instead of just the base name - -In an average web app, only `dest` might be required, and configured as shown in -the following example. - -```javascript -const upload = multer({ dest: 'uploads/' }) -``` - -If you want more control over your uploads, you'll want to use the `storage` -option instead of `dest`. Multer ships with storage engines `DiskStorage` -and `MemoryStorage`; More engines are available from third parties. - -#### `.single(fieldname)` - -Accept a single file with the name `fieldname`. The single file will be stored -in `req.file`. - -#### `.array(fieldname[, maxCount])` - -Accept an array of files, all with the name `fieldname`. Optionally error out if -more than `maxCount` files are uploaded. The array of files will be stored in -`req.files`. - -#### `.fields(fields)` - -Accept a mix of files, specified by `fields`. An object with arrays of files -will be stored in `req.files`. - -`fields` should be an array of objects with `name` and optionally a `maxCount`. -Example: - -```javascript -[ - { name: 'avatar', maxCount: 1 }, - { name: 'gallery', maxCount: 8 } -] -``` - -#### `.none()` - -Accept only text fields. If any file upload is made, error with code -"LIMIT\_UNEXPECTED\_FILE" will be issued. - -#### `.any()` - -Accepts all files that comes over the wire. An array of files will be stored in -`req.files`. - -**WARNING:** Make sure that you always handle the files that a user uploads. -Never add multer as a global middleware since a malicious user could upload -files to a route that you didn't anticipate. Only use this function on routes -where you are handling the uploaded files. - -### `storage` - -#### `DiskStorage` - -The disk storage engine gives you full control on storing files to disk. - -```javascript -const storage = multer.diskStorage({ - destination: function (req, file, cb) { - cb(null, '/tmp/my-uploads') - }, - filename: function (req, file, cb) { - const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9) - cb(null, file.fieldname + '-' + uniqueSuffix) - } -}) - -const upload = multer({ storage: storage }) -``` - -There are two options available, `destination` and `filename`. They are both -functions that determine where the file should be stored. - -`destination` is used to determine within which folder the uploaded files should -be stored. This can also be given as a `string` (e.g. `'/tmp/uploads'`). If no -`destination` is given, the operating system's default directory for temporary -files is used. - -**Note:** You are responsible for creating the directory when providing -`destination` as a function. When passing a string, multer will make sure that -the directory is created for you. - -`filename` is used to determine what the file should be named inside the folder. -If no `filename` is given, each file will be given a random name that doesn't -include any file extension. - -**Note:** Multer will not append any file extension for you, your function -should return a filename complete with an file extension. - -Each function gets passed both the request (`req`) and some information about -the file (`file`) to aid with the decision. - -Note that `req.body` might not have been fully populated yet. It depends on the -order that the client transmits fields and files to the server. - -For understanding the calling convention used in the callback (needing to pass -null as the first param), refer to -[Node.js error handling](https://web.archive.org/web/20220417042018/https://www.joyent.com/node-js/production/design/errors) - -#### `MemoryStorage` - -The memory storage engine stores the files in memory as `Buffer` objects. It -doesn't have any options. - -```javascript -const storage = multer.memoryStorage() -const upload = multer({ storage: storage }) -``` - -When using memory storage, the file info will contain a field called -`buffer` that contains the entire file. - -**WARNING**: Uploading very large files, or relatively small files in large -numbers very quickly, can cause your application to run out of memory when -memory storage is used. - -### `limits` - -An object specifying the size limits of the following optional properties. Multer passes this object into busboy directly, and the details of the properties can be found on [busboy's page](https://github.com/mscdex/busboy#busboy-methods). - -The following integer values are available: - -Key | Description | Default ---- | --- | --- -`fieldNameSize` | Max field name size | 100 bytes -`fieldSize` | Max field value size (in bytes) | 1MB -`fields` | Max number of non-file fields | Infinity -`fileSize` | For multipart forms, the max file size (in bytes) | Infinity -`files` | For multipart forms, the max number of file fields | Infinity -`parts` | For multipart forms, the max number of parts (fields + files) | Infinity -`headerPairs` | For multipart forms, the max number of header key=>value pairs to parse | 2000 - -Specifying the limits can help protect your site against denial of service (DoS) attacks. - -### `fileFilter` - -Set this to a function to control which files should be uploaded and which -should be skipped. The function should look like this: - -```javascript -function fileFilter (req, file, cb) { - - // The function should call `cb` with a boolean - // to indicate if the file should be accepted - - // To reject this file pass `false`, like so: - cb(null, false) - - // To accept the file pass `true`, like so: - cb(null, true) - - // You can always pass an error if something goes wrong: - cb(new Error('I don\'t have a clue!')) - -} -``` - -## Error handling - -When encountering an error, Multer will delegate the error to Express. You can -display a nice error page using [the standard express way](http://expressjs.com/guide/error-handling.html). - -If you want to catch errors specifically from Multer, you can call the -middleware function by yourself. Also, if you want to catch only [the Multer errors](https://github.com/expressjs/multer/blob/master/lib/multer-error.js), you can use the `MulterError` class that is attached to the `multer` object itself (e.g. `err instanceof multer.MulterError`). - -```javascript -const multer = require('multer') -const upload = multer().single('avatar') - -app.post('/profile', function (req, res) { - upload(req, res, function (err) { - if (err instanceof multer.MulterError) { - // A Multer error occurred when uploading. - } else if (err) { - // An unknown error occurred when uploading. - } - - // Everything went fine. - }) -}) -``` - -## Custom storage engine - -For information on how to build your own storage engine, see [Multer Storage Engine](https://github.com/expressjs/multer/blob/master/StorageEngine.md). - -## License - -[MIT](LICENSE) diff --git a/_includes/readmes/response-time.md b/_includes/readmes/response-time.md deleted file mode 100644 index 4e26aee0fe..0000000000 --- a/_includes/readmes/response-time.md +++ /dev/null @@ -1,142 +0,0 @@ -# response-time - -[![NPM Version][npm-version-image]][npm-url] -[![NPM Downloads][npm-downloads-image]][npm-url] -[![Node.js Version][node-image]][node-url] -[![Build Status][ci-image]][ci-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Response time for Node.js servers. - -This module creates a middleware that records the response time for -requests in HTTP servers. The "response time" is defined here as the -elapsed time from when a request enters this middleware to when the -headers are written out to the client. - -## Installation - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install response-time -``` - -## API - - - -```js -var responseTime = require('response-time') -``` - -### responseTime([options]) - -Create a middleware that adds a `X-Response-Time` header to responses. If -you don't want to use this module to automatically set a header, please -see the section about [`responseTime(fn)`](#responsetimefn). - -#### Options - -The `responseTime` function accepts an optional `options` object that may -contain any of the following keys: - -##### digits - -The fixed number of digits to include in the output, which is always in -milliseconds, defaults to `3` (ex: `2.300ms`). - -##### header - -The name of the header to set, defaults to `X-Response-Time`. - -##### suffix - -Boolean to indicate if units of measurement suffix should be added to -the output, defaults to `true` (ex: `2.300ms` vs `2.300`). - -### responseTime(fn) - -Create a new middleware that records the response time of a request and -makes this available to your own function `fn`. The `fn` argument will be -invoked as `fn(req, res, time)`, where `time` is a number in milliseconds. - -## Examples - -### express/connect - -```js -var express = require('express') -var responseTime = require('response-time') - -var app = express() - -app.use(responseTime()) - -app.get('/', function (req, res) { - res.send('hello, world!') -}) -``` - -### vanilla http server - -```js -var finalhandler = require('finalhandler') -var http = require('http') -var responseTime = require('response-time') - -// create "middleware" -var _responseTime = responseTime() - -http.createServer(function (req, res) { - var done = finalhandler(req, res) - _responseTime(req, res, function (err) { - if (err) return done(err) - - // respond to request - res.setHeader('content-type', 'text/plain') - res.end('hello, world!') - }) -}) -``` - -### response time metrics - -```js -var express = require('express') -var responseTime = require('response-time') -var StatsD = require('node-statsd') - -var app = express() -var stats = new StatsD() - -stats.socket.on('error', function (error) { - console.error(error.stack) -}) - -app.use(responseTime(function (req, res, time) { - var stat = (req.method + req.url).toLowerCase() - .replace(/[:.]/g, '') - .replace(/\//g, '_') - stats.timing(stat, time) -})) - -app.get('/', function (req, res) { - res.send('hello, world!') -}) -``` - -## License - -[MIT](LICENSE) - -[npm-version-image]: https://badgen.net/npm/v/response-time -[npm-url]: https://npmjs.org/package/response-time -[npm-downloads-image]: https://badgen.net/npm/dm/response-time -[node-image]: https://badgen.net/npm/node/response-time -[node-url]: https://nodejs.org/en/download -[ci-image]: https://badgen.net/github/checks/express/response-time/master?label=ci -[ci-url]: https://github.com/express/response-time/actions/workflows/ci.yml -[coveralls-image]: https://badgen.net/coveralls/c/github/express/response-time/master -[coveralls-url]: https://coveralls.io/r/express/response-time?branch=master diff --git a/_includes/readmes/serve-favicon.md b/_includes/readmes/serve-favicon.md deleted file mode 100644 index ce8daa83d5..0000000000 --- a/_includes/readmes/serve-favicon.md +++ /dev/null @@ -1,136 +0,0 @@ -# serve-favicon - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Linux Build Status][ci-image]][ci-url] -[![Windows Build][appveyor-image]][appveyor-url] -[![Coverage Status][coveralls-image]][coveralls-url] - -Node.js middleware for serving a favicon. - -A favicon is a visual cue that client software, like browsers, use to identify -a site. For an example and more information, please visit -[the Wikipedia article on favicons](https://en.wikipedia.org/wiki/Favicon). - -Why use this module? - - - User agents request `favicon.ico` frequently and indiscriminately, so you - may wish to exclude these requests from your logs by using this middleware - before your logger middleware. - - This module caches the icon in memory to improve performance by skipping - disk access. - - This module provides an `ETag` based on the contents of the icon, rather - than file system properties. - - This module will serve with the most compatible `Content-Type`. - -**Note** This module is exclusively for serving the "default, implicit favicon", -which is `GET /favicon.ico`. For additional vendor-specific icons that require -HTML markup, additional middleware is required to serve the relevant files, for -example [serve-static](https://npmjs.org/package/serve-static). - -## Install - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install serve-favicon -``` - -## API - -### favicon(path, options) - -Create new middleware to serve a favicon from the given `path` to a favicon file. -`path` may also be a `Buffer` of the icon to serve. - -#### Options - -Serve favicon accepts these properties in the options object. - -##### maxAge - -The `cache-control` `max-age` directive in `ms`, defaulting to 1 year. This can -also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) -module. - -## Examples - -Typically this middleware will come very early in your stack (maybe even first) -to avoid processing any other middleware if we already know the request is for -`/favicon.ico`. - -### express - -```javascript -var express = require('express') -var favicon = require('serve-favicon') -var path = require('path') - -var app = express() -app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))) - -// Add your routes here, etc. - -app.listen(3000) -``` - -### connect - -```javascript -var connect = require('connect') -var favicon = require('serve-favicon') -var path = require('path') - -var app = connect() -app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))) - -// Add your middleware here, etc. - -app.listen(3000) -``` - -### vanilla http server - -This middleware can be used anywhere, even outside express/connect. It takes -`req`, `res`, and `callback`. - -```javascript -var http = require('http') -var favicon = require('serve-favicon') -var finalhandler = require('finalhandler') -var path = require('path') - -var _favicon = favicon(path.join(__dirname, 'public', 'favicon.ico')) - -var server = http.createServer(function onRequest (req, res) { - var done = finalhandler(req, res) - - _favicon(req, res, function onNext (err) { - if (err) return done(err) - - // continue to process the request here, etc. - - res.statusCode = 404 - res.end('oops') - }) -}) - -server.listen(3000) -``` - -## License - -[MIT](LICENSE) - -[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/serve-favicon/master.svg?label=windows -[appveyor-url]: https://ci.appveyor.com/project/dougwilson/serve-favicon -[ci-image]: https://badgen.net/github/checks/expressjs/serve-favicon/master?label=ci -[ci-url]: https://github.com/expressjs/serve-favicon/actions/workflows/ci.yml -[coveralls-image]: https://img.shields.io/coveralls/expressjs/serve-favicon.svg -[coveralls-url]: https://coveralls.io/r/expressjs/serve-favicon?branch=master -[downloads-image]: https://img.shields.io/npm/dm/serve-favicon.svg -[downloads-url]: https://npmjs.org/package/serve-favicon -[npm-image]: https://img.shields.io/npm/v/serve-favicon.svg -[npm-url]: https://npmjs.org/package/serve-favicon diff --git a/_includes/readmes/serve-index.md b/_includes/readmes/serve-index.md deleted file mode 100644 index f720b0d950..0000000000 --- a/_includes/readmes/serve-index.md +++ /dev/null @@ -1,151 +0,0 @@ -# serve-index - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Linux Build Status][ci-image]][ci-url] -[![Windows Build][appveyor-image]][appveyor-url] -[![Coverage Status][coveralls-image]][coveralls-url] - - Serves pages that contain directory listings for a given path. - -## Install - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install serve-index -``` - -## API - -```js -var serveIndex = require('serve-index') -``` - -### serveIndex(path, options) - -Returns middlware that serves an index of the directory in the given `path`. - -The `path` is based off the `req.url` value, so a `req.url` of `'/some/dir` -with a `path` of `'public'` will look at `'public/some/dir'`. If you are using -something like `express`, you can change the URL "base" with `app.use` (see -the express example). - -#### Options - -Serve index accepts these properties in the options object. - -##### filter - -Apply this filter function to files. Defaults to `false`. The `filter` function -is called for each file, with the signature `filter(filename, index, files, dir)` -where `filename` is the name of the file, `index` is the array index, `files` is -the array of files and `dir` is the absolute path the file is located (and thus, -the directory the listing is for). - -##### hidden - -Display hidden (dot) files. Defaults to `false`. - -##### icons - -Display icons. Defaults to `false`. - -##### stylesheet - -Optional path to a CSS stylesheet. Defaults to a built-in stylesheet. - -##### template - -Optional path to an HTML template or a function that will render a HTML -string. Defaults to a built-in template. - -When given a string, the string is used as a file path to load and then the -following tokens are replaced in templates: - - * `{directory}` with the name of the directory. - * `{files}` with the HTML of an unordered list of file links. - * `{linked-path}` with the HTML of a link to the directory. - * `{style}` with the specified stylesheet and embedded images. - -When given as a function, the function is called as `template(locals, callback)` -and it needs to invoke `callback(error, htmlString)`. The following are the -provided locals: - - * `directory` is the directory being displayed (where `/` is the root). - * `displayIcons` is a Boolean for if icons should be rendered or not. - * `fileList` is a sorted array of files in the directory. The array contains - objects with the following properties: - - `name` is the relative name for the file. - - `stat` is a `fs.Stats` object for the file. - * `path` is the full filesystem path to `directory`. - * `style` is the default stylesheet or the contents of the `stylesheet` option. - * `viewName` is the view name provided by the `view` option. - -##### view - -Display mode. `tiles` and `details` are available. Defaults to `tiles`. - -## Examples - -### Serve directory indexes with vanilla node.js http server - -```js -var finalhandler = require('finalhandler') -var http = require('http') -var serveIndex = require('serve-index') -var serveStatic = require('serve-static') - -// Serve directory indexes for public/ftp folder (with icons) -var index = serveIndex('public/ftp', {'icons': true}) - -// Serve up public/ftp folder files -var serve = serveStatic('public/ftp') - -// Create server -var server = http.createServer(function onRequest(req, res){ - var done = finalhandler(req, res) - serve(req, res, function onNext(err) { - if (err) return done(err) - index(req, res, done) - }) -}) - -// Listen -server.listen(3000) -``` - -### Serve directory indexes with express - -```js -var express = require('express') -var serveIndex = require('serve-index') - -var app = express() - -// Serve URLs like /ftp/thing as public/ftp/thing -// The express.static serves the file contents -// The serveIndex is this module serving the directory -app.use('/ftp', express.static('public/ftp'), serveIndex('public/ftp', {'icons': true})) - -// Listen -app.listen(3000) -``` - -## License - -[MIT](LICENSE). The [Silk](http://www.famfamfam.com/lab/icons/silk/) icons -are created by/copyright of [FAMFAMFAM](http://www.famfamfam.com/). - -[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/serve-index/master.svg?label=windows -[appveyor-url]: https://ci.appveyor.com/project/dougwilson/serve-index -[ci-image]: https://badgen.net/github/checks/expressjs/serve-index/master?label=ci -[ci-url]: https://github.com/expressjs/serve-index/actions/workflows/ci.yml -[coveralls-image]: https://img.shields.io/coveralls/expressjs/serve-index/master.svg -[coveralls-url]: https://coveralls.io/r/expressjs/serve-index?branch=master -[downloads-image]: https://img.shields.io/npm/dm/serve-index.svg -[downloads-url]: https://npmjs.org/package/serve-index -[npm-image]: https://img.shields.io/npm/v/serve-index.svg -[npm-url]: https://npmjs.org/package/serve-index \ No newline at end of file diff --git a/_includes/readmes/serve-static.md b/_includes/readmes/serve-static.md deleted file mode 100644 index 56268f74cd..0000000000 --- a/_includes/readmes/serve-static.md +++ /dev/null @@ -1,256 +0,0 @@ -# serve-static - -[![NPM Version][npm-version-image]][npm-url] -[![NPM Downloads][npm-downloads-image]][npm-url] -[![Linux Build][github-actions-ci-image]][github-actions-ci-url] -[![Windows Build][appveyor-image]][appveyor-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -## Install - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install serve-static -``` - -## API - -```js -var serveStatic = require('serve-static') -``` - -### serveStatic(root, options) - -Create a new middleware function to serve files from within a given root -directory. The file to serve will be determined by combining `req.url` -with the provided root directory. When a file is not found, instead of -sending a 404 response, this module will instead call `next()` to move on -to the next middleware, allowing for stacking and fall-backs. - -#### Options - -##### acceptRanges - -Enable or disable accepting ranged requests, defaults to true. -Disabling this will not send `Accept-Ranges` and ignore the contents -of the `Range` request header. - -##### cacheControl - -Enable or disable setting `Cache-Control` response header, defaults to -true. Disabling this will ignore the `immutable` and `maxAge` options. - -##### dotfiles - -Set how "dotfiles" are treated when encountered. A dotfile is a file -or directory that begins with a dot ("."). Note this check is done on -the path itself without checking if the path actually exists on the -disk. If `root` is specified, only the dotfiles above the root are -checked (i.e. the root itself can be within a dotfile when set -to "deny"). - - - `'allow'` No special treatment for dotfiles. - - `'deny'` Deny a request for a dotfile and 403/`next()`. - - `'ignore'` Pretend like the dotfile does not exist and 404/`next()`. - -The default value is `'ignore'`. - -##### etag - -Enable or disable etag generation, defaults to true. - -##### extensions - -Set file extension fallbacks. When set, if a file is not found, the given -extensions will be added to the file name and search for. The first that -exists will be served. Example: `['html', 'htm']`. - -The default value is `false`. - -##### fallthrough - -Set the middleware to have client errors fall-through as just unhandled -requests, otherwise forward a client error. The difference is that client -errors like a bad request or a request to a non-existent file will cause -this middleware to simply `next()` to your next middleware when this value -is `true`. When this value is `false`, these errors (even 404s), will invoke -`next(err)`. - -Typically `true` is desired such that multiple physical directories can be -mapped to the same web address or for routes to fill in non-existent files. - -The value `false` can be used if this middleware is mounted at a path that -is designed to be strictly a single file system directory, which allows for -short-circuiting 404s for less overhead. This middleware will also reply to -all methods. - -The default value is `true`. - -##### immutable - -Enable or disable the `immutable` directive in the `Cache-Control` response -header, defaults to `false`. If set to `true`, the `maxAge` option should -also be specified to enable caching. The `immutable` directive will prevent -supported clients from making conditional requests during the life of the -`maxAge` option to check if the file has changed. - -##### index - -By default this module will send "index.html" files in response to a request -on a directory. To disable this set `false` or to supply a new index pass a -string or an array in preferred order. - -##### lastModified - -Enable or disable `Last-Modified` header, defaults to true. Uses the file -system's last modified value. - -##### maxAge - -Provide a max-age in milliseconds for http caching, defaults to 0. This -can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) -module. - -##### redirect - -Redirect to trailing "/" when the pathname is a dir. Defaults to `true`. - -##### setHeaders - -Function to set custom headers on response. Alterations to the headers need to -occur synchronously. The function is called as `fn(res, path, stat)`, where -the arguments are: - - - `res` the response object - - `path` the file path that is being sent - - `stat` the stat object of the file that is being sent - -## Examples - -### Serve files with vanilla node.js http server - -```js -var finalhandler = require('finalhandler') -var http = require('http') -var serveStatic = require('serve-static') - -// Serve up public/ftp folder -var serve = serveStatic('public/ftp', { index: ['index.html', 'index.htm'] }) - -// Create server -var server = http.createServer(function onRequest (req, res) { - serve(req, res, finalhandler(req, res)) -}) - -// Listen -server.listen(3000) -``` - -### Serve all files as downloads - -```js -var contentDisposition = require('content-disposition') -var finalhandler = require('finalhandler') -var http = require('http') -var serveStatic = require('serve-static') - -// Serve up public/ftp folder -var serve = serveStatic('public/ftp', { - index: false, - setHeaders: setHeaders -}) - -// Set header to force download -function setHeaders (res, path) { - res.setHeader('Content-Disposition', contentDisposition(path)) -} - -// Create server -var server = http.createServer(function onRequest (req, res) { - serve(req, res, finalhandler(req, res)) -}) - -// Listen -server.listen(3000) -``` - -### Serving using express - -#### Simple - -This is a simple example of using Express. - -```js -var express = require('express') -var serveStatic = require('serve-static') - -var app = express() - -app.use(serveStatic('public/ftp', { index: ['default.html', 'default.htm'] })) -app.listen(3000) -``` - -#### Multiple roots - -This example shows a simple way to search through multiple directories. -Files are searched for in `public-optimized/` first, then `public/` second -as a fallback. - -```js -var express = require('express') -var path = require('path') -var serveStatic = require('serve-static') - -var app = express() - -app.use(serveStatic(path.join(__dirname, 'public-optimized'))) -app.use(serveStatic(path.join(__dirname, 'public'))) -app.listen(3000) -``` - -#### Different settings for paths - -This example shows how to set a different max age depending on the served -file. In this example, HTML files are not cached, while everything else -is for 1 day. - -```js -var express = require('express') -var path = require('path') -var serveStatic = require('serve-static') - -var app = express() - -app.use(serveStatic(path.join(__dirname, 'public'), { - maxAge: '1d', - setHeaders: setCustomCacheControl -})) - -app.listen(3000) - -function setCustomCacheControl (res, file) { - if (path.extname(file) === '.html') { - // Custom Cache-Control for HTML files - res.setHeader('Cache-Control', 'public, max-age=0') - } -} -``` - -## License - -[MIT](LICENSE) - -[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/serve-static/master?label=windows -[appveyor-url]: https://ci.appveyor.com/project/dougwilson/serve-static -[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/serve-static/master -[coveralls-url]: https://coveralls.io/r/expressjs/serve-static?branch=master -[github-actions-ci-image]: https://badgen.net/github/checks/expressjs/serve-static/master?label=linux -[github-actions-ci-url]: https://github.com/expressjs/serve-static/actions/workflows/ci.yml -[node-image]: https://badgen.net/npm/node/serve-static -[node-url]: https://nodejs.org/en/download/ -[npm-downloads-image]: https://badgen.net/npm/dm/serve-static -[npm-url]: https://npmjs.org/package/serve-static -[npm-version-image]: https://badgen.net/npm/v/serve-static diff --git a/_includes/readmes/session.md b/_includes/readmes/session.md deleted file mode 100644 index 65a37e6364..0000000000 --- a/_includes/readmes/session.md +++ /dev/null @@ -1,1032 +0,0 @@ -# express-session - -[![NPM Version][npm-version-image]][npm-url] -[![NPM Downloads][npm-downloads-image]][node-url] -[![Build Status][ci-image]][ci-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -## Installation - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install express-session -``` - -## API - -```js -var session = require('express-session') -``` - -### session(options) - -Create a session middleware with the given `options`. - -**Note** Session data is _not_ saved in the cookie itself, just the session ID. -Session data is stored server-side. - -**Note** Since version 1.5.0, the [`cookie-parser` middleware](https://www.npmjs.com/package/cookie-parser) -no longer needs to be used for this module to work. This module now directly reads -and writes cookies on `req`/`res`. Using `cookie-parser` may result in issues -if the `secret` is not the same between this module and `cookie-parser`. - -**Warning** The default server-side session storage, `MemoryStore`, is _purposely_ -not designed for a production environment. It will leak memory under most -conditions, does not scale past a single process, and is meant for debugging and -developing. - -For a list of stores, see [compatible session stores](#compatible-session-stores). - -#### Options - -`express-session` accepts these properties in the options object. - -##### cookie - -Settings object for the session ID cookie. The default value is -`{ path: '/', httpOnly: true, secure: false, maxAge: null }`. - -The following are options that can be set in this object. - -##### cookie.domain - -Specifies the value for the `Domain` `Set-Cookie` attribute. By default, no domain -is set, and most clients will consider the cookie to apply to only the current -domain. - -##### cookie.expires - -Specifies the `Date` object to be the value for the `Expires` `Set-Cookie` attribute. -By default, no expiration is set, and most clients will consider this a -"non-persistent cookie" and will delete it on a condition like exiting a web browser -application. - -**Note** If both `expires` and `maxAge` are set in the options, then the last one -defined in the object is what is used. - -**Note** The `expires` option should not be set directly; instead only use the `maxAge` -option. - -##### cookie.httpOnly - -Specifies the `boolean` value for the `HttpOnly` `Set-Cookie` attribute. When truthy, -the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` -attribute is set. - -**Note** be careful when setting this to `true`, as compliant clients will not allow -client-side JavaScript to see the cookie in `document.cookie`. - -##### cookie.maxAge - -Specifies the `number` (in milliseconds) to use when calculating the `Expires` -`Set-Cookie` attribute. This is done by taking the current server time and adding -`maxAge` milliseconds to the value to calculate an `Expires` datetime. By default, -no maximum age is set. - -**Note** If both `expires` and `maxAge` are set in the options, then the last one -defined in the object is what is used. - -##### cookie.partitioned - -Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`](rfc-cutler-httpbis-partitioned-cookies) -attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not. -By default, the `Partitioned` attribute is not set. - -**Note** This is an attribute that has not yet been fully standardized, and may -change in the future. This also means many clients may ignore this attribute until -they understand it. - -More information about can be found in [the proposal](https://github.com/privacycg/CHIPS). - -##### cookie.path - -Specifies the value for the `Path` `Set-Cookie`. By default, this is set to `'/'`, which -is the root path of the domain. - -##### cookie.priority - -Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1]. - - - `'low'` will set the `Priority` attribute to `Low`. - - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set. - - `'high'` will set the `Priority` attribute to `High`. - -More information about the different priority levels can be found in -[the specification][rfc-west-cookie-priority-00-4.1]. - -**Note** This is an attribute that has not yet been fully standardized, and may change in the future. -This also means many clients may ignore this attribute until they understand it. - -##### cookie.sameSite - -Specifies the `boolean` or `string` to be the value for the `SameSite` `Set-Cookie` attribute. -By default, this is `false`. - - - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. - - `false` will not set the `SameSite` attribute. - - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. - - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie. - - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. - -More information about the different enforcement levels can be found in -[the specification][rfc-6265bis-03-4.1.2.7]. - -**Note** This is an attribute that has not yet been fully standardized, and may change in -the future. This also means many clients may ignore this attribute until they understand it. - -**Note** There is a [draft spec](https://tools.ietf.org/html/draft-west-cookie-incrementalism-01) -that requires that the `Secure` attribute be set to `true` when the `SameSite` attribute has been -set to `'none'`. Some web browsers or other clients may be adopting this specification. - -##### cookie.secure - -Specifies the `boolean` value for the `Secure` `Set-Cookie` attribute. When truthy, -the `Secure` attribute is set, otherwise it is not. By default, the `Secure` -attribute is not set. - -**Note** be careful when setting this to `true`, as compliant clients will not send -the cookie back to the server in the future if the browser does not have an HTTPS -connection. - -Please note that `secure: true` is a **recommended** option. However, it requires -an https-enabled website, i.e., HTTPS is necessary for secure cookies. If `secure` -is set, and you access your site over HTTP, the cookie will not be set. If you -have your node.js behind a proxy and are using `secure: true`, you need to set -"trust proxy" in express: - -```js -var app = express() -app.set('trust proxy', 1) // trust first proxy -app.use(session({ - secret: 'keyboard cat', - resave: false, - saveUninitialized: true, - cookie: { secure: true } -})) -``` - -For using secure cookies in production, but allowing for testing in development, -the following is an example of enabling this setup based on `NODE_ENV` in express: - -```js -var app = express() -var sess = { - secret: 'keyboard cat', - cookie: {} -} - -if (app.get('env') === 'production') { - app.set('trust proxy', 1) // trust first proxy - sess.cookie.secure = true // serve secure cookies -} - -app.use(session(sess)) -``` - -The `cookie.secure` option can also be set to the special value `'auto'` to have -this setting automatically match the determined security of the connection. Be -careful when using this setting if the site is available both as HTTP and HTTPS, -as once the cookie is set on HTTPS, it will no longer be visible over HTTP. This -is useful when the Express `"trust proxy"` setting is properly setup to simplify -development vs production configuration. - -##### genid - -Function to call to generate a new session ID. Provide a function that returns -a string that will be used as a session ID. The function is given `req` as the -first argument if you want to use some value attached to `req` when generating -the ID. - -The default value is a function which uses the `uid-safe` library to generate IDs. - -**NOTE** be careful to generate unique IDs so your sessions do not conflict. - -```js -app.use(session({ - genid: function(req) { - return genuuid() // use UUIDs for session IDs - }, - secret: 'keyboard cat' -})) -``` - -##### name - -The name of the session ID cookie to set in the response (and read from in the -request). - -The default value is `'connect.sid'`. - -**Note** if you have multiple apps running on the same hostname (this is just -the name, i.e. `localhost` or `127.0.0.1`; different schemes and ports do not -name a different hostname), then you need to separate the session cookies from -each other. The simplest method is to simply set different `name`s per app. - -##### proxy - -Trust the reverse proxy when setting secure cookies (via the "X-Forwarded-Proto" -header). - -The default value is `undefined`. - - - `true` The "X-Forwarded-Proto" header will be used. - - `false` All headers are ignored and the connection is considered secure only - if there is a direct TLS/SSL connection. - - `undefined` Uses the "trust proxy" setting from express - -##### resave - -Forces the session to be saved back to the session store, even if the session -was never modified during the request. Depending on your store this may be -necessary, but it can also create race conditions where a client makes two -parallel requests to your server and changes made to the session in one -request may get overwritten when the other request ends, even if it made no -changes (this behavior also depends on what store you're using). - -The default value is `true`, but using the default has been deprecated, -as the default will change in the future. Please research into this setting -and choose what is appropriate to your use-case. Typically, you'll want -`false`. - -How do I know if this is necessary for my store? The best way to know is to -check with your store if it implements the `touch` method. If it does, then -you can safely set `resave: false`. If it does not implement the `touch` -method and your store sets an expiration date on stored sessions, then you -likely need `resave: true`. - -##### rolling - -Force the session identifier cookie to be set on every response. The expiration -is reset to the original [`maxAge`](#cookiemaxage), resetting the expiration -countdown. - -The default value is `false`. - -With this enabled, the session identifier cookie will expire in -[`maxAge`](#cookiemaxage) since the last response was sent instead of in -[`maxAge`](#cookiemaxage) since the session was last modified by the server. - -This is typically used in conjuction with short, non-session-length -[`maxAge`](#cookiemaxage) values to provide a quick timeout of the session data -with reduced potential of it occurring during on going server interactions. - -**Note** When this option is set to `true` but the `saveUninitialized` option is -set to `false`, the cookie will not be set on a response with an uninitialized -session. This option only modifies the behavior when an existing session was -loaded for the request. - -##### saveUninitialized - -Forces a session that is "uninitialized" to be saved to the store. A session is -uninitialized when it is new but not modified. Choosing `false` is useful for -implementing login sessions, reducing server storage usage, or complying with -laws that require permission before setting a cookie. Choosing `false` will also -help with race conditions where a client makes multiple parallel requests -without a session. - -The default value is `true`, but using the default has been deprecated, as the -default will change in the future. Please research into this setting and -choose what is appropriate to your use-case. - -**Note** if you are using Session in conjunction with PassportJS, Passport -will add an empty Passport object to the session for use after a user is -authenticated, which will be treated as a modification to the session, causing -it to be saved. *This has been fixed in PassportJS 0.3.0* - -##### secret - -**Required option** - -This is the secret used to sign the session ID cookie. The secret can be any type -of value that is supported by Node.js `crypto.createHmac` (like a string or a -`Buffer`). This can be either a single secret, or an array of multiple secrets. If -an array of secrets is provided, only the first element will be used to sign the -session ID cookie, while all the elements will be considered when verifying the -signature in requests. The secret itself should be not easily parsed by a human and -would best be a random set of characters. A best practice may include: - - - The use of environment variables to store the secret, ensuring the secret itself - does not exist in your repository. - - Periodic updates of the secret, while ensuring the previous secret is in the - array. - -Using a secret that cannot be guessed will reduce the ability to hijack a session to -only guessing the session ID (as determined by the `genid` option). - -Changing the secret value will invalidate all existing sessions. In order to rotate -the secret without invalidating sessions, provide an array of secrets, with the new -secret as first element of the array, and including previous secrets as the later -elements. - -**Note** HMAC-256 is used to sign the session ID. For this reason, the secret should -contain at least 32 bytes of entropy. - -##### store - -The session store instance, defaults to a new `MemoryStore` instance. - -##### unset - -Control the result of unsetting `req.session` (through `delete`, setting to `null`, -etc.). - -The default value is `'keep'`. - - - `'destroy'` The session will be destroyed (deleted) when the response ends. - - `'keep'` The session in the store will be kept, but modifications made during - the request are ignored and not saved. - -### req.session - -To store or access session data, simply use the request property `req.session`, -which is (generally) serialized as JSON by the store, so nested objects -are typically fine. For example below is a user-specific view counter: - -```js -// Use the session middleware -app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) - -// Access the session as req.session -app.get('/', function(req, res, next) { - if (req.session.views) { - req.session.views++ - res.setHeader('Content-Type', 'text/html') - res.write('

views: ' + req.session.views + '

') - res.write('

expires in: ' + (req.session.cookie.maxAge / 1000) + 's

') - res.end() - } else { - req.session.views = 1 - res.end('welcome to the session demo. refresh!') - } -}) -``` - -#### Session.regenerate(callback) - -To regenerate the session simply invoke the method. Once complete, -a new SID and `Session` instance will be initialized at `req.session` -and the `callback` will be invoked. - -```js -req.session.regenerate(function(err) { - // will have a new session here -}) -``` - -#### Session.destroy(callback) - -Destroys the session and will unset the `req.session` property. -Once complete, the `callback` will be invoked. - -```js -req.session.destroy(function(err) { - // cannot access session here -}) -``` - -#### Session.reload(callback) - -Reloads the session data from the store and re-populates the -`req.session` object. Once complete, the `callback` will be invoked. - -```js -req.session.reload(function(err) { - // session updated -}) -``` - -#### Session.save(callback) - -Save the session back to the store, replacing the contents on the store with the -contents in memory (though a store may do something else--consult the store's -documentation for exact behavior). - -This method is automatically called at the end of the HTTP response if the -session data has been altered (though this behavior can be altered with various -options in the middleware constructor). Because of this, typically this method -does not need to be called. - -There are some cases where it is useful to call this method, for example, -redirects, long-lived requests or in WebSockets. - -```js -req.session.save(function(err) { - // session saved -}) -``` - -#### Session.touch() - -Updates the `.maxAge` property. Typically this is -not necessary to call, as the session middleware does this for you. - -### req.session.id - -Each session has a unique ID associated with it. This property is an -alias of [`req.sessionID`](#reqsessionid-1) and cannot be modified. -It has been added to make the session ID accessible from the `session` -object. - -### req.session.cookie - -Each session has a unique cookie object accompany it. This allows -you to alter the session cookie per visitor. For example we can -set `req.session.cookie.expires` to `false` to enable the cookie -to remain for only the duration of the user-agent. - -#### Cookie.maxAge - -Alternatively `req.session.cookie.maxAge` will return the time -remaining in milliseconds, which we may also re-assign a new value -to adjust the `.expires` property appropriately. The following -are essentially equivalent - -```js -var hour = 3600000 -req.session.cookie.expires = new Date(Date.now() + hour) -req.session.cookie.maxAge = hour -``` - -For example when `maxAge` is set to `60000` (one minute), and 30 seconds -has elapsed it will return `30000` until the current request has completed, -at which time `req.session.touch()` is called to reset -`req.session.cookie.maxAge` to its original value. - -```js -req.session.cookie.maxAge // => 30000 -``` - -#### Cookie.originalMaxAge - -The `req.session.cookie.originalMaxAge` property returns the original -`maxAge` (time-to-live), in milliseconds, of the session cookie. - -### req.sessionID - -To get the ID of the loaded session, access the request property -`req.sessionID`. This is simply a read-only value set when a session -is loaded/created. - -## Session Store Implementation - -Every session store _must_ be an `EventEmitter` and implement specific -methods. The following methods are the list of **required**, **recommended**, -and **optional**. - - * Required methods are ones that this module will always call on the store. - * Recommended methods are ones that this module will call on the store if - available. - * Optional methods are ones this module does not call at all, but helps - present uniform stores to users. - -For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. - -### store.all(callback) - -**Optional** - -This optional method is used to get all sessions in the store as an array. The -`callback` should be called as `callback(error, sessions)`. - -### store.destroy(sid, callback) - -**Required** - -This required method is used to destroy/delete a session from the store given -a session ID (`sid`). The `callback` should be called as `callback(error)` once -the session is destroyed. - -### store.clear(callback) - -**Optional** - -This optional method is used to delete all sessions from the store. The -`callback` should be called as `callback(error)` once the store is cleared. - -### store.length(callback) - -**Optional** - -This optional method is used to get the count of all sessions in the store. -The `callback` should be called as `callback(error, len)`. - -### store.get(sid, callback) - -**Required** - -This required method is used to get a session from the store given a session -ID (`sid`). The `callback` should be called as `callback(error, session)`. - -The `session` argument should be a session if found, otherwise `null` or -`undefined` if the session was not found (and there was no error). A special -case is made when `error.code === 'ENOENT'` to act like `callback(null, null)`. - -### store.set(sid, session, callback) - -**Required** - -This required method is used to upsert a session into the store given a -session ID (`sid`) and session (`session`) object. The callback should be -called as `callback(error)` once the session has been set in the store. - -### store.touch(sid, session, callback) - -**Recommended** - -This recommended method is used to "touch" a given session given a -session ID (`sid`) and session (`session`) object. The `callback` should be -called as `callback(error)` once the session has been touched. - -This is primarily used when the store will automatically delete idle sessions -and this method is used to signal to the store the given session is active, -potentially resetting the idle timer. - -## Compatible Session Stores - -The following modules implement a session store that is compatible with this -module. Please make a PR to add additional modules :) - -[![★][aerospike-session-store-image] aerospike-session-store][aerospike-session-store-url] A session store using [Aerospike](http://www.aerospike.com/). - -[aerospike-session-store-url]: https://www.npmjs.com/package/aerospike-session-store -[aerospike-session-store-image]: https://badgen.net/github/stars/aerospike/aerospike-session-store-expressjs?label=%E2%98%85 - -[![★][better-sqlite3-session-store-image] better-sqlite3-session-store][better-sqlite3-session-store-url] A session store based on [better-sqlite3](https://github.com/JoshuaWise/better-sqlite3). - -[better-sqlite3-session-store-url]: https://www.npmjs.com/package/better-sqlite3-session-store -[better-sqlite3-session-store-image]: https://badgen.net/github/stars/timdaub/better-sqlite3-session-store?label=%E2%98%85 - -[![★][cassandra-store-image] cassandra-store][cassandra-store-url] An Apache Cassandra-based session store. - -[cassandra-store-url]: https://www.npmjs.com/package/cassandra-store -[cassandra-store-image]: https://badgen.net/github/stars/webcc/cassandra-store?label=%E2%98%85 - -[![★][cluster-store-image] cluster-store][cluster-store-url] A wrapper for using in-process / embedded -stores - such as SQLite (via knex), leveldb, files, or memory - with node cluster (desirable for Raspberry Pi 2 -and other multi-core embedded devices). - -[cluster-store-url]: https://www.npmjs.com/package/cluster-store -[cluster-store-image]: https://badgen.net/github/stars/coolaj86/cluster-store?label=%E2%98%85 - -[![★][connect-arango-image] connect-arango][connect-arango-url] An ArangoDB-based session store. - -[connect-arango-url]: https://www.npmjs.com/package/connect-arango -[connect-arango-image]: https://badgen.net/github/stars/AlexanderArvidsson/connect-arango?label=%E2%98%85 - -[![★][connect-azuretables-image] connect-azuretables][connect-azuretables-url] An [Azure Table Storage](https://azure.microsoft.com/en-gb/services/storage/tables/)-based session store. - -[connect-azuretables-url]: https://www.npmjs.com/package/connect-azuretables -[connect-azuretables-image]: https://badgen.net/github/stars/mike-goodwin/connect-azuretables?label=%E2%98%85 - -[![★][connect-cloudant-store-image] connect-cloudant-store][connect-cloudant-store-url] An [IBM Cloudant](https://cloudant.com/)-based session store. - -[connect-cloudant-store-url]: https://www.npmjs.com/package/connect-cloudant-store -[connect-cloudant-store-image]: https://badgen.net/github/stars/adriantanasa/connect-cloudant-store?label=%E2%98%85 - -[![★][connect-cosmosdb-image] connect-cosmosdb][connect-cosmosdb-url] An Azure [Cosmos DB](https://azure.microsoft.com/en-us/products/cosmos-db/)-based session store. - -[connect-cosmosdb-url]: https://www.npmjs.com/package/connect-cosmosdb -[connect-cosmosdb-image]: https://badgen.net/github/stars/thekillingspree/connect-cosmosdb?label=%E2%98%85 - -[![★][connect-couchbase-image] connect-couchbase][connect-couchbase-url] A [couchbase](http://www.couchbase.com/)-based session store. - -[connect-couchbase-url]: https://www.npmjs.com/package/connect-couchbase -[connect-couchbase-image]: https://badgen.net/github/stars/christophermina/connect-couchbase?label=%E2%98%85 - -[![★][connect-datacache-image] connect-datacache][connect-datacache-url] An [IBM Bluemix Data Cache](http://www.ibm.com/cloud-computing/bluemix/)-based session store. - -[connect-datacache-url]: https://www.npmjs.com/package/connect-datacache -[connect-datacache-image]: https://badgen.net/github/stars/adriantanasa/connect-datacache?label=%E2%98%85 - -[![★][@google-cloud/connect-datastore-image] @google-cloud/connect-datastore][@google-cloud/connect-datastore-url] A [Google Cloud Datastore](https://cloud.google.com/datastore/docs/concepts/overview)-based session store. - -[@google-cloud/connect-datastore-url]: https://www.npmjs.com/package/@google-cloud/connect-datastore -[@google-cloud/connect-datastore-image]: https://badgen.net/github/stars/GoogleCloudPlatform/cloud-datastore-session-node?label=%E2%98%85 - -[![★][connect-db2-image] connect-db2][connect-db2-url] An IBM DB2-based session store built using [ibm_db](https://www.npmjs.com/package/ibm_db) module. - -[connect-db2-url]: https://www.npmjs.com/package/connect-db2 -[connect-db2-image]: https://badgen.net/github/stars/wallali/connect-db2?label=%E2%98%85 - -[![★][connect-dynamodb-image] connect-dynamodb][connect-dynamodb-url] A DynamoDB-based session store. - -[connect-dynamodb-url]: https://www.npmjs.com/package/connect-dynamodb -[connect-dynamodb-image]: https://badgen.net/github/stars/ca98am79/connect-dynamodb?label=%E2%98%85 - -[![★][@google-cloud/connect-firestore-image] @google-cloud/connect-firestore][@google-cloud/connect-firestore-url] A [Google Cloud Firestore](https://cloud.google.com/firestore/docs/overview)-based session store. - -[@google-cloud/connect-firestore-url]: https://www.npmjs.com/package/@google-cloud/connect-firestore -[@google-cloud/connect-firestore-image]: https://badgen.net/github/stars/googleapis/nodejs-firestore-session?label=%E2%98%85 - -[![★][connect-hazelcast-image] connect-hazelcast][connect-hazelcast-url] Hazelcast session store for Connect and Express. - -[connect-hazelcast-url]: https://www.npmjs.com/package/connect-hazelcast -[connect-hazelcast-image]: https://badgen.net/github/stars/huseyinbabal/connect-hazelcast?label=%E2%98%85 - -[![★][connect-loki-image] connect-loki][connect-loki-url] A Loki.js-based session store. - -[connect-loki-url]: https://www.npmjs.com/package/connect-loki -[connect-loki-image]: https://badgen.net/github/stars/Requarks/connect-loki?label=%E2%98%85 - -[![★][connect-lowdb-image] connect-lowdb][connect-lowdb-url] A lowdb-based session store. - -[connect-lowdb-url]: https://www.npmjs.com/package/connect-lowdb -[connect-lowdb-image]: https://badgen.net/github/stars/travishorn/connect-lowdb?label=%E2%98%85 - -[![★][connect-memcached-image] connect-memcached][connect-memcached-url] A memcached-based session store. - -[connect-memcached-url]: https://www.npmjs.com/package/connect-memcached -[connect-memcached-image]: https://badgen.net/github/stars/balor/connect-memcached?label=%E2%98%85 - -[![★][connect-memjs-image] connect-memjs][connect-memjs-url] A memcached-based session store using -[memjs](https://www.npmjs.com/package/memjs) as the memcached client. - -[connect-memjs-url]: https://www.npmjs.com/package/connect-memjs -[connect-memjs-image]: https://badgen.net/github/stars/liamdon/connect-memjs?label=%E2%98%85 - -[![★][connect-ml-image] connect-ml][connect-ml-url] A MarkLogic Server-based session store. - -[connect-ml-url]: https://www.npmjs.com/package/connect-ml -[connect-ml-image]: https://badgen.net/github/stars/bluetorch/connect-ml?label=%E2%98%85 - -[![★][connect-monetdb-image] connect-monetdb][connect-monetdb-url] A MonetDB-based session store. - -[connect-monetdb-url]: https://www.npmjs.com/package/connect-monetdb -[connect-monetdb-image]: https://badgen.net/github/stars/MonetDB/npm-connect-monetdb?label=%E2%98%85 - -[![★][connect-mongo-image] connect-mongo][connect-mongo-url] A MongoDB-based session store. - -[connect-mongo-url]: https://www.npmjs.com/package/connect-mongo -[connect-mongo-image]: https://badgen.net/github/stars/kcbanner/connect-mongo?label=%E2%98%85 - -[![★][connect-mongodb-session-image] connect-mongodb-session][connect-mongodb-session-url] Lightweight MongoDB-based session store built and maintained by MongoDB. - -[connect-mongodb-session-url]: https://www.npmjs.com/package/connect-mongodb-session -[connect-mongodb-session-image]: https://badgen.net/github/stars/mongodb-js/connect-mongodb-session?label=%E2%98%85 - -[![★][connect-mssql-v2-image] connect-mssql-v2][connect-mssql-v2-url] A Microsoft SQL Server-based session store based on [connect-mssql](https://www.npmjs.com/package/connect-mssql). - -[connect-mssql-v2-url]: https://www.npmjs.com/package/connect-mssql-v2 -[connect-mssql-v2-image]: https://badgen.net/github/stars/jluboff/connect-mssql-v2?label=%E2%98%85 - -[![★][connect-neo4j-image] connect-neo4j][connect-neo4j-url] A [Neo4j](https://neo4j.com)-based session store. - -[connect-neo4j-url]: https://www.npmjs.com/package/connect-neo4j -[connect-neo4j-image]: https://badgen.net/github/stars/MaxAndersson/connect-neo4j?label=%E2%98%85 - -[![★][connect-ottoman-image] connect-ottoman][connect-ottoman-url] A [couchbase ottoman](http://www.couchbase.com/)-based session store. - -[connect-ottoman-url]: https://www.npmjs.com/package/connect-ottoman -[connect-ottoman-image]: https://badgen.net/github/stars/noiissyboy/connect-ottoman?label=%E2%98%85 - -[![★][connect-pg-simple-image] connect-pg-simple][connect-pg-simple-url] A PostgreSQL-based session store. - -[connect-pg-simple-url]: https://www.npmjs.com/package/connect-pg-simple -[connect-pg-simple-image]: https://badgen.net/github/stars/voxpelli/node-connect-pg-simple?label=%E2%98%85 - -[![★][connect-redis-image] connect-redis][connect-redis-url] A Redis-based session store. - -[connect-redis-url]: https://www.npmjs.com/package/connect-redis -[connect-redis-image]: https://badgen.net/github/stars/tj/connect-redis?label=%E2%98%85 - -[![★][connect-session-firebase-image] connect-session-firebase][connect-session-firebase-url] A session store based on the [Firebase Realtime Database](https://firebase.google.com/docs/database/) - -[connect-session-firebase-url]: https://www.npmjs.com/package/connect-session-firebase -[connect-session-firebase-image]: https://badgen.net/github/stars/benweier/connect-session-firebase?label=%E2%98%85 - -[![★][connect-session-knex-image] connect-session-knex][connect-session-knex-url] A session store using -[Knex.js](http://knexjs.org/), which is a SQL query builder for PostgreSQL, MySQL, MariaDB, SQLite3, and Oracle. - -[connect-session-knex-url]: https://www.npmjs.com/package/connect-session-knex -[connect-session-knex-image]: https://badgen.net/github/stars/llambda/connect-session-knex?label=%E2%98%85 - -[![★][connect-session-sequelize-image] connect-session-sequelize][connect-session-sequelize-url] A session store using -[Sequelize.js](http://sequelizejs.com/), which is a Node.js / io.js ORM for PostgreSQL, MySQL, SQLite and MSSQL. - -[connect-session-sequelize-url]: https://www.npmjs.com/package/connect-session-sequelize -[connect-session-sequelize-image]: https://badgen.net/github/stars/mweibel/connect-session-sequelize?label=%E2%98%85 - -[![★][connect-sqlite3-image] connect-sqlite3][connect-sqlite3-url] A [SQLite3](https://github.com/mapbox/node-sqlite3) session store modeled after the TJ's `connect-redis` store. - -[connect-sqlite3-url]: https://www.npmjs.com/package/connect-sqlite3 -[connect-sqlite3-image]: https://badgen.net/github/stars/rawberg/connect-sqlite3?label=%E2%98%85 - -[![★][connect-typeorm-image] connect-typeorm][connect-typeorm-url] A [TypeORM](https://github.com/typeorm/typeorm)-based session store. - -[connect-typeorm-url]: https://www.npmjs.com/package/connect-typeorm -[connect-typeorm-image]: https://badgen.net/github/stars/makepost/connect-typeorm?label=%E2%98%85 - -[![★][couchdb-expression-image] couchdb-expression][couchdb-expression-url] A [CouchDB](https://couchdb.apache.org/)-based session store. - -[couchdb-expression-url]: https://www.npmjs.com/package/couchdb-expression -[couchdb-expression-image]: https://badgen.net/github/stars/tkshnwesper/couchdb-expression?label=%E2%98%85 - -[![★][dynamodb-store-image] dynamodb-store][dynamodb-store-url] A DynamoDB-based session store. - -[dynamodb-store-url]: https://www.npmjs.com/package/dynamodb-store -[dynamodb-store-image]: https://badgen.net/github/stars/rafaelrpinto/dynamodb-store?label=%E2%98%85 - -[![★][dynamodb-store-v3-image] dynamodb-store-v3][dynamodb-store-v3-url] Implementation of a session store using DynamoDB backed by the [AWS SDK for JavaScript v3](https://github.com/aws/aws-sdk-js-v3). - -[dynamodb-store-v3-url]: https://www.npmjs.com/package/dynamodb-store-v3 -[dynamodb-store-v3-image]: https://badgen.net/github/stars/FryDay/dynamodb-store-v3?label=%E2%98%85 - -[![★][express-etcd-image] express-etcd][express-etcd-url] An [etcd](https://github.com/stianeikeland/node-etcd) based session store. - -[express-etcd-url]: https://www.npmjs.com/package/express-etcd -[express-etcd-image]: https://badgen.net/github/stars/gildean/express-etcd?label=%E2%98%85 - -[![★][express-mysql-session-image] express-mysql-session][express-mysql-session-url] A session store using native -[MySQL](https://www.mysql.com/) via the [node-mysql](https://github.com/felixge/node-mysql) module. - -[express-mysql-session-url]: https://www.npmjs.com/package/express-mysql-session -[express-mysql-session-image]: https://badgen.net/github/stars/chill117/express-mysql-session?label=%E2%98%85 - -[![★][express-nedb-session-image] express-nedb-session][express-nedb-session-url] A NeDB-based session store. - -[express-nedb-session-url]: https://www.npmjs.com/package/express-nedb-session -[express-nedb-session-image]: https://badgen.net/github/stars/louischatriot/express-nedb-session?label=%E2%98%85 - -[![★][express-oracle-session-image] express-oracle-session][express-oracle-session-url] A session store using native -[oracle](https://www.oracle.com/) via the [node-oracledb](https://www.npmjs.com/package/oracledb) module. - -[express-oracle-session-url]: https://www.npmjs.com/package/express-oracle-session -[express-oracle-session-image]: https://badgen.net/github/stars/slumber86/express-oracle-session?label=%E2%98%85 - -[![★][express-session-cache-manager-image] express-session-cache-manager][express-session-cache-manager-url] -A store that implements [cache-manager](https://www.npmjs.com/package/cache-manager), which supports -a [variety of storage types](https://www.npmjs.com/package/cache-manager#store-engines). - -[express-session-cache-manager-url]: https://www.npmjs.com/package/express-session-cache-manager -[express-session-cache-manager-image]: https://badgen.net/github/stars/theogravity/express-session-cache-manager?label=%E2%98%85 - -[![★][express-session-etcd3-image] express-session-etcd3][express-session-etcd3-url] An [etcd3](https://github.com/mixer/etcd3) based session store. - -[express-session-etcd3-url]: https://www.npmjs.com/package/express-session-etcd3 -[express-session-etcd3-image]: https://badgen.net/github/stars/willgm/express-session-etcd3?label=%E2%98%85 - -[![★][express-session-level-image] express-session-level][express-session-level-url] A [LevelDB](https://github.com/Level/levelup) based session store. - -[express-session-level-url]: https://www.npmjs.com/package/express-session-level -[express-session-level-image]: https://badgen.net/github/stars/tgohn/express-session-level?label=%E2%98%85 - -[![★][express-session-rsdb-image] express-session-rsdb][express-session-rsdb-url] Session store based on Rocket-Store: A very simple, super fast and yet powerfull, flat file database. - -[express-session-rsdb-url]: https://www.npmjs.com/package/express-session-rsdb -[express-session-rsdb-image]: https://badgen.net/github/stars/paragi/express-session-rsdb?label=%E2%98%85 - -[![★][express-sessions-image] express-sessions][express-sessions-url] A session store supporting both MongoDB and Redis. - -[express-sessions-url]: https://www.npmjs.com/package/express-sessions -[express-sessions-image]: https://badgen.net/github/stars/konteck/express-sessions?label=%E2%98%85 - -[![★][firestore-store-image] firestore-store][firestore-store-url] A [Firestore](https://github.com/hendrysadrak/firestore-store)-based session store. - -[firestore-store-url]: https://www.npmjs.com/package/firestore-store -[firestore-store-image]: https://badgen.net/github/stars/hendrysadrak/firestore-store?label=%E2%98%85 - -[![★][fortune-session-image] fortune-session][fortune-session-url] A [Fortune.js](https://github.com/fortunejs/fortune) -based session store. Supports all backends supported by Fortune (MongoDB, Redis, Postgres, NeDB). - -[fortune-session-url]: https://www.npmjs.com/package/fortune-session -[fortune-session-image]: https://badgen.net/github/stars/aliceklipper/fortune-session?label=%E2%98%85 - -[![★][hazelcast-store-image] hazelcast-store][hazelcast-store-url] A Hazelcast-based session store built on the [Hazelcast Node Client](https://www.npmjs.com/package/hazelcast-client). - -[hazelcast-store-url]: https://www.npmjs.com/package/hazelcast-store -[hazelcast-store-image]: https://badgen.net/github/stars/jackspaniel/hazelcast-store?label=%E2%98%85 - -[![★][level-session-store-image] level-session-store][level-session-store-url] A LevelDB-based session store. - -[level-session-store-url]: https://www.npmjs.com/package/level-session-store -[level-session-store-image]: https://badgen.net/github/stars/toddself/level-session-store?label=%E2%98%85 - -[![★][lowdb-session-store-image] lowdb-session-store][lowdb-session-store-url] A [lowdb](https://www.npmjs.com/package/lowdb)-based session store. - -[lowdb-session-store-url]: https://www.npmjs.com/package/lowdb-session-store -[lowdb-session-store-image]: https://badgen.net/github/stars/fhellwig/lowdb-session-store?label=%E2%98%85 - -[![★][medea-session-store-image] medea-session-store][medea-session-store-url] A Medea-based session store. - -[medea-session-store-url]: https://www.npmjs.com/package/medea-session-store -[medea-session-store-image]: https://badgen.net/github/stars/BenjaminVadant/medea-session-store?label=%E2%98%85 - -[![★][memorystore-image] memorystore][memorystore-url] A memory session store made for production. - -[memorystore-url]: https://www.npmjs.com/package/memorystore -[memorystore-image]: https://badgen.net/github/stars/roccomuso/memorystore?label=%E2%98%85 - -[![★][mssql-session-store-image] mssql-session-store][mssql-session-store-url] A SQL Server-based session store. - -[mssql-session-store-url]: https://www.npmjs.com/package/mssql-session-store -[mssql-session-store-image]: https://badgen.net/github/stars/jwathen/mssql-session-store?label=%E2%98%85 - -[![★][nedb-session-store-image] nedb-session-store][nedb-session-store-url] An alternate NeDB-based (either in-memory or file-persisted) session store. - -[nedb-session-store-url]: https://www.npmjs.com/package/nedb-session-store -[nedb-session-store-image]: https://badgen.net/github/stars/JamesMGreene/nedb-session-store?label=%E2%98%85 - -[![★][@quixo3/prisma-session-store-image] @quixo3/prisma-session-store][@quixo3/prisma-session-store-url] A session store for the [Prisma Framework](https://www.prisma.io). - -[@quixo3/prisma-session-store-url]: https://www.npmjs.com/package/@quixo3/prisma-session-store -[@quixo3/prisma-session-store-image]: https://badgen.net/github/stars/kleydon/prisma-session-store?label=%E2%98%85 - -[![★][restsession-image] restsession][restsession-url] Store sessions utilizing a RESTful API - -[restsession-url]: https://www.npmjs.com/package/restsession -[restsession-image]: https://badgen.net/github/stars/jankal/restsession?label=%E2%98%85 - -[![★][sequelstore-connect-image] sequelstore-connect][sequelstore-connect-url] A session store using [Sequelize.js](http://sequelizejs.com/). - -[sequelstore-connect-url]: https://www.npmjs.com/package/sequelstore-connect -[sequelstore-connect-image]: https://badgen.net/github/stars/MattMcFarland/sequelstore-connect?label=%E2%98%85 - -[![★][session-file-store-image] session-file-store][session-file-store-url] A file system-based session store. - -[session-file-store-url]: https://www.npmjs.com/package/session-file-store -[session-file-store-image]: https://badgen.net/github/stars/valery-barysok/session-file-store?label=%E2%98%85 - -[![★][session-pouchdb-store-image] session-pouchdb-store][session-pouchdb-store-url] Session store for PouchDB / CouchDB. Accepts embedded, custom, or remote PouchDB instance and realtime synchronization. - -[session-pouchdb-store-url]: https://www.npmjs.com/package/session-pouchdb-store -[session-pouchdb-store-image]: https://badgen.net/github/stars/solzimer/session-pouchdb-store?label=%E2%98%85 - -[![★][@cyclic.sh/session-store-image] @cyclic.sh/session-store][@cyclic.sh/session-store-url] A DynamoDB-based session store for [Cyclic.sh](https://www.cyclic.sh/) apps. - -[@cyclic.sh/session-store-url]: https://www.npmjs.com/package/@cyclic.sh/session-store -[@cyclic.sh/session-store-image]: https://badgen.net/github/stars/cyclic-software/session-store?label=%E2%98%85 - -[![★][@databunker/session-store-image] @databunker/session-store][@databunker/session-store-url] A [Databunker](https://databunker.org/)-based encrypted session store. - -[@databunker/session-store-url]: https://www.npmjs.com/package/@databunker/session-store -[@databunker/session-store-image]: https://badgen.net/github/stars/securitybunker/databunker-session-store?label=%E2%98%85 - -[![★][sessionstore-image] sessionstore][sessionstore-url] A session store that works with various databases. - -[sessionstore-url]: https://www.npmjs.com/package/sessionstore -[sessionstore-image]: https://badgen.net/github/stars/adrai/sessionstore?label=%E2%98%85 - -[![★][tch-nedb-session-image] tch-nedb-session][tch-nedb-session-url] A file system session store based on NeDB. - -[tch-nedb-session-url]: https://www.npmjs.com/package/tch-nedb-session -[tch-nedb-session-image]: https://badgen.net/github/stars/tomaschyly/NeDBSession?label=%E2%98%85 - -## Examples - -### View counter - -A simple example using `express-session` to store page views for a user. - -```js -var express = require('express') -var parseurl = require('parseurl') -var session = require('express-session') - -var app = express() - -app.use(session({ - secret: 'keyboard cat', - resave: false, - saveUninitialized: true -})) - -app.use(function (req, res, next) { - if (!req.session.views) { - req.session.views = {} - } - - // get the url pathname - var pathname = parseurl(req).pathname - - // count the views - req.session.views[pathname] = (req.session.views[pathname] || 0) + 1 - - next() -}) - -app.get('/foo', function (req, res, next) { - res.send('you viewed this page ' + req.session.views['/foo'] + ' times') -}) - -app.get('/bar', function (req, res, next) { - res.send('you viewed this page ' + req.session.views['/bar'] + ' times') -}) - -app.listen(3000) -``` - -### User login - -A simple example using `express-session` to keep a user log in session. - -```js -var escapeHtml = require('escape-html') -var express = require('express') -var session = require('express-session') - -var app = express() - -app.use(session({ - secret: 'keyboard cat', - resave: false, - saveUninitialized: true -})) - -// middleware to test if authenticated -function isAuthenticated (req, res, next) { - if (req.session.user) next() - else next('route') -} - -app.get('/', isAuthenticated, function (req, res) { - // this is only called when there is an authentication user due to isAuthenticated - res.send('hello, ' + escapeHtml(req.session.user) + '!' + - ' Logout') -}) - -app.get('/', function (req, res) { - res.send('
' + - 'Username:
' + - 'Password:
' + - '
') -}) - -app.post('/login', express.urlencoded({ extended: false }), function (req, res) { - // login logic to validate req.body.user and req.body.pass - // would be implemented here. for this example any combo works - - // regenerate the session, which is good practice to help - // guard against forms of session fixation - req.session.regenerate(function (err) { - if (err) next(err) - - // store user information in session, typically a user id - req.session.user = req.body.user - - // save the session before redirection to ensure page - // load does not happen before session is saved - req.session.save(function (err) { - if (err) return next(err) - res.redirect('/') - }) - }) -}) - -app.get('/logout', function (req, res, next) { - // logout logic - - // clear the user from the session object and save. - // this will ensure that re-using the old session id - // does not have a logged in user - req.session.user = null - req.session.save(function (err) { - if (err) next(err) - - // regenerate the session, which is good practice to help - // guard against forms of session fixation - req.session.regenerate(function (err) { - if (err) next(err) - res.redirect('/') - }) - }) -}) - -app.listen(3000) -``` - -## Debugging - -This module uses the [debug](https://www.npmjs.com/package/debug) module -internally to log information about session operations. - -To see all the internal logs, set the `DEBUG` environment variable to -`express-session` when launching your app (`npm start`, in this example): - -```sh -$ DEBUG=express-session npm start -``` - -On Windows, use the corresponding command; - -```sh -> set DEBUG=express-session & npm start -``` - -## License - -[MIT](LICENSE) - -[rfc-6265bis-03-4.1.2.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7 -[rfc-cutler-httpbis-partitioned-cookies]: https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/ -[rfc-west-cookie-priority-00-4.1]: https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1 -[ci-image]: https://badgen.net/github/checks/expressjs/session/master?label=ci -[ci-url]: https://github.com/expressjs/session/actions?query=workflow%3Aci -[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/session/master -[coveralls-url]: https://coveralls.io/r/expressjs/session?branch=master -[node-url]: https://nodejs.org/en/download -[npm-downloads-image]: https://badgen.net/npm/dm/express-session -[npm-url]: https://npmjs.org/package/express-session -[npm-version-image]: https://badgen.net/npm/v/express-session diff --git a/_includes/readmes/timeout.md b/_includes/readmes/timeout.md deleted file mode 100644 index 69da8a6d33..0000000000 --- a/_includes/readmes/timeout.md +++ /dev/null @@ -1,168 +0,0 @@ -# connect-timeout - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] -[![Gratipay][gratipay-image]][gratipay-url] - -Times out a request in the Connect/Express application framework. - -## Install - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install connect-timeout -``` - -## API - -**NOTE** This module is not recommend as a "top-level" middleware (i.e. -`app.use(timeout('5s'))`) unless you take precautions to halt your own -middleware processing. See [as top-level middleware](#as-top-level-middleware) -for how to use as a top-level middleware. - -While the library will emit a 'timeout' event when requests exceed the given -timeout, node will continue processing the slow request until it terminates. -Slow requests will continue to use CPU and memory, even if you are returning -a HTTP response in the timeout callback. For better control over CPU/memory, -you may need to find the events that are taking a long time (3rd party HTTP -requests, disk I/O, database calls) and find a way to cancel them, and/or -close the attached sockets. - -### timeout(time, [options]) - -Returns middleware that times out in `time` milliseconds. `time` can also -be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) -module. On timeout, `req` will emit `"timeout"`. - -#### Options - -The `timeout` function takes an optional `options` object that may contain -any of the following keys: - -##### respond - -Controls if this module will "respond" in the form of forwarding an error. -If `true`, the timeout error is passed to `next()` so that you may customize -the response behavior. This error has a `.timeout` property as well as -`.status == 503`. This defaults to `true`. - -### req.clearTimeout() - -Clears the timeout on the request. The timeout is completely removed and -will not fire for this request in the future. - -### req.timedout - -`true` if timeout fired; `false` otherwise. - -## Examples - -### as top-level middleware - -Because of the way middleware processing works, once this module -passes the request to the next middleware (which it has to do in order -for you to do work), it can no longer stop the flow, so you must take -care to check if the request has timedout before you continue to act -on the request. - -```javascript -var bodyParser = require('body-parser') -var cookieParser = require('cookie-parser') -var express = require('express') -var timeout = require('connect-timeout') - -// example of using this top-level; note the use of haltOnTimedout -// after every middleware; it will stop the request flow on a timeout -var app = express() -app.use(timeout('5s')) -app.use(bodyParser()) -app.use(haltOnTimedout) -app.use(cookieParser()) -app.use(haltOnTimedout) - -// Add your routes here, etc. - -function haltOnTimedout (req, res, next) { - if (!req.timedout) next() -} - -app.listen(3000) -``` - -### express 3.x - -```javascript -var express = require('express') -var bodyParser = require('body-parser') -var timeout = require('connect-timeout') - -var app = express() -app.post('/save', timeout('5s'), bodyParser.json(), haltOnTimedout, function (req, res, next) { - savePost(req.body, function (err, id) { - if (err) return next(err) - if (req.timedout) return - res.send('saved as id ' + id) - }) -}) - -function haltOnTimedout (req, res, next) { - if (!req.timedout) next() -} - -function savePost (post, cb) { - setTimeout(function () { - cb(null, ((Math.random() * 40000) >>> 0)) - }, (Math.random() * 7000) >>> 0) -} - -app.listen(3000) -``` - -### connect - -```javascript -var bodyParser = require('body-parser') -var connect = require('connect') -var timeout = require('connect-timeout') - -var app = connect() -app.use('/save', timeout('5s'), bodyParser.json(), haltOnTimedout, function (req, res, next) { - savePost(req.body, function (err, id) { - if (err) return next(err) - if (req.timedout) return - res.send('saved as id ' + id) - }) -}) - -function haltOnTimedout (req, res, next) { - if (!req.timedout) next() -} - -function savePost (post, cb) { - setTimeout(function () { - cb(null, ((Math.random() * 40000) >>> 0)) - }, (Math.random() * 7000) >>> 0) -} - -app.listen(3000) -``` - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/connect-timeout.svg -[npm-url]: https://npmjs.org/package/connect-timeout -[travis-image]: https://img.shields.io/travis/expressjs/timeout/master.svg -[travis-url]: https://travis-ci.org/expressjs/timeout -[coveralls-image]: https://img.shields.io/coveralls/expressjs/timeout/master.svg -[coveralls-url]: https://coveralls.io/r/expressjs/timeout?branch=master -[downloads-image]: https://img.shields.io/npm/dm/connect-timeout.svg -[downloads-url]: https://npmjs.org/package/connect-timeout -[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg -[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/_includes/readmes/vhost.md b/_includes/readmes/vhost.md deleted file mode 100644 index 422e67f476..0000000000 --- a/_includes/readmes/vhost.md +++ /dev/null @@ -1,163 +0,0 @@ -# vhost - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Build Status][github-actions-ci-image]][github-actions-ci-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -## Install - -```sh -$ npm install vhost -``` - -## API - -```js -var vhost = require('vhost') -``` - -### vhost(hostname, handle) - -Create a new middleware function to hand off request to `handle` when the incoming -host for the request matches `hostname`. The function is called as -`handle(req, res, next)`, like a standard middleware. - -`hostname` can be a string or a RegExp object. When `hostname` is a string it can -contain `*` to match 1 or more characters in that section of the hostname. When -`hostname` is a RegExp, it will be forced to case-insensitive (since hostnames are) -and will be forced to match based on the start and end of the hostname. - -When host is matched and the request is sent down to a vhost handler, the `req.vhost` -property will be populated with an object. This object will have numeric properties -corresponding to each wildcard (or capture group if RegExp object provided) and the -`hostname` that was matched. - -```js -var connect = require('connect') -var vhost = require('vhost') -var app = connect() - -app.use(vhost('*.*.example.com', function handle (req, res, next) { - // for match of "foo.bar.example.com:8080" against "*.*.example.com": - console.dir(req.vhost.host) // => 'foo.bar.example.com:8080' - console.dir(req.vhost.hostname) // => 'foo.bar.example.com' - console.dir(req.vhost.length) // => 2 - console.dir(req.vhost[0]) // => 'foo' - console.dir(req.vhost[1]) // => 'bar' -})) -``` - -## Examples - -### using with connect for static serving - -```js -var connect = require('connect') -var serveStatic = require('serve-static') -var vhost = require('vhost') - -var mailapp = connect() - -// add middlewares to mailapp for mail.example.com - -// create app to serve static files on subdomain -var staticapp = connect() -staticapp.use(serveStatic('public')) - -// create main app -var app = connect() - -// add vhost routing to main app for mail -app.use(vhost('mail.example.com', mailapp)) - -// route static assets for "assets-*" subdomain to get -// around max host connections limit on browsers -app.use(vhost('assets-*.example.com', staticapp)) - -// add middlewares and main usage to app - -app.listen(3000) -``` - -### using with connect for user subdomains - -```js -var connect = require('connect') -var serveStatic = require('serve-static') -var vhost = require('vhost') - -var mainapp = connect() - -// add middlewares to mainapp for the main web site - -// create app that will server user content from public/{username}/ -var userapp = connect() - -userapp.use(function (req, res, next) { - var username = req.vhost[0] // username is the "*" - - // pretend request was for /{username}/* for file serving - req.originalUrl = req.url - req.url = '/' + username + req.url - - next() -}) -userapp.use(serveStatic('public')) - -// create main app -var app = connect() - -// add vhost routing for main app -app.use(vhost('userpages.local', mainapp)) -app.use(vhost('www.userpages.local', mainapp)) - -// listen on all subdomains for user pages -app.use(vhost('*.userpages.local', userapp)) - -app.listen(3000) -``` - -### using with any generic request handler - -```js -var connect = require('connect') -var http = require('http') -var vhost = require('vhost') - -// create main app -var app = connect() - -app.use(vhost('mail.example.com', function (req, res) { - // handle req + res belonging to mail.example.com - res.setHeader('Content-Type', 'text/plain') - res.end('hello from mail!') -})) - -// an external api server in any framework -var httpServer = http.createServer(function (req, res) { - res.setHeader('Content-Type', 'text/plain') - res.end('hello from the api!') -}) - -app.use(vhost('api.example.com', function (req, res) { - // handle req + res belonging to api.example.com - // pass the request to a standard Node.js HTTP server - httpServer.emit('request', req, res) -})) - -app.listen(3000) -``` - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/vhost.svg -[npm-url]: https://npmjs.org/package/vhost -[coveralls-image]: https://img.shields.io/coveralls/expressjs/vhost/master.svg -[coveralls-url]: https://coveralls.io/r/expressjs/vhost -[downloads-image]: https://img.shields.io/npm/dm/vhost.svg -[downloads-url]: https://npmjs.org/package/vhost -[github-actions-ci-image]: https://img.shields.io/github/actions/workflow/status/expressjs/vhost/ci.yml?branch=master&label=ci -[github-actions-ci-url]: https://github.com/expressjs/vhost/actions/workflows/ci.yml diff --git a/_includes/util-list.md b/_includes/util-list.md deleted file mode 100644 index e26620ddc4..0000000000 --- a/_includes/util-list.md +++ /dev/null @@ -1,42 +0,0 @@ -## Utility modules in jshttp - -- [negotiator](/{{page.lang}}/resources/utils/negotiator.html) -- [cookie](/{{page.lang}}/resources/utils/cookie.html) -- [fresh](/{{page.lang}}/resources/utils/fresh.html) -- [range-parser](/{{page.lang}}/resources/utils/range-parser.html) -- [methods](/{{page.lang}}/resources/utils/methods.html) -- [basic-auth](/{{page.lang}}/resources/utils/basic-auth.html) -- [compressible](/{{page.lang}}/resources/utils/compressible.html) -- [on-finished](/{{page.lang}}/resources/utils/on-finished.html) -- [http-assert](/{{page.lang}}/resources/utils/http-assert.html) -- [accepts](/{{page.lang}}/resources/utils/accepts.html) -- [type-is](/{{page.lang}}/resources/utils/type-is.html) -- [statuses](/{{page.lang}}/resources/utils/statuses.html) -- [mime-types](/{{page.lang}}/resources/utils/mime-types.html) -- [proxy-addr](/{{page.lang}}/resources/utils/proxy-addr.html) -- [on-headers](/{{page.lang}}/resources/utils/on-headers.html) -- [vary](/{{page.lang}}/resources/utils/vary.html) -- [media-typer](/{{page.lang}}/resources/utils/media-typer.html) -- [etag](/{{page.lang}}/resources/utils/etag.html) -- [mime-db](/{{page.lang}}/resources/utils/mime-db.html) -- [http-/{{page.lang}}/resources/utils](/{{page.lang}}/resources/utils/http-/{{page.lang}}/resources/utils.html) -- [spdy-push](/{{page.lang}}/resources/utils/spdy-push.html) -- [http-errors](/{{page.lang}}/resources/utils/http-errors.html) -- [content-disposition](/{{page.lang}}/resources/utils/content-disposition.html) -- [forwarded](/{{page.lang}}/resources/utils/forwarded.html) -- [content-type](/{{page.lang}}/resources/utils/content-type.html) - -## Utility modules in pillarjs - -- [cookies](/{{page.lang}}/resources/utils/cookies.html) -- [csrf](/{{page.lang}}/resources/utils/csrf.html) -- [finalhandler](/{{page.lang}}/resources/utils/finalhandler.html) -- [parseurl](/{{page.lang}}/resources/utils/parseurl.html) -- [path-match](/{{page.lang}}/resources/utils/path-match.html) -- [path-to-regexp](/{{page.lang}}/resources/utils/path-to-regexp.html) -- [resolve-path](/{{page.lang}}/resources/utils/resolve-path.html) -- [router](/{{page.lang}}/resources/utils/router.html) -- [routington](/{{page.lang}}/resources/utils/routington.html) -- [send](/{{page.lang}}/resources/utils/send.html) -- [ssl-redirect](/{{page.lang}}/resources/utils/ssl-redirect.html) -- [templation](/{{page.lang}}/resources/utils/templation.html) diff --git a/_layouts/3x-api.html b/_layouts/3x-api.html deleted file mode 100644 index 33a3e32d91..0000000000 --- a/_layouts/3x-api.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - {% include head.html %} - - - -
- - {% include header/header-{{ page.lang }}.html %} - - {% include api/en/3x/menu.md %} - -
- - {{ content }} - -
- - {% include footer/footer-{{ page.lang }}.html %} - - - - - diff --git a/_layouts/404.html b/_layouts/404.html deleted file mode 100644 index 338facdd1f..0000000000 --- a/_layouts/404.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - {% include head.html %} - - {% if page.lang == 'en' %} - - {% else %} - - {% endif %} - {% include header/header-{{ page.lang }}.html %} -
-
- {{ content }} -
- {% include footer/footer-{{ page.lang }}.html %} - - \ No newline at end of file diff --git a/_layouts/4x-api.html b/_layouts/4x-api.html deleted file mode 100644 index 845cc61e0d..0000000000 --- a/_layouts/4x-api.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - {% include head.html %} - - - -
- - {% include header/header-{{ page.lang }}.html %} - - {% include api/en/4x/menu.md %} - -
- - {{ content }} - -
- - {% include footer/footer-{{ page.lang }}.html %} - - - - diff --git a/_layouts/5x-api.html b/_layouts/5x-api.html deleted file mode 100644 index 7e1f2d236a..0000000000 --- a/_layouts/5x-api.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - {% include head.html %} - - - -
- - {% include header/header-{{ page.lang }}.html %} - - {% include api/en/5x/menu.md %} - -
- - {{ content }} - -
- - {% include footer/footer-{{ page.lang }}.html %} - - - - diff --git a/_layouts/home.html b/_layouts/home.html deleted file mode 100644 index 3cbb367410..0000000000 --- a/_layouts/home.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - {% include head.html %} - - {% if page.lang == 'en' %} - - {% else %} - -
- {% include i18n-notice.html %} -
- {% endif %} - -
- {{ content }} -
- - {% include footer/footer-{{ page.lang }}.html %} - - - diff --git a/_layouts/middleware.html b/_layouts/middleware.html deleted file mode 100644 index efcf8e8d63..0000000000 --- a/_layouts/middleware.html +++ /dev/null @@ -1,33 +0,0 @@ ---- -layout: page ---- -
-
- {% if page.title contains 'middleware' %} - {% capture readme %}{% include mw-list.md %}{% endcapture %} - {% else %} - {% capture readme %}{% include util-list.md %}{% endcapture %} - {% endif %} - {{ readme | markdownify }} -
-
- {% if page.module == 'mw-home' %} - {{content}} - - {% elsif page.module %} - {% capture note-middleware %} - This page was generated from the {{page.module}} README. - {% endcapture %} - - {% include admonitions/note.html content=note-middleware %} - - {% capture included-readme %}{% include readmes/{{page.module}}.md %}{% endcapture %} - - {{ included-readme | markdownify }} - - {% else %} -

ERROR: No source specified for README {{page.module}}

- {% endif %} - -
-
diff --git a/_layouts/page.html b/_layouts/page.html deleted file mode 100644 index aeb4e2eb01..0000000000 --- a/_layouts/page.html +++ /dev/null @@ -1,34 +0,0 @@ - -{% if page.lang %} - - - {% include head.html %} - - {% if page.lang == 'en' %} - - {% else %} - - {% endif %} - -
- - {% include header/header-{{ page.lang }}.html %} - -
- - {% if page.lang != 'en' %} -
- {% include i18n-notice.html %} -
- {% endif %} -
-{{ content }} -
-
- - {% include footer/footer-{{ page.lang }}.html %} - - - - -{% endif %} diff --git a/_layouts/post.html b/_layouts/post.html deleted file mode 100644 index 2c7e463eb7..0000000000 --- a/_layouts/post.html +++ /dev/null @@ -1,35 +0,0 @@ - - - {% include head.html %} - - - -
- - {% include header/header-{{ page.lang }}.html %} - - {% include blog/posts-menu.md %} - -
-
- {% if page.title %} -

{{page.title}}

- {% endif %} - {% if page.sub_title %} -

{{page.sub_title}}

- {% endif %} -
- {% if page.author %} -
By {{page.author}}
- {% endif %} -
{{page.date| date: "%d %b %Y" }}
-
- {{ content }} -
-
- - {% include footer/footer-{{ page.lang }}.html %} - - - - diff --git a/_posts/2024-07-16-welcome-post.md b/_posts/2024-07-16-welcome-post.md deleted file mode 100644 index bbbb66d576..0000000000 --- a/_posts/2024-07-16-welcome-post.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Welcome to The Express Blog! -description: Introducing the new Express blog — a primary platform for announcements, updates, and communication from the Express technical committee. -tags: site-admin -author: Rand McKinney and Chris Del ---- - -Welcome to the new Express blog! The blog is meant to be a primary means of communication for the Express technical committee (TC). While we currently have other channels such as X, LinkedIn, and of course GitHub, there's no authoritative "soapbox" for announcements and general communication. - -Initially, the Express blog will be a venue: -- For periodic announcements of new releases, pre-releases, plans, and ongoing work on the project. -- For the Express TC to discuss issues of particular importance to the Express community. -- To highlight security issues or other urgent information. - -Eventually, we hope the blog will evolve into a more general communication hub for the entire Express community; for example to share examples, tips, and experiences with the Express ecosystem and other information that's not simply technical documentation or GitHub discussion. - -Initially, posts will be written by TC members (potentially collaborating others), mainly because we don't have bandwidth to review general posts from the broader community. Eventually, we would love to open up the blog for broader contributions, but for now the focus is on trying to release Express 5.0, and the reality of an open-source project is that everyone has finite time to contribute. - -Express TC member [Ulises Gascón](https://github.com/UlisesGascon) suggested a number of interesting topics for blog posts in [expressjs.com issue 1500](https://github.com/expressjs/expressjs.com/issues/1500), but there are undoubtedly many others. - -If you have an idea for a post, feel free to pitch the idea! You can add a comment to [expressjs.com issue 1500](https://github.com/expressjs/expressjs.com/issues/1500) or open a new issue, and then after appropriate discussion, open a PR. We've also written up simple [instructions to create a blog post](/en/blog/write-post.html). - -Happy blogging! diff --git a/_posts/2024-09-29-security-releases.md b/_posts/2024-09-29-security-releases.md deleted file mode 100644 index e8f2378db5..0000000000 --- a/_posts/2024-09-29-security-releases.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: September 2024 Security Releases -description: Security releases for Express, body-parser, send, serve-static, and path-to-regexp have been published. We recommend that all users upgrade as soon as possible. -tags: security, vulnerabilities -author: Ulises Gascón ---- - -Recently, the Express team has been made aware of a number of security vulnerabilities in the Express project. We have released a number of patches to address these vulnerabilities. - -{% include admonitions/warning.html -content="We strongly recommend that you upgrade these modules to the recommended (or latest) version as soon as possible." -%} - -The following vulnerabilities have been addressed: - -- [High severity vulnerability CVE-2024-45590 in body-parser middleware](#high-severity-vulnerability-cve-2024-45590-in-body-parser-middleware) -- [High severity vulnerability CVE-2024-47178 in basic-auth-connect middleware](#high-severity-vulnerability-cve-2024-47178-in-basic-auth-connect-middleware) -- [Moderate severity vulnerability CVE-2024-43796 in Express core](#moderate-severity-vulnerability-cve-2024-43796-in-express-core) -- [Moderate severity vulnerability CVE-2024-43799 in send utility module](#moderate-severity-vulnerability-cve-2024-43799-in-send-utility-module) -- [Moderate severity vulnerability CVE-2024-43800 in serve-static middleware](#moderate-severity-vulnerability-cve-2024-43800-in-serve-static-middleware) -- [Moderate severity vulnerability CVE-2024-45296 in path-to-regexp utility module](#moderate-severity-vulnerability-cve-2024-45296-in-path-to-regexp-utility-module) - -## High severity vulnerability CVE-2024-45590 in body-parser middleware - -**[body-parser](https://www.npmjs.com/package/body-parser) version `<1.20.3` is vulnerable to denial of service when URL-encoding is enabled** - -A malicious actor using a specially-crafted payload could flood the server with a large number of requests, resulting in denial of service. - -**Affected versions**: `<1.20.3` - -**Patched versions**: `>=1.20.3` - -This vulnerability was discovered during the [OSTIF audit to Express](https://github.com/expressjs/security-wg/issues/6) and was mitigated by [the Express security triage team](https://github.com/expressjs/security-wg?tab=readme-ov-file#security-triage-team). - -For more details, see [GHSA-qwcr-r2fm-qrc7](https://github.com/expressjs/body-parser/security/advisories/GHSA-qwcr-r2fm-qrc7). - -## High severity vulnerability CVE-2024-47178 in basic-auth-connect middleware - -**[basic-auth-connect](https://www.npmjs.com/package/basic-auth-connect) uses a timing-unsafe equality comparison** - -basic-auth-connect `<1.1.0` uses a timing-unsafe equality comparison that can leak timing information - -**Affected versions** -- `<1.1.0` - -**Patched versions** -- `>=1.1.0` - -This vulnerability was discovered during the [OSTIF audit to Express](https://github.com/expressjs/security-wg/issues/6) and was mitigated by [the Express Securty triage team](https://github.com/expressjs/security-wg?tab=readme-ov-file#security-triage-team). - -More details area available in [GHSA-7p89-p6hx-q4fw](https://github.com/expressjs/basic-auth-connect/security/advisories/GHSA-7p89-p6hx-q4fw) - - - -## Moderate severity vulnerability CVE-2024-43796 in Express core - -The core **[express](https://www.npmjs.com/package/express) package is vulnerable to cross-site scripting (XSS) attack via `response.redirect()`**. - -In Express version <4.20.0, passing untrusted user input—even after sanitizing it—to `response.redirect()` may execute untrusted code. - -**Affected versions**: -- `<4.20.0` -- `>=5.0.0-alpha.1`, `<5.0.0` - -**Patched versions**: -- `>=4.20.0` -- `>=5.0.0` - -This vulnerability was discovered during the [OSTIF audit of Express](https://github.com/expressjs/security-wg/issues/6) and was mitigated by [the Express security triage team](https://github.com/expressjs/security-wg?tab=readme-ov-file#security-triage-team). - -For more details, see [GHSA-qw6h-vgh9-j6wx](https://github.com/expressjs/express/security/advisories/GHSA-qw6h-vgh9-j6wx). - - -## Moderate severity vulnerability CVE-2024-43799 in send utility module - -The **[send](https://www.npmjs.com/package/send) utility module is vulnerable to template injection that can lead to vulnerability to cross-site scripting (XSS) attack**. - -Passing untrusted user input—even after sanitizing it—to `SendStream.redirect()` can execute untrusted code. - -**Affected versions**: `< 0.19.0` - -**Patched versions**: `>=0.19.0` - -This vulnerability was discovered during the [OSTIF audit of Express](https://github.com/expressjs/security-wg/issues/6) and was mitigated by [the Express security triage team](https://github.com/expressjs/security-wg?tab=readme-ov-file#security-triage-team). - -For more details, see [GHSA-m6fv-jmcg-4jfg](https://github.com/pillarjs/send/security/advisories/GHSA-m6fv-jmcg-4jfg). - - -## Moderate severity vulnerability CVE-2024-43800 in serve-static middleware - -The **[serve-static](https://www.npmjs.com/package/serve-static) middleware module is vulnerable to template injection that can lead to vulnerability to cross-site scripting (XSS) attack**. - -Passing untrusted user input—even after sanitizing it—to `redirect()` can execute untrusted code. - -**Affected versions**: -- `< 1.16.0` -- `>=2.0.0`, `<2.1.0` - -**Patched versions**: -- `>=1.16.0` -- `>=2.1.0` - -This vulnerability was discovered during the [OSTIF audit of Express](https://github.com/expressjs/security-wg/issues/6) and was mitigated by [the Express security triage team](https://github.com/expressjs/security-wg?tab=readme-ov-file#security-triage-team). - -For more details, see [GHSA-cm22-4g7w-348p](https://github.com/expressjs/serve-static/security/advisories/GHSA-cm22-4g7w-348p) - - -## Moderate severity vulnerability CVE-2024-45296 in path-to-regexp utility module - -The **[path-to-regexp](https://www.npmjs.com/package/path-to-regexp) utility module is vulnerable to regular expression denial of service (ReDoS) attack**. - -A bad regular expression is generated any time you have two parameters within a single segment, separated by something that is not a period (`.`). For example, `/:a-:b`. - -Using `/:a-:b` will produce the regular expression `/^\/([^\/]+?)-([^\/]+?)\/?$/`. This can be exploited by a path such as `/a${'-a'.repeat(8_000)}/a`. [OWASP](https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS) has a good example of why this occurs, but in essence, the `/a` at the end ensures this route would never match, but due to naive backtracking it will still attempt every combination of the `:a-:b` on the repeated 8,000 `-a`. - -Because JavaScript is single-threaded and regex matching runs on the main thread, poor performance will block the event loop and can lead to a DoS. In local benchmarks, exploiting the unsafe regex will result in performance that is over 1000x worse than the safe regex. In a more realistic environment, using Express v4 and ten concurrent connections results in an average latency of ~600ms vs 1ms. - -**Affected versions**: -- `>=4.0.0`, `<8.0.0` -- `>=0.2.0`, `<1.9.0` -- `<0.1.10` -- `>=2.0.0`, `<3.3.0` -- `>=4.0.0`, `<6.3.0` - -**Patched versions**: -- `>=8.0.0` -- `>=1.9.0` -- `>=0.1.10` -- `>=3.3.0` -- `>=6.3.0` - -Thanks to [Blake Embrey](https://github.com/blakeembrey) who reported and created the security patch. - -For more details, see [GHSA-9wv6-86v2-598j](https://github.com/pillarjs/path-to-regexp/security/advisories/GHSA-9wv6-86v2-598j) - diff --git a/_posts/2024-10-01-HeroDevs-partnership-announcement.md b/_posts/2024-10-01-HeroDevs-partnership-announcement.md deleted file mode 100644 index 7b69a4bbf0..0000000000 --- a/_posts/2024-10-01-HeroDevs-partnership-announcement.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: Express Never Ending Support Launched by HeroDevs and Express.js -description: The Express.js team is pleased to announce a partnership with HeroDevs to launch Express Never-Ending Support (NES), providing long-term support for applications built with legacy Express. This collaboration ensures that developers relying on older versions of the framework will continue to receive critical security and compatibility updates, allowing them to maintain and scale their applications securely, even after the framework's official end-of-life. -tags: partnerships, announcements -author: Express Technical Committee ---- - -The Express.js team is pleased to announce a partnership with HeroDevs to launch [Express Never-Ending Support (NES)](https://www.herodevs.com/support/express-nes), providing long-term support for applications built with legacy Express. This collaboration ensures that developers relying on older versions of the framework will continue to receive critical security and compatibility updates, allowing them to maintain and scale their applications securely, even after the framework's official end-of-life. - -Express.js is known for its minimalistic design and flexibility, offering developers a powerful yet lightweight framework for building web and mobile applications. Its extensive set of HTTP utility methods and middleware have made creating APIs both efficient and scalable—qualities that have made it a go-to choice for Node.js developers over the years. - -However, Express.js v3.x reached its end-of-life in July 2015, leaving many businesses and developers in need of support to keep their applications secure and compliant. - -> "We’re grateful to see HeroDevs stepping in to provide extended long-term support for Express -> -> Express NES ensures that the many businesses and developers who rely on Express can continue using it safely and securely, even years after its original end-of-life. This kind of ongoing commitment to the open-source ecosystem is crucial, and we’re excited to see the benefits it brings to the developer community.” — said a spokesperson for the Express Technical Committee. - -Express NES is designed as a drop-in replacement for legacy versions of Express.js, offering security patches, compatibility updates and compliance fixes. This solution ensures that developers can remain on legacy Express.js without becoming vulnerable to security risks and compliance issues. - -> “We’re thrilled to introduce Express NES as part of our continued mission to support the sustainability of key open-source tools -> -> Our partnership with OpenJS has enabled us to meet the needs of developers still relying on older versions of critical frameworks. Express NES ensures that they can continue building and maintaining their applications without the risk of security vulnerabilities or loss of compliance.” — Joe Eames, VP of Partnership at HeroDevs. - -For more information on Express NES and how to get started, visit [HeroDevs’ website](https://www.herodevs.com/support/express-nes). \ No newline at end of file diff --git a/_posts/2024-10-15-v5-release.md b/_posts/2024-10-15-v5-release.md deleted file mode 100644 index ebb9fcca8a..0000000000 --- a/_posts/2024-10-15-v5-release.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: "Introducing Express v5: A New Era for the Node.js Framework" -tags: releases -author: Wes Todd and the Express Technical Committee -description: Announcing the release of Express version 5 ---- - -Ten years ago (July 2014) the [Express v5 release pull request](https://github.com/expressjs/express/pull/2237) was opened, and now at long last it's been merged and published! - -We want to recognize the work of all our contributors, especially [Doug Wilson](https://github.com/dougwilson), who spent the last ten years ensuring Express was the most stable project around. Without his contributions and those of many others, this release could not have happened. - -Eight months ago we went public with a plan to move [Express forward](https://github.com/expressjs/discussions/issues/160). This plan included re-committing to the governance outlined years ago and adding more contributors to help kickstart progress. Many people may not realize that robust project governance is critical to the health of a large open-source project. We want to thank the [OpenJS Foundation Cross Project -Council](https://github.com/openjs-foundation/cross-project-council/) and its members for helping us put together this plan. - -## So what about v5? - -This release is designed to be boring! -That may sound odd, but we've intentionally kept it simple to unblock the ecosystem and enable more impactful changes in future releases. This is also about signaling to the Node.js ecosystem that Express is moving again. -The focus of this release is on dropping old Node.js version support, addressing security concerns, and simplifying maintenance. - -Before going into the changes in this release, let's address why it was released v5 on the `next` dist-tag. As part of reviving the project, we started a [Security working group](https://github.com/expressjs/security-wg) and [security triage team](https://github.com/expressjs/security-wg?tab=readme-ov-file#security-triage-team) to address the growing needs around open source supply chain security. We undertook a security audit (more details to come on that) and uncovered some problems that needed to be addressed. Thus, in addition to the "normal" work done in public issues, we also did a lot of security work in private forks. -This security work required orchestration when releasing, to ensure the code and CVE reports went out together. You can find a summary of the most recent vulnerabilities patched in [our security release notes](https://expressjs.com/2024/09/29/security-releases.html). - -While we weren't able to simultaneously release v5, this blog post, the changelog, and documentation, we felt it was most important to have a secure and stable release. - -As soon as possible, we'll provide more details on our long-term support (LTS) plans, including when the release will move from `next` to `latest`. For now, if you are uncomfortable being on the bleeding edge (even if it is a rather dull edge) then you should wait to upgrade until the release is tagged `latest`. That said, we look forward to working with you to address any bugs you encounter as you upgrade. - -## Breaking changes - -The v5 release has the minimum possible number of breaking changes, listed here in order of impact to applications. - -- [Ending support for old Node.js versions](#ending-support-for-old-nodejs-versions) -- [Changes to path matching and regular expressions](#changes-to-path-matching-and-regular-expressions) -- [Promise support](#promise-support) -- [Body parser changes](#body-parser-changes) -- [Removing deprecated method signatures](#removing-deprecated-method-signatures) - -There are also a number of subtle changes: for details, see [Migrating to Express 5]({{site.url}}/{{page.lang}}/guide/migrating-5). - -### Ending support for old Node.js versions - -Goodbye Node.js 0.10, hello Node 18 and up! - -This release drops support for Node.js versions before v18. This is an important change because supporting old Node.js versions has been holding back many critical performance and maintainability changes. This change also enables more stable and maintainable continuous integration (CI), adopting new language and runtime features, and dropping dependencies that are no longer required. - -We recognize that this might cause difficulty for some enterprises with older or "parked" applications, and because of this we are working on a [partnership with HeroDevs](https://expressjs.com/2024/10/01/HeroDevs-partnership-announcement.html) to offer "never-ending support" that will include critical security patches even after v4 enters end-of-life (more on these plans soon). That said, we strongly suggest that you update to modern Node.js versions as soon as possible. - -### Changes to path matching and regular expressions - -The v5 releases updates to `path-to-regexp@8.x` from `path-to-regexp@0.x`, which incorporates many years of changes. If you were using any of the 5.0.0-beta releases, a last-minute update which greatly changed the path semantics to [remove the possibility of any ReDoS attacks](https://blakeembrey.com/posts/2024-09-web-redos/). For more detailed changes, [see the `path-to-regexp` readme](https://github.com/pillarjs/path-to-regexp?tab=readme-ov-file#express--4x). - -#### No more regex - -This release no longer supports "sub-expression" regular expressions, for example `/:foo(\\d+)`. -This is a commonly-used pattern, but we removed it for security reasons. Unfortunately, it's easy to write a regular expression that has exponential time behavior when parsing input: The dreaded regular expression denial of service (ReDoS) attack. It's very difficult to prevent this, but as a library that converts strings to regular expressions, we are on the hook for such security aspects. - -*How to migrate:* The best approach to prevent ReDoS attacks is to use a robust input validation library. [There are many on `npm`](https://www.npmjs.com/search?q=validate%20express) depending on your needs. TC member Wes Todd maintains [a middleware-based "code first" OpenAPI library](https://www.npmjs.com/package/@wesleytodd/openapi) for this kind of thing. - -#### Splats, optional, and captures oh my - -This release includes simplified patterns for common route patterns. With the removal of regular expression semantics comes other small but impactful changes to how you write your routes. - -1. `:name?` becomes `{:name}`. Usage of `{}` for optional parts of your route means you can now do things like `/base{/:optional}/:required` and what parts are actually optional is much more explicit. -2. `*` becomes `*name`. -3. New reserved characters: `(`, `)`, `[`, `]`, `?`, `+`, & `!`. These have been reserved to leave room for future improvements and to prevent mistakes when migrating where those characters mean specific things in previous versions. - -#### Name everything - -This release no longer supports ordered numerical parameters. - -In Express v4, you could get numerical parameters using regex capture groups (for example, `/user(s?)` => `req.params[0] === 's'`). Now all parameters must be named. Along with requiring a name, Express now supports all valid JavaScript identifiers or quoted (for example, `/:"this"`). - -### Promise support - -This one may be a bit contentious, but we "promise" we're moving in the right direction. We added support for returned *rejected* promises from errors raised in middleware. This *does not include* calling `next` from returned *resolved* promises. There are a lot of edge cases in old Express apps that have expectations of `Promise` behavior, and before we can run we need to walk. For most folks, this means you can now write middleware like the following: - -```javascript -app.use(async (req, res, next) => { - req.locals.user = await getUser(req); - next(); -}); -``` - -Notice that this example uses `async/await` and the `getUser` call may throw an error (if, for example, the user doesn't exist, the user database is down, and so on), but we still call `next` if it is successful. We don't need to catch the error in line anymore if we want to rely on error-handling middleware instead because the router will now catch the rejected promise and treat that as calling `next(err)`. - -NOTE: Best practice is to handle errors as close to the site as possible. So while this is now handled in the router, it's best to catch the error in the middleware and handle it without relying on separate error-handling middleware. - -### Body parser changes - -There are a number of `body-parser` changes: - -- Add option to customize the urlencoded body depth with a default value of 32 as mitigation for [CVE-2024-45590](https://nvd.nist.gov/vuln/detail/CVE-2024-45590) ([technical details](https://github.com/expressjs/body-parser/commit/b2695c4450f06ba3b0ccf48d872a229bb41c9bce)) -- Remove deprecated `bodyParser()` combination middleware -- `req.body` is no longer always initialized to `{}` -- `urlencoded` parser now defaults `extended` to false -- Added support for Brotli lossless data compression - -### Removing deprecated method signatures - -Express v5 removes a number of deprecated method signatures, many of which were carried over from v3. Below are the changes you need to make: - -- `res.redirect('back')` and `res.location('back')`: The magic string `'back'` is no longer supported. Use `req.get('Referrer') || '/'` explicitly instead. -- `res.send(status, body)` and `res.send(body, status)` signatures: Use `res.status(status).send(body)`. -- `res.send(status)` signature: Use `res.sendStatus(status)` for simple status responses, or `res.status(status).send()` for sending a status code with an optional body. -- `res.redirect(url, status)` signature: Use `res.redirect(status, url)`. -- `res.json(status, obj)` and `res.json(obj, status)` signatures: Use `res.status(status).json(obj)`. -- `res.jsonp(status, obj)` and `res.jsonp(obj, status)` signatures: Use `res.status(status).jsonp(obj)`. -- `app.param(fn)`: This method has been deprecated. Instead, access parameters directly via `req.params`, or use `req.body` or `req.query` as needed. -- `app.del('/', () => {})` method: Use `app.delete('/', () => {})` instead. -- `req.acceptsCharset`: Use `req.acceptsCharsets` (plural). -- `req.acceptsEncoding`: Use `req.acceptsEncodings` (plural). -- `req.acceptsLanguage`: Use `req.acceptsLanguages` (plural). -- `res.sendfile` method: Use `res.sendFile` instead. - -As a framework, we aim to ensure that the API is as consistent as possible. We've removed these deprecated signatures to make the API more predictable and easier to use. By streamlining each method to use a single, consistent signature, we simplify the developer experience and reduce confusion. - -## Migration and security guidance - -For developers looking to migrate from v4 to v5, there's a [detailed migration guide]({{site.url}}/{{page.lang}}/guide/migrating-5) to help you navigate through the changes and ensure a smooth upgrade process. - -Additionally, we’ve been working hard on a comprehensive [Threat Model](https://github.com/expressjs/security-wg/blob/main/docs/ThreatModel.md) that helps illustrate our philosophy of a "Fast, unopinionated, minimalist web framework for Node.js." It provides critical insights into areas like user input validation and security practices that are essential for safe and secure usage of Express in your applications. - -## Our work is just starting - -We see the v5 release as a milestone toward an Express ecosystem that's a stable and reliable tool for companies, governments, educators, and hobby projects. It is our commitment as the new stewards of the Express project to move the ecosystem forward with this goal in mind. If you want to support this work, which we do on a volunteer basis, please consider supporting the project and its maintainers via [our sponsorship opportunities](https://opencollective.com/express). - -We have an [extensive working backlog](https://github.com/expressjs/discussions/issues/266) of tasks, PRs, and issues for Express and dependencies. Naturally, we expect developers will continue to report issues to add to this backlog and open PRs moving forward, and we'll continue to collaborate with the community to triage and resolve them. We look forward to continuing to improve Express and making it useful for its users across the world. diff --git a/_posts/2024-10-22-security-audit-milestone-achievement.md b/_posts/2024-10-22-security-audit-milestone-achievement.md deleted file mode 100644 index 115f4e7d6a..0000000000 --- a/_posts/2024-10-22-security-audit-milestone-achievement.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: "Express.js Security Audit: A Milestone Achievement" -tags: security, audit, releases -author: Express Technical Committee -description: Celebrating the successful completion of the Express.js security audit conducted by Ada Logics and facilitated by OSTIF. ---- - - -We are thrilled to announce the successful completion of a comprehensive security audit for Express.js, conducted by [Ada Logics](https://adalogics.com/) and facilitated by [OSTIF](https://ostif.org/). This extensive review of our framework and its core components marks a significant milestone in our commitment to ensuring the security and reliability of Express.js for our community. - -## A Collaborative Effort - -This audit was made possible through the collaboration between [the Express Security Working Group](https://github.com/expressjs/security-wg), Ada Logics, OSTIF, and the [OpenJS Foundation](https://openjsf.org/). Our focus was on thoroughly evaluating the Express.js codebase, including its dependencies and core libraries. The primary goal was to identify any potential security vulnerabilities and to strengthen the overall security posture of the framework. - -### Key Highlights of the Audit - -- **Audit Duration**: Conducted in April and May 2024. -- **Scope**: Core Express.js codebase and critical dependencies, such as `body-parser`, `basic-auth-connect`, `serve-static`, and more. -- **Findings**: A total of 5 security vulnerabilities were identified, all of which have been addressed and patched. -- **Severity**: Issues ranged from moderate to high severity, impacting components like `res.redirect` and `serve-static`. - -## A Closer Look at the Findings - -The audit identified several vulnerabilities, including potential Cross-Site Scripting (XSS) risks and a Denial of Service (DoS) vulnerability in the `body-parser` middleware. Here are the key CVEs reported: - -- **CVE-2024-43796**: XSS in `res.redirect`—fixed in versions >= 4.20.0 and >= 5.0.0. -- **CVE-2024-45590**: DoS in `body-parser`—patched in version >= 1.20.3. -- **CVE-2024-47178**: Timing vulnerability in `basic-auth-connect`—patched in version >= 1.1.0. -- **CVE-2024-43799**: XSS in the `send` utility module—patched in version >= 0.19.0. -- **CVE-2024-43800**: XSS in `serve-static`—fixed in versions >= 1.16.0 and >= 2.1.0. - -Each of these vulnerabilities was promptly addressed by our dedicated [security triage team](https://github.com/expressjs/security-wg?tab=readme-ov-file#security-triage-team), ensuring that users remain protected against known threats. - -For full details on the audit results, you can access the [official audit report here](https://ostif.org/wp-content/uploads/2024/10/expressjs-2024-security-audit-report.pdf). - -## A Commitment to Transparency and Security - -At Express, security is a top priority, and we believe in the importance of transparency when it comes to vulnerabilities and their resolution. This audit not only highlights our proactive approach but also reinforces our ongoing commitment to building a secure web framework for all. - -We strongly recommend all users update to the latest versions of the affected packages to benefit from the recent security fixes. For more information on the patches and how to upgrade, please refer to our [September 2024 Security Release announcement](https://expressjs.com/2024/09/29/security-releases.html). - -## A Word of Thanks - -This audit would not have been possible without the efforts and expertise of many individuals and organizations. We want to extend our gratitude to: - -- The team at Ada Logics for their diligent review and insights. -- OSTIF for their coordination and support throughout the audit process. -- The OpenJS Foundation for sponsoring this important initiative. -- Our Express.js community, who continue to support and trust us with their projects. -- [Jordan Harband](https://github.com/ljharb) for his amazing support while we needed changes in [qs](https://www.npmjs.com/package/qs). - - -Together, we’ve made Express.js stronger, more resilient, and ready for the challenges ahead. We look forward to continuing to serve our community with a focus on excellence and security. - -Thank you for being a part of this journey with us! diff --git a/_posts/2025-01-09-rewind-2024-triumphs-and-2025-vision.md b/_posts/2025-01-09-rewind-2024-triumphs-and-2025-vision.md deleted file mode 100644 index 93d0e4b454..0000000000 --- a/_posts/2025-01-09-rewind-2024-triumphs-and-2025-vision.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: "A New Chapter for Express.js: Triumphs of 2024 and an ambitious 2025" -tags: news, rewind, 2024 -author: Express Technical Committee -description: Explore the transformative journey of Express.js in 2024, marked by governance improvements, the long-awaited release of Express 5.0, and heightened security measures. Look into the ambitious plans for 2025, including performance optimizations, scoped packages, and a bold roadmap for sustained growth in the Node.js ecosystem. ---- - - -As we step into the new year, it’s almost impossible to ignore the unmistakable energy coursing through the Express.js community. The past twelve months have proven both foundational and forward-looking: an era of governance overhauls, technical triumphs, and security enhancements that not only shaped 2024 but also laid the groundwork for what promises to be a transformative 2025. -In this long-form recap and forecast, we’ll journey through the story of Express.js with its evolution, its hurdles, and the new heights it’s poised to reach. - ---- - -## A Transformative 2024 - -Few could have predicted just how pivotal 2024 would be for the Express.js project. From the revitalization of its governance structures to the unveiling of long-awaited features, it was a year that solidified the framework’s role as a mainstay in the Node.js ecosystem. - -### Governance and Community Milestones - -Central to the project’s growth was the [Express Forward Plan](https://github.com/expressjs/discussions/issues/160), devised to ensure strategic alignment and long-term sustainability. This year also saw the introduction of a new generation of Technical Committee (TC) members, each bringing fresh insights and energy to the community. Those members include [Blake Embrey](https://github.com/blakeembrey), [Chris de Almeida](https://github.com/ctcpip), [Jean Burellier](https://github.com/sheplu), [Jon Church](https://github.com/jonchurch), [Linus Unnebäck](https://github.com/LinusU), [Rand McKinney](https://github.com/crandmck), [Ulises Gascón](https://github.com/ulisesgascon), and [Wes Todd](https://github.com/wesleytodd). By defining a clear path and transparent processes, the community was able to collaborate on ambitious updates more cohesively than ever before. A revitalized release process further streamlined how new versions are planned and executed, eliminating much of the guesswork and inconsistent timing that had previously challenged contributors. - -In parallel, the [Security Working Group](https://github.com/expressjs/discussions/issues/165) took shape. Express.js, widely recognized for its importance to the broader Node.js landscape, formally introduced a [security triage team](https://github.com/expressjs/security-wg#security-triage-team) dedicated to proactively identifying and resolving vulnerabilities. This forward-thinking approach was bolstered by the adoption of a [Threat Model for Express.js](https://github.com/expressjs/express/pull/5526), underscoring the project’s commitment to robust, future-proof security. - -As if these achievements weren’t enough, Express.js proudly reached [Impact Project status](https://github.com/openjs-foundation/cross-project-council/pull/1404) under the OpenJS Foundation. This acknowledgment affirmed the significance of the framework to the JavaScript ecosystem and showcased the community’s tireless efforts in ensuring its enduring relevance. - -### Technical Advancements and the Release of Express 5.0 - -Naturally, 2024 will forever be remembered as the year when Express.js finally introduced its much-anticipated [Express 5.0](https://expressjs.com/2024/10/15/v5-release.html). After more than a decade of community discussions and behind-the-scenes experimentation, this release brought modern features and a future-oriented architecture to the framework, acting as a catalyst for the next chapter of Express.js development. - -But the story did not end there. Even before the release of Express 5.0 was fully established, the community had already begun charting the course for [Express 6.0](https://github.com/expressjs/discussions/issues/267), reflecting an unwavering commitment to innovation. Guiding critical decisions throughout 2024 were new [decision framework](https://github.com/expressjs/discussions/issues/285), which helped the Technical Committee tackle pressing matters such as [engine usage](https://github.com/expressjs/discussions/issues/286) and [dependency management](https://github.com/expressjs/discussions/issues/279). Collectively, these measures fostered transparency and agility, ensuring that Express.js continues to evolve in response to the community’s most urgent needs. - -### Maintenance, Tooling, and Collaboration - -Express.js also deepened its relationship with the Node.js community by re-integrating into the [Node.js CITGM project](https://github.com/expressjs/express/issues/5489). This move ensured broader ecosystem compatibility and provided developers with further validation that they can rely on Express.js as a dependable cornerstone of their Node.js applications. - -### A Heightened Security Posture - -Above all, 2024 will stand out for Express.js’s vigorous approach to security. In partnership with the [OpenJS Foundation](https://openjsf.org/) and [OSTIF](https://ostif.org/), the project undertook a comprehensive [security audit](https://expressjs.com/2024/10/22/security-audit-milestone-achievement.html) that yielded critical insights and propelled immediate improvements. The sense of proactive vigilance extended to the adoption of the [OSSF Scorecard](https://github.com/expressjs/discussions/issues/162), implemented at an organizational level to keep track of security metrics and maintain focus on ongoing enhancements. - -Throughout the year, maintainers rapidly responded to disclosed vulnerabilities such as [CVE-2024-43796](https://github.com/expressjs/express/security/advisories/GHSA-qw6h-vgh9-j6wx), [CVE-2024-45590](https://github.com/expressjs/body-parser/security/advisories/GHSA-qwcr-r2fm-qrc7), and [CVE-2024-47178](https://github.com/expressjs/basic-auth-connect/security/advisories/GHSA-7p89-p6hx-q4fw). Each instance underscored the community’s readiness to defend the framework’s integrity and safeguard its user base. In a further demonstration of long-term commitment, Express.js teamed up with [HeroDevs](https://www.herodevs.com/) to establish [Never-Ending Support (NES)](https://openjsf.org/blog/at-the-openjs-foundation-were-excited-to-announce-), offering an extended maintenance plan that reaffirms Express.js as a reliable foundation for developers now and in the years to come. - - ---- - -## A Bold Vision for 2025 - -While 2024 laid a sturdy bedrock, the Express.js Technical Committee is not resting on its laurels. The newly revealed roadmap for 2025—bolstered by the [Sovereign Tech Fund (STF)](https://www.sovereign.tech/)—embodies a spirit of forward momentum. It promises notable strides in security, performance, and general developer experience, with each initiative building on the insights gained over the past year. - -### Automating npm Releases - -At the forefront of this plan is the automation of npm releases, an endeavor designed to free maintainers from manual steps and human error. By streamlining the publishing process, the project can achieve faster turnaround times for patches and new features, preserving the stability that developers have come to expect from Express.js. It’s an internal shift with massive external benefits: smoother upgrades, more frequent releases, and a deeper reservoir of confidence for users. - -### Introducing Scoped Packages - -Express.js will also explore a transition toward scoped packages. By clearly delineating which modules fall under the Express.js umbrella, the maintainers hope to reduce confusion and foster an environment more conducive to organized expansion. As new packages and features are proposed, scoping will make it simpler to track official tools and ensure that community contributions meet consistent quality standards. - -### Strengthening Security Reporting and Procedures - -Since security remains one of the project’s primary pillars, 2025 will see a significant push to refine how vulnerabilities are reported and managed. Building upon the success of the Security Working Group, the new process will introduce transparent guidelines for reporting potential issues and a consistent triage routine for mitigating them. Additional training for both the Security Triage group and the Technical Committee will further cultivate a shared culture of readiness. Moreover, Express.js is poised to integrate [OSSF Scorecard](https://github.com/expressjs/discussions/issues/162) even more deeply into daily operations, ensuring that both maintainers and users have real-time insights into the project’s health. - -### Performance Monitoring and Deep-Level Optimizations - -Performance is another focal point. By systematically monitoring the framework’s speed and responsiveness—along with that of its dependencies—the Express.js team aims to pinpoint bottlenecks more rapidly. Over time, insights from these monitoring efforts will drive deeper optimizations in the core Express.js code and its core libraries. These improvements, expected to come to fruition by mid-2026, promise a faster, more scalable framework that can handle the heaviest production workloads with ease. - -### Phasing Out Legacy Techniques and Enhancing Documentation - -A future of agility and resilience depends on eliminating outdated techniques that invite complexity and fragility. As a result, Express.js will begin phasing out monkey-patching and passthrough APIs that rely too heavily on Node.js internals. This modernization strategy not only reduces technical debt but also ensures that Express.js remains aligned with Node.js updates going forward. - -In tandem, the project will make a concerted effort to bolster its security documentation. Through updated guides and best practices, maintainers hope to demystify crucial topics like secure session handling, input validation, and access control. The goal is to arm developers—from novices to seasoned engineers—with the knowledge they need to protect their applications against an ever-evolving threat landscape. - ---- - -## The Road Ahead - -As Express.js steps into 2025, it does so with a powerful sense of purpose. The achievements of the past year—culminating in the official release of Express 5.0 and wide-reaching governance enhancements—serve as a sturdy foundation for what’s to come. Yet, the framework’s leadership knows there is always more to build, more to secure, and more to imagine. - -Through automated releases, scopes for packages, rigorous security protocols, performance monitoring, and an ongoing effort to modernize core APIs, Express.js is evolving in real-time. And it isn’t just about technology; it’s about forging a collaborative environment where contributors can rely on transparent processes, robust training, and a supportive governance structure. - -Whether you’re a seasoned maintainer, an occasional contributor, or a newcomer to this thriving ecosystem, your voice matters. Join the [Express.js GitHub Discussions](https://github.com/expressjs/discussions), attend open meetings, and stay tuned for updates on [Express.js blog](https://expressjs.com/) as we finalize timetables for these initiatives. Each advancement, no matter how technical, flows from a common aspiration: to sustain Express.js as a fast, safe, and influential framework for millions of developers worldwide. -Together, we’ll keep the spirit of 2024 alive—pushing boundaries, refining practices, and laying the path to a future where Express.js remains at the heart of modern web development. - diff --git a/2x/applications.html b/applications.html similarity index 94% rename from 2x/applications.html rename to applications.html index 113485e86e..129fe93253 100644 --- a/2x/applications.html +++ b/applications.html @@ -3,19 +3,6 @@ Express - node web framework -