4.x API
Note
Express 4.0 requires Node.js 0.10 or higher.
express()
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])
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.
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 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])
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.
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 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 | Â |
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
, thestat
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:
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])
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.
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 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])
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.
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. |
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 |
The depth
option was added in Express v4.20.0. If you are using an earlier version, this option will not be available.
Application
The app
object conventionally denotes the Express application.
Create it by calling the top-level express()
function exported by the Express module:
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 and app.param.
- Configuring middleware; see app.route.
- Rendering HTML views; see app.render.
- Registering a template engine; see app.engine.
It also has settings (properties) that affect how the application behaves; for more information, see Application settings.
The Express application object can be referred from the request object and the response object as req.app
, and res.app
, respectively.
Properties
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.
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.
console.dir(app.locals.title)
// => 'My App'
console.dir(app.locals.email)
// => '[email protected]'
Once set, the value of app.locals
properties persist throughout the life of the application,
in contrast with 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)
app.locals.title = 'My App'
app.locals.strftime = require('strftime')
app.locals.email = '[email protected]'
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.
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 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.
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
Events
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.
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)
Methods
app.all(path, callback [, callback ...])
This method is like the standard app.METHOD() methods, except it matches all HTTP verbs.
Arguments
Argument | Description | Default |
---|---|---|
path |
The path for which the middleware function is invoked; can be any of:
|
'/' (root path) |
callback |
Callback functions; can be:
You can provide multiple callback functions that behave just like middleware, except
that these callbacks can invoke 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 |
Examples
The following callback is executed for requests to /secret
whether using
GET, POST, PUT, DELETE, or any other HTTP request method:
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.
app.all('*', requireAuthentication, loadUser)
Or the equivalent:
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â:
app.all('/api/*', requireAuthentication)
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.
Arguments
Argument | Description | Default |
---|---|---|
path |
The path for which the middleware function is invoked; can be any of:
|
'/' (root path) |
callback |
Callback functions; can be:
You can provide multiple callback functions that behave just like middleware, except
that these callbacks can invoke 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 |
Example
app.delete('/', function (req, res) {
res.send('DELETE request to homepage')
})
app.disable(name)
Sets the Boolean setting name
to false
, where name
is one of the properties from the app settings table.
Calling app.set('foo', false)
for a Boolean property is the same as calling app.disable('foo')
.
For example:
app.disable('trust proxy')
app.get('trust proxy')
// => false
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.disabled('trust proxy')
// => true
app.enable('trust proxy')
app.disabled('trust proxy')
// => false
app.enable(name)
Sets the Boolean setting name
to true
, where name
is one of the properties from the app settings table.
Calling app.set('foo', true)
for a Boolean property is the same as calling app.enable('foo')
.
app.enable('trust proxy')
app.get('trust proxy')
// => true
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.enabled('trust proxy')
// => false
app.enable('trust proxy')
app.enabled('trust proxy')
// => true
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.
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:
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 library maps Node template engines to follow this convention, so they work seamlessly with Express.
var engines = require('consolidate')
app.engine('haml', engines.haml)
app.engine('html', engines.hogan)
app.get(name)
Returns the value of name
app setting, where name
is one of the strings in the
app settings table. For example:
app.get('title')
// => undefined
app.set('title', 'My Site')
app.get('title')
// => "My Site"
app.get(path, callback [, callback ...])
Routes HTTP GET requests to the specified path with the specified callback functions.
Arguments
Argument | Description | Default |
---|---|---|
path |
The path for which the middleware function is invoked; can be any of:
|
'/' (root path) |
callback |
Callback functions; can be:
You can provide multiple callback functions that behave just like middleware, except
that these callbacks can invoke 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 |
For more information, see the routing guide.
Example
app.get('/', function (req, res) {
res.send('GET request to homepage')
})
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().
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().
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.).
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):
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 object and (for HTTP) is a convenience method for the following:
app.listen = function () {
var server = http.createServer(this)
return server.listen.apply(server, arguments)
}
Note
All the forms of Nodeâs http.Server.listen() method are in fact actually supported.
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 below for the complete list.
Arguments
Argument | Description | Default |
---|---|---|
path |
The path for which the middleware function is invoked; can be any of:
|
'/' (root path) |
callback |
Callback functions; can be:
You can provide multiple callback functions that behave just like middleware, except
that these callbacks can invoke 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 |
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.
For more information on routing, see the routing guide.
app.param([name], callback)
Add callback triggers to 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.
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.
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
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.
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.
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:
// 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() })
app.path()
Returns the canonical path of the app, a string.
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 to get the canonical path of the app.
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.
Arguments
Argument | Description | Default |
---|---|---|
path |
The path for which the middleware function is invoked; can be any of:
|
'/' (root path) |
callback |
Callback functions; can be:
You can provide multiple callback functions that behave just like middleware, except
that these callbacks can invoke 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 |
Example
app.post('/', function (req, res) {
res.send('POST request to homepage')
})
app.put(path, callback [, callback ...])
Routes HTTP PUT requests to the specified path with the specified callback functions.
Arguments
Argument | Description | Default |
---|---|---|
path |
The path for which the middleware function is invoked; can be any of:
|
'/' (root path) |
callback |
Callback functions; can be:
You can provide multiple callback functions that behave just like middleware, except
that these callbacks can invoke 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 |
Example
app.put('/', function (req, res) {
res.send('PUT request to homepage')
})
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(),
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.
app.render('email', function (err, html) {
// ...
})
app.render('email', { name: 'Tobi' }, function (err, html) {
// ...
})
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).
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...
})
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.
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.set('title', 'My Site')
app.get('title') // "My Site"
Application Settings
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â).
Property | Type | Description | Default |
---|---|---|---|
|
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) |
|
String |
Environment mode. Be sure to set to âproductionâ in a production environment; see Production best practices: performance and reliability. |
|
|
Varied |
Set the ETag response header. For possible values, see the |
|
|
String | Specifies the default JSONP callback name. |
âcallbackâ |
|
Boolean |
Enable escaping JSON responses from the NOTE: Sub-apps will inherit the value of this setting. |
N/A (undefined) |
|
Varied | The 'replacer' argument used by `JSON.stringify`.
NOTE: Sub-apps will inherit the value of this setting. |
N/A (undefined) |
|
Varied | The '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) |
|
Varied |
Disable query parsing by setting the value to The simple query parser is based on Nodeâs native query parser, querystring. The extended query parser is based on 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" |
|
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) |
|
Number | The number of dot-separated parts of the host to remove to access subdomain. | 2 |
|
Varied |
Indicates the app is behind a front-facing proxy, and to use the 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. |
|
|
String or Array | A directory or an array of directories for the application's views. If an array, the views are looked up in the order they occur in the array. |
|
|
Boolean | Enables view template compilation caching. NOTE: Sub-apps will not inherit the value of this setting in production (when `NODE_ENV` is "production"). |
|
|
String | The default engine extension to use when omitted.
NOTE: Sub-apps will inherit the value of this setting. |
N/A (undefined) |
|
Boolean | Enables the "X-Powered-By: Express" HTTP header. |
|
Options for `trust proxy` setting
Read Express behind proxies for more information.
Type | Value |
---|---|
Boolean |
If If |
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:
Set IP addresses in any of the following ways: Specify a single subnet:
Specify a subnet and an address:
Specify multiple subnets as CSV:
Specify multiple subnets as an array:
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.
|
Options for `etag` setting
NOTE: These settings apply only to dynamic files, not static files. The express.static middleware ignores these settings.
The ETag functionality is implemented using the etag package. For more information, see its documentation.
Type | Value |
---|---|
Boolean |
|
String |
If "strong", enables strong ETag. If "weak", enables weak ETag. |
Function |
Custom ETag function implementation. Use this only if you know what you are doing.
|
app.use([path,] callback [, callback...])
Mounts the specified middleware function or functions
at the specified path:
the middleware function is executed when the base of the requested path matches path
.
Arguments
Argument | Description | Default |
---|---|---|
path |
The path for which the middleware function is invoked; can be any of:
|
'/' (root path) |
callback |
Callback functions; can be:
You can provide multiple callback functions that behave just like middleware, except
that these callbacks can invoke 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 |
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:
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.
Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.
// 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.
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)
):
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.
Type | Example |
---|---|
Path |
Matches the exact path
|
Path Pattern |
This will match paths starting with
This will match paths starting with
This will match paths starting with
This will match paths starting with
|
Regular Expression |
This will match paths starting with
|
Array |
This will match paths starting with
|
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()
.
Usage | Example |
---|---|
Single Middleware |
You can define and mount a middleware function locally.
A router is valid middleware.
An Express app is valid middleware.
|
Series of Middleware |
You can specify more than one middleware function at the same mount path.
|
Array |
Use an array to group middleware logically.
|
Combination |
You can combine all the above ways of mounting middleware.
|
</div>
Following are some examples of using the express.static middleware in an Express app.
Serve static content for the app from the âpublicâ directory in the application directory:
// 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â:
// 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:
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:
app.use(express.static(path.join(__dirname, 'public')))
app.use(express.static(path.join(__dirname, 'files')))
app.use(express.static(path.join(__dirname, 'uploads')))
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:
app.get('/user/:id', function (req, res) {
res.send('user ' + req.params.id)
})
But you could just as well have:
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.
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, multer,
formidable,
multiparty,
connect-multiparty,
or pez.
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:
// index.js
app.get('/viewdirectory', require('./mymiddleware.js'))
// mymiddleware.js
module.exports = function (req, res) {
res.send('The views directory is ' + req.app.get('views'))
}
req.baseUrl
The URL path on which a router instance was mounted.
The req.baseUrl
property is similar to the mountpath property of the app
object,
except app.mountpath
returns the matched path pattern(s).
For example:
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.
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â.
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()
or 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
.
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)
})
req.cookies
When using cookie-parser middleware, this property is an object that
contains cookies sent by the request. If the request contains no cookies, it defaults to {}
.
// Cookie: name=tj
console.dir(req.cookies.name)
// => 'tj'
If the cookie has been signed, you have to use req.signedCookies.
For more information, issues, or concerns, see cookie-parser.
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.
console.dir(req.fresh)
// => true
req.hostname
Contains the hostname derived from the Host
HTTP header.
When the trust proxy
setting
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.
// Host: "example.com:3000"
console.dir(req.hostname)
// => 'example.com'
req.ip
Contains the remote IP address of the request.
When the trust proxy
setting 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.
console.dir(req.ip)
// => '127.0.0.1'
req.ips
When the trust proxy
setting 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.
req.method
Contains a string corresponding to the HTTP method of the request:
GET
, POST
, PUT
, and so on.
req.originalUrl
req.url
is not a native Express property, it is inherited from Nodeâs http module.
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