Express Object
Creates an Express application. The express() function is a top-level function exported by the express module.
const express = require('express');const app = express();import express from 'express';
const app = express();Methods
The Express object has the following methods that can be used to create middleware functions, routers and have some built-in middleware:
express.json()
Arguments
options Configures how the JSON body is parsed; it accepts the properties below.
defaultCharset Specify the default character set for the JSON content if the charset is not specified in
the Content-Type header of the request.
inflate Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.
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.
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.
strict Enables or disables only accepting arrays and objects; when disabled will accept anything
JSON.parse accepts.
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.
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.
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 undefined 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.
const express = require('express');const app = express();
// parse requests with a Content-Type of application/jsonapp.use(express.json());
app.post('/profile', (req, res) => { console.dir(req.body); res.json(req.body);});import express from 'express';
const app = express();
// parse requests with a Content-Type of application/jsonapp.use(express.json());
app.post('/profile', (req, res) => { console.dir(req.body); res.json(req.body);});express.raw()
Arguments
options Configures how the request body is parsed; it accepts the properties below.
inflate Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.
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.
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.
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.
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 undefined 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.
const express = require('express');const app = express();
// parse requests with a Content-Type of application/octet-stream into a Bufferapp.use(express.raw());
app.post('/upload', (req, res) => { console.dir(Buffer.isBuffer(req.body)); // => true res.send(`received ${req.body.length} bytes`);});import express from 'express';
const app = express();
// parse requests with a Content-Type of application/octet-stream into a Bufferapp.use(express.raw());
app.post('/upload', (req, res) => { console.dir(Buffer.isBuffer(req.body)); // => true res.send(`received ${req.body.length} bytes`);});express.Router()
Arguments
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.
strict Enable strict routing. Disabled by default, /foo and /foo/ are treated the same by the
router.
Creates a new router object.
const router = express.Router([options]);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()
Arguments
root The root directory from which to serve static assets.
options Configures how files are served; it accepts the properties below. See also the example below.
dotfiles Determines how dotfiles (files or directories that begin with a dot ”.”) are treated. See dotfiles below.
etag Enable or disable etag generation.
Note
express.static always sends weak ETags.
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'].
fallthrough Let client errors fall-through as unhandled requests, otherwise forward a client error. See fallthrough below.
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.
index Sends the specified directory index file. Set to false to disable directory indexing.
lastModified Set the Last-Modified header to the last modified date of the file on the OS.
maxAge Set the max-age property of the Cache-Control header in milliseconds or a string in ms format.
redirect Redirect to trailing ”/” when the pathname is a directory.
setHeaders Function for setting HTTP headers to serve with the file. See setHeaders below.
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.
cacheControl Enable or disable setting the Cache-Control response header. Disabling this will ignore
the immutable and maxAge 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 instead calls next()
to move on to the next middleware, allowing for stacking and fall-backs.
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().
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:
const express = require('express');const app = express();
const options = { dotfiles: 'ignore', etag: false, extensions: ['htm', 'html'], index: false, maxAge: '1d', redirect: false, setHeaders(res, path, stat) { res.set('x-timestamp', Date.now()); },};
app.use(express.static('public', options));import express from 'express';
const app = express();
const options = { dotfiles: 'ignore', etag: false, extensions: ['htm', 'html'], index: false, maxAge: '1d', redirect: false, setHeaders(res, path, stat) { res.set('x-timestamp', Date.now()); },};
app.use(express.static('public', options));express.text()
Arguments
options Configures how the text body is parsed; it accepts the properties below.
defaultCharset Specify the default character set for the text content if the charset is not specified in
the Content-Type header of the request.
inflate Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.
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.
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.
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.
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 undefined 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.
const express = require('express');const app = express();
// parse requests with a Content-Type of text/plain into a stringapp.use(express.text());
app.post('/', (req, res) => { console.dir(typeof req.body); // => 'string' res.send(req.body);});import express from 'express';
const app = express();
// parse requests with a Content-Type of text/plain into a stringapp.use(express.text());
app.post('/', (req, res) => { console.dir(typeof req.body); // => 'string' res.send(req.body);});express.urlencoded()
Arguments
options Configures how the URL-encoded body is parsed; it accepts the properties below.
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.
inflate Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies are rejected.
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.
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.
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.
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.
defaultCharset The default charset to parse as, if not specified in content-type. Must be either utf-8
or iso-8859-1.
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 ✓.
interpretNumericEntities Whether to decode numeric entities such as ☺ when parsing an iso-8859-1 form.
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. It is recommended to keep this value as low as possible.
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 undefined 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.
const express = require('express');const app = express();
// parse requests with a Content-Type of application/x-www-form-urlencodedapp.use(express.urlencoded({ extended: true }));
app.post('/profile', (req, res) => { console.dir(req.body); res.json(req.body);});import express from 'express';
const app = express();
// parse requests with a Content-Type of application/x-www-form-urlencodedapp.use(express.urlencoded({ extended: true }));
app.post('/profile', (req, res) => { console.dir(req.body); res.json(req.body);});