API 4.x

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.

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.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 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.

Property

Description

Type

Default

dotfiles

Determines how dotfiles (files or directories that begin with a dot “.”) are treated.

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.

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().

NOTE: With the default value, it will not ignore files in a directory that begins with a dot.

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.

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.

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

Application

The app object conventionally denotes the Express application.
Create it by calling the top-level express() function exported by the Express module:

Properties

app.locals

The app.locals object has properties that are local variables within the application.

app.locals.title
// => 'My App'
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 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)

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.

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.

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.

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.

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.

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):

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.

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.

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.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.

Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or 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.

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.

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.

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]+/'.

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.

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.

Example

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.

Application Settings

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

case sensitive routing

Boolean

Enable case sensitivity.
When enabled, "/Foo" and "/foo" are different routes.
When disabled, "/Foo" and "/foo" are treated the same.

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 when clients sniff responses for HTML.

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

Number

The 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 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.

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").

Options for `trust proxy` setting

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.

StringString containing comma-separated valuesArray 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:

app.set('trust proxy', 'loopback')

Specify a subnet and an address:

app.set('trust proxy', 'loopback, 123.123.123.123')

Specify multiple subnets as CSV:

app.set('trust proxy', 'loopback, linklocal, uniquelocal')

Specify multiple subnets as an array:

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.

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.

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)):

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().
Even though the examples are for app.use(), they are also valid for app.use(), app.METHOD(), and app.all().

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.

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.

req.hostname

When the trust proxy setting does not evaluate to false,
this property will instead have the value of the X-Forwarded-Host header field.
This header can be set by the client or by the proxy.

// Host: "example.com:3000"
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.

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 app.use() will rewrite req.url to strip the mount point.

req.params

This property is an object containing properties mapped to the named 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 {}.

// GET /user/tj
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/*:

req.protocol

When the trust proxy setting 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.

req.protocol
// => "http"

req.query

This property is an object containing a property for each query string parameter in the route.
If there is no query string, it is the empty object, {}.

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.

req.secure

A Boolean property that is true if a TLS connection is established. Equivalent to:

'https' == req.protocol;

req.signedCookies

When using 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).

req.subdomains

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.

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.

req.xhr
// => true

Methods

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).

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.

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.

res.locals

An object that contains response local variables scoped to the request, and therefore available only to
the view(s) rendered during that request / response cycle (if any). Otherwise,
this property is identical to app.locals.

This property is useful for exposing request-level information such as the request path name,
authenticated user, user settings, and so on.

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.

When using 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.

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 path (this typically appears in the browser dialog).
Override this default with the filename parameter.

When an error occurs or transfer is complete, the method calls the optional callback function fn.
This method uses res.sendFile() to transfer the file.

The optional options argument passes through to the underlying res.sendFile()
call, and takes the exact same parameters.

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

Use to quickly end the response without any data. If you need to respond with data, instead use methods such as res.send() and res.json().

res.end();
res.status(404).end();

res.format(object)

Performs content-negotiation on the Accept HTTP header on the request object, when present.
It uses 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”).

Redirects can be a fully-qualified URL for redirecting to a different site:

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:

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.

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:

res.redirect('..');

A back redirection redirects the request back to the referer,
defaulting to / when the referer is missing.

res.redirect('back');

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.

When the parameter is a String, the method sets the Content-Type to “text/html”:

res.send('<p>some html</p>');

When the parameter is an Array or Object, Express responds with the JSON representation:

res.send({ user: 'tobi' });
res.send([1,2,3]);

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

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.

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.

If an unsupported status code is specified, the HTTP status is still set to statusCode and the string version of the code is sent as the response body.

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.

res.vary(field)

Adds the field to the Vary response header, if it is not there already.

res.vary('User-Agent').render('docs');

Router

A router object is an isolated 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() or as the argument to another router’s use() method.

The top-level express object has a 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:

// 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.

// only requests to /calendar/* will be sent to our "router"
app.use('/calendar', router);

Methods

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.

router.all('*', requireAuthentication, loadUser);

Or the equivalent:

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”:

router.all('/api/*', requireAuthentication);

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”.

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”.

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.

Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or 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.

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.

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.

This approach re-uses the single /users/:user_id path and adds handlers for
various HTTP methods.

NOTE: 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.

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(). A simple example and use case is described below.
See 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.

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.

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:

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:

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.