Express Object
Creates an Express application. The express() function is a top-level function exported by the express module.
var express = require('express');var app = express();Methods
express.json([options])
Note
This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.
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.
Warning
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 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. | 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 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 |
express.raw([options])
Note
This is a built-in middleware function in Express. It parses incoming request
payloads into a Buffer and is based on
body-parser.
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.
Warning
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 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 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 |
express.Router([options])
Creates a new router object.
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.
express.static(root, [options])
This is a built-in middleware function in Express. It serves static files and is based on serve-static.
Note
For best results, 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 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.
| Property | Description | Type | Default |
|---|---|---|---|
dotfiles | Determines how dotfiles (files or directories that begin with a dot ”.”) are treated. See 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 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. | 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 below. | Function | |
acceptRanges | Enable or disable accepting ranged requests. Disabling this will not send the Accept-Ranges header and will ignore the contents of the Range request header. | Boolean | true |
cacheControl | Enable or disable setting the Cache-Control response header. Disabling this will ignore the immutable and maxAge options. | Boolean | true |
For more information, see Serving static files in Express. and Using middleware - Built-in middleware.
dotfiles
Possible values for this option are:
- “allow” - No special treatment for dotfiles.
- “deny” - Deny a request for a dotfile, respond with
403, then callnext(). - “ignore” - Act as if the dotfile does not exist, respond with
404, then callnext(). 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:
fn(res, path, stat);Arguments:
res, the response object.path, the file path that is being sent.stat, thestatobject 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:
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));express.text([options])
Note
This is a built-in middleware function in Express. It parses incoming request payloads into a string and is based on body-parser.
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.
Warning
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 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 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 |
express.urlencoded([options])
Note
This is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser.
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).
Warning
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. | 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 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 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 |
depth | 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. | Number | 32 |
Caution
The depth option was added in Express v4.20.0. If you are using an earlier version, this option
will not be available.