# app.get()
GET client javascript. Here we use sendFile() because serving __dirname with the static() middleware would also mean serving our server "index.js" and the "search.jade" template.
# GithubView()
Custom view that fetches and renders remove github templates. You could render templates from a database etc.
# all(path, ...)
Special-cased "all" method, applying the given route path
, middleware, and callback to every HTTP method.
Parameters
Name | Types | Description |
---|---|---|
path | String |
|
... | Function |
Returns
app
for chaining
# disable(setting)
Disable setting
.
Parameters
Name | Types | Description |
---|---|---|
setting | String |
Returns
app
for chaining
# disabled(setting)
Check if setting
is disabled. app.disabled('foo') // => true app.enable('foo') app.disabled('foo') // => false
Parameters
Name | Types | Description |
---|---|---|
setting | String |
Returns
Boolean
# enable(setting)
Enable setting
.
Parameters
Name | Types | Description |
---|---|---|
setting | String |
Returns
app
for chaining
# enabled(setting)
Check if setting
is enabled (truthy). app.enabled('foo') // => false app.enable('foo') app.enabled('foo') // => true
Parameters
Name | Types | Description |
---|---|---|
setting | String |
Returns
Boolean
# engine(ext, fn)
Register the given template engine callback fn
as ext
. By default will require()
the engine based on the file extension. For example if you try to render a "foo.ejs" file Express will invoke the following internally: app.engine('ejs', require('ejs').__express); For engines that do not provide .__express
out of the box, or if you wish to "map" a different extension to the template engine you may use this method. For example mapping the EJS template engine to ".html" files: 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 was created to map all of node's popular template engines to follow this convention, thus allowing them to work seamlessly within Express.
Parameters
Name | Types | Description |
---|---|---|
ext | String |
|
fn | Function |
Returns
app
for chaining
# handle()
private method
Dispatch a req, res pair into the application. Starts pipeline processing. If no callback is provided, then default error handlers will respond in the event of an error bubbling through the stack.
# init()
private method
Initialize the server. - setup default configuration - setup default middleware - setup route reflection methods
# lazyrouter()
private method
lazily adds the base router if it has not yet been added. We cannot add the base router in the defaultConfiguration because it reads app settings which might be set after that has run.
# listen()
Listen for connections. A node http.Server
is returned, with this application (which is a Function
) as its callback. If you wish to create both an HTTP and HTTPS server you may do so with the "http" and "https" modules as shown here: var http = require('http') , https = require('https') , express = require('express') , app = express(); http.createServer(app).listen(80); https.createServer({ ... }, app).listen(443);
Returns
http.Server
# logerror(err)
private method
Log error using console.error.
Parameters
Name | Types | Description |
---|---|---|
err | Error |
# param(name, fn)
Proxy to Router#param()
with one added api feature. The name parameter can be an array of names. See the Router#param() docs for more details.
Parameters
Name | Types | Description |
---|---|---|
name | String |
Array |
fn | Function |
Returns
app
for chaining
# path()
private method
Return the app's absolute pathname based on the parent(s) that have mounted it. For example if the application was mounted as "/admin", which itself was mounted as "/blog" then the return value would be "/blog/admin".
Returns
String
# render(name, options, callback)
Render the given view name
name with options
and a callback accepting an error and the rendered template string. Example: app.render('email', { name: 'Tobi' }, function(err, html){ // ... })
Parameters
Name | Types | Description |
---|---|---|
name | String |
|
options | Object |
Function |
callback | Function |
# route()
Proxy to the app Router#route()
Returns a new Route
instance for the path. Routes are isolated middleware stacks for specific paths. See the Route api docs for details.
# set(setting, val)
Assign setting
to val
, or return setting
's value. app.set('foo', 'bar'); app.set('foo'); // => "bar" Mounted servers inherit their parent server's settings.
Parameters
Name | Types | Description |
---|---|---|
setting | String |
|
val | * |
Returns
Server
for chaining
# use()
Proxy Router#use()
to add middleware to the app router. See Router#use() documentation for details. If the fn parameter is an express app, then it will be mounted at the route specified.
# exports.init(app)
private method
Initialization middleware, exposing the request and response to each other, as well as defaulting the X-Powered-By header field.
Parameters
Name | Types | Description |
---|---|---|
app | Function |
Returns
Function
# defineGetter()
Check if the request is fresh, aka Last-Modified and/or the ETag still match.
Returns
Boolean
# defineGetter(obj, name, getter)
private method
Helper function for creating a getter on an object.
Parameters
Name | Types | Description |
---|---|---|
obj | Object |
|
name | String |
|
getter | Function |
# hostname()
Parse the "Host" header field to a hostname. When the "trust proxy" setting trusts the socket address, the "X-Forwarded-Host" header field will be trusted.
Returns
String
# ip()
Return the remote address from the trusted proxy. The is the remote address on the socket unless "trust proxy" is set.
Returns
String
# ips()
When "trust proxy" is set, trusted proxy addresses + client. For example if the value were "client, proxy1, proxy2" you would receive the array ["client", "proxy1", "proxy2"]
where "proxy2" is the furthest down-stream and "proxy1" and "proxy2" were trusted.
Returns
Array
# is(types...)
Check if the incoming request contains the "Content-Type" header field, and it contains the given mime type
. Examples: // With Content-Type: text/html; charset=utf-8 req.is('html'); req.is('text/html'); req.is('text/'); // => true // When Content-Type is application/json req.is('json'); req.is('application/json'); req.is('application/'); // => true req.is('html'); // => false
Parameters
Name | Types | Description |
---|---|---|
types... | String |
Array |
Returns
String|false|null
# param(name, defaultValue)
Return the value of param name
when present or defaultValue
. - Checks route placeholders, ex: /user/:id - Checks body params, ex: id=12, {"id":12} - Checks query string params, ex: ?id=12 To utilize request bodies, req.body
should be an object. This can be done by using the bodyParser()
middleware.
Parameters
Name | Types | Description |
---|---|---|
name | String |
|
defaultValue | Mixed |
Returns
String
# protocol()
Return the protocol string "http" or "https" when requested with TLS. When the "trust proxy" setting trusts the socket address, the "X-Forwarded-Proto" header field will be trusted and used if present. If you're running behind a reverse proxy that supplies https for you this may be enabled.
Returns
String
# range(size, options, options.combine)
Parse Range header field, capping to the given size
. Unspecified ranges such as "0-" require knowledge of your resource length. In the case of a byte range this is of course the total number of bytes. If the Range header field is not given undefined
is returned, -1
when unsatisfiable, and -2
when syntactically invalid. When ranges are returned, the array has a "type" property which is the type of range that is required (most commonly, "bytes"). Each array element is an object with a "start" and "end" property for the portion of the range. The "combine" option can be set to true
and overlapping & adjacent ranges will be combined into a single range. NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" should respond with 4 users when available, not 3.
Parameters
Name | Types | Description |
---|---|---|
size | number |
|
options | object |
|
options.combine | boolean |
Returns
number|array
# req.accepts(type(s))
To do: update docs. Check if the given type(s)
is acceptable, returning the best match when true, otherwise undefined
, in which case you should respond with 406 "Not Acceptable". The type
value may be a single MIME type string such as "application/json", an extension name such as "json", a comma-delimited list such as "json, html, text/plain", an argument list such as "json", "html", "text/plain"
, or an array ["json", "html", "text/plain"]
. When a list or array is given, the best match, if any is returned. Examples: // Accept: text/html req.accepts('html'); // => "html" // Accept: text/, application/json req.accepts('html'); // => "html" req.accepts('text/html'); // => "text/html" req.accepts('json, text'); // => "json" req.accepts('application/json'); // => "application/json" // Accept: text/, application/json req.accepts('image/png'); req.accepts('png'); // => undefined // Accept: text/*;q=.5, application/json req.accepts(['html', 'json']); req.accepts('html', 'json'); req.accepts('html, json'); // => "json"
Parameters
Name | Types | Description |
---|---|---|
type(s) | String |
Array |
Returns
String|Array|Boolean
# req.acceptsCharsets(...charset)
Check if the given charset
s are acceptable, otherwise you should respond with 406 "Not Acceptable".
Parameters
Name | Types | Description |
---|---|---|
...charset | String |
Returns
String|Array
# req.acceptsEncodings(...encoding)
Check if the given encoding
s are accepted.
Parameters
Name | Types | Description |
---|---|---|
...encoding | String |
Returns
String|Array
# req.acceptsLanguages(...lang)
Check if the given lang
s are acceptable, otherwise you should respond with 406 "Not Acceptable".
Parameters
Name | Types | Description |
---|---|---|
...lang | String |
Returns
String|Array
# req.get(name)
Return request header. The Referrer
header field is special-cased, both Referrer
and Referer
are interchangeable. Examples: req.get('Content-Type'); // => "text/plain" req.get('content-type'); // => "text/plain" req.get('Something'); // => undefined Aliased as req.header()
.
Parameters
Name | Types | Description |
---|---|---|
name | String |
Returns
String
# stale()
Check if the request is stale, aka "Last-Modified" and / or the "ETag" for the resource has changed.
Returns
Boolean
# subdomains()
Return subdomains as an array. Subdomains are the dot-separated parts of the host before the main domain of the app. By default, the domain of the app is assumed to be the last two parts of the host. This can be changed by setting "subdomain offset". For example, if the domain is "tobi.ferrets.example.com": If "subdomain offset" is not set, req.subdomains is ["ferrets", "tobi"]
. If "subdomain offset" is 3, req.subdomains is ["tobi"]
.
Returns
Array
# append(field, val)
Append additional header field
with value val
. Example: res.append('Link', ['http://localhost/', 'http://localhost:3000/']); res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); res.append('Warning', '199 Miscellaneous warning');
Parameters
Name | Types | Description |
---|---|---|
field | String |
|
val | String |
Array |
Returns
ServerResponse
for chaining
# attachment(filename)
Set Content-Disposition header to attachment with optional filename
.
Parameters
Name | Types | Description |
---|---|---|
filename | String |
Returns
ServerResponse
# clearCookie(name, options)
Clear cookie name
.
Parameters
Name | Types | Description |
---|---|---|
name | String |
|
options | Object |
Returns
ServerResponse
for chaining
# download()
Transfer the file at the given path
as an attachment. Optionally providing an alternate attachment filename
, and optional callback callback(err)
. The callback is invoked when the data transfer is complete, or when an error has occurred. Be sure to check res.headersSent
if you plan to respond. Optionally providing an options
object to use with res.sendFile()
. This function will set the Content-Disposition
header, overriding any Content-Disposition
header passed as header options in order to set the attachment and filename. This method uses res.sendFile()
.
# json(obj)
Send JSON response. Examples: res.json(null); res.json({ user: 'tj' });
Parameters
Name | Types | Description |
---|---|---|
obj | string |
number |
# location(url)
Set the location header to url
. The given url
can also be "back", which redirects to the Referrer or Referer headers or "/". Examples: res.location('/foo/bar').; res.location('http://example.com'); res.location('../login');
Parameters
Name | Types | Description |
---|---|---|
url | String |
Returns
ServerResponse
for chaining
# redirect()
Redirect to the given url
with optional response status
defaulting to 302. The resulting url
is determined by res.location()
, so it will play nicely with mounted apps, relative paths, "back"
etc. Examples: res.redirect('/foo/bar'); res.redirect('http://example.com'); res.redirect(301, 'http://example.com'); res.redirect('../login'); // /blog/post/1 -> /blog/login
# render()
Render view
with the given options
and optional callback fn
. When a callback function is given a response will not be made automatically, otherwise a response of 200 and text/html is given. Options: - cache
boolean hinting to the engine it should cache - filename
filename of the view being rendered
# res.contentType(type)
Set Content-Type response header with type
through mime.lookup()
when it does not contain "/", or set the Content-Type to type
otherwise. Examples: res.type('.html'); res.type('html'); res.type('json'); res.type('application/json'); res.type('png');
Parameters
Name | Types | Description |
---|---|---|
type | String |
Returns
ServerResponse
for chaining
# res.cookie(name, value, options)
Set cookie name
to value
, with the given options
. Options: - maxAge
max-age in milliseconds, converted to expires
- signed
sign the cookie - path
defaults to "/" Examples: // "Remember Me" for 15 minutes res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); // same as above res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
Parameters
Name | Types | Description |
---|---|---|
name | String |
|
value | String |
Object |
options | Object |
Returns
ServerResponse
for chaining
# res.format(obj)
Respond to the Acceptable formats using an obj
of mime-type callbacks. This method uses req.accepted
, an array of acceptable types ordered by their quality values. When "Accept" is not present the first callback is invoked, otherwise the first match is used. When no match is performed the server responds with 406 "Not Acceptable". Content-Type is set for you, however if you choose you may alter this within the callback using res.type()
or res.set('Content-Type', ...)
. res.format({ 'text/plain': function(){ res.send('hey'); }, 'text/html': function(){ res.send('
hey
'); }, 'application/json': function () { res.send({ message: 'hey' }); } }); In addition to canonicalized MIME types you may also use extnames mapped to these types: res.format({ text: function(){ res.send('hey'); }, html: function(){ res.send('hey
'); }, json: function(){ res.send({ message: 'hey' }); } }); By default Express passes anError
with a .status
of 406 to next(err)
if a match is not made. If you provide a .default
callback it will be invoked instead.
Parameters
Name | Types | Description |
---|---|---|
obj | Object |
Returns
ServerResponse
for chaining
# res.get(field)
Get value for header field
.
Parameters
Name | Types | Description |
---|---|---|
field | String |
Returns
String
# res.links(links)
Set Link header field with the given links
. Examples: res.links({ next: 'http://api.example.com/users?page=2', last: 'http://api.example.com/users?page=5' });
Parameters
Name | Types | Description |
---|---|---|
links | Object |
Returns
ServerResponse
# res.sendfile()
Transfer the file at the given path
. Automatically sets the Content-Type response header field. The callback callback(err)
is invoked when the transfer is complete or when an error occurs. Be sure to check res.headersSent
if you wish to attempt responding, as the header and some data may have already been transferred. Options: - maxAge
defaulting to 0 (can be string converted by ms
) - root
root directory for relative filenames - headers
object of headers to serve with file - dotfiles
serve dotfiles, defaulting to false; can be "allow"
to send them Other options are passed along to send
. Examples: The following example illustrates how res.sendfile()
may be used as an alternative for the static()
middleware for dynamic situations. The code backing res.sendfile()
is actually the same code, so HTTP cache support etc is identical. app.get('/user/:uid/photos/:file', function(req, res){ var uid = req.params.uid , file = req.params.file; req.user.mayViewFilesFrom(uid, function(yes){ if (yes) { res.sendfile('/uploads/' + uid + '/' + file); } else { res.send(403, 'Sorry! you cant see that.'); } }); });
# res.set(field, val)
Set header field
to val
, or pass an object of header fields. Examples: res.set('Foo', ['bar', 'baz']); res.set('Accept', 'application/json'); res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); Aliased as res.header()
.
Parameters
Name | Types | Description |
---|---|---|
field | String |
Object |
val | String |
Array |
Returns
ServerResponse
for chaining
# res.vary(field)
Add field
to Vary. If already present in the Vary set, then this call is simply ignored.
Parameters
Name | Types | Description |
---|---|---|
field | Array |
String |
Returns
ServerResponse
for chaining
# send(body)
Send a response. Examples: res.send(Buffer.from('wahoo')); res.send({ some: 'json' }); res.send('
some html
');Parameters
Name | Types | Description |
---|---|---|
body | string |
number |
# sendFile()
Transfer the file at the given path
. Automatically sets the Content-Type response header field. The callback callback(err)
is invoked when the transfer is complete or when an error occurs. Be sure to check res.headersSent
if you wish to attempt responding, as the header and some data may have already been transferred. Options: - maxAge
defaulting to 0 (can be string converted by ms
) - root
root directory for relative filenames - headers
object of headers to serve with file - dotfiles
serve dotfiles, defaulting to false; can be "allow"
to send them Other options are passed along to send
. Examples: The following example illustrates how res.sendFile()
may be used as an alternative for the static()
middleware for dynamic situations. The code backing res.sendFile()
is actually the same code, so HTTP cache support etc is identical. app.get('/user/:uid/photos/:file', function(req, res){ var uid = req.params.uid , file = req.params.file; req.user.mayViewFilesFrom(uid, function(yes){ if (yes) { res.sendFile('/uploads/' + uid + '/' + file); } else { res.send(403, 'Sorry! you cant see that.'); } }); });
# status(code)
Set status code
.
Parameters
Name | Types | Description |
---|---|---|
code | Number |
Returns
ServerResponse
# stringify(value, replacer, spaces, escape)
private method
Stringify JSON, like JSON.stringify, but v8 optimized, with the ability to escape characters that can trigger HTML sniffing.
Parameters
Name | Types | Description |
---|---|---|
value | * |
|
replacer | function |
|
spaces | number |
|
escape | boolean |
# matchLayer(layer, path)
private method
Match path to a layer.
Parameters
Name | Types | Description |
---|---|---|
layer | Layer |
|
path | string |
# param(name, fn)
Map the given param placeholder name
(s) to the given callback. Parameter mapping is used to provide pre-conditions to routes which use normalized placeholders. For example a :user_id parameter could automatically load a user's information from the database without any additional code, The callback uses the same signature as middleware, the only difference being that the value of the placeholder is passed, in this case the id of the user. Once the next()
function is invoked, just like middleware it will continue on to execute the route, or subsequent parameter functions. Just like in middleware, you must either respond to the request or call next to avoid stalling the request. app.param('user_id', function(req, res, next, id){ User.find(id, function(err, user){ if (err) { return next(err); } else if (!user) { return next(new Error('failed to load user')); } req.user = user; next(); }); });
Parameters
Name | Types | Description |
---|---|---|
name | String |
|
fn | Function |
Returns
app
for chaining
# proto(options)
Initialize a new Router
with the given options
.
Parameters
Name | Types | Description |
---|---|---|
options | Object |
Returns
Router
which is a callable function
# route(path)
Create a new Route for the given path. Each route contains a separate middleware stack and VERB handlers. See the Route api documentation for details on adding handlers and middleware to routes.
Parameters
Name | Types | Description |
---|---|---|
path | String |
Returns
Route
# use()
Use the given middleware function, with optional path, defaulting to "/". Use (like .all
) will run for any http METHOD, but it will not add handlers for those methods so OPTIONS requests will not consider .use
functions even if they could respond. The other difference is that route path is stripped and not visible to the handler function. The main effect of this feature is that mounted handlers can operate without any code changes regardless of the "prefix" pathname.
# decode_param(val)
private method
Decode param value.
Parameters
Name | Types | Description |
---|---|---|
val | string |
Returns
string
# handle(req, res, next)
private method
Handle the request for the layer.
Parameters
Name | Types | Description |
---|---|---|
req | Request |
|
res | Response |
|
next | function |
# handle_error(error, req, res, next)
private method
Handle the error for the layer.
Parameters
Name | Types | Description |
---|---|---|
error | Error |
|
req | Request |
|
res | Response |
|
next | function |
# match(path)
private method
Check if this route matches path
, if so populate .params
.
Parameters
Name | Types | Description |
---|---|---|
path | String |
Returns
Boolean
# all(handler)
Add a handler for all HTTP verbs to this route. Behaves just like middleware and can respond or call next
to continue processing. You can use multiple .all
call to add multiple handlers. function check_something(req, res, next){ next(); }; function validate_user(req, res, next){ next(); }; route .all(validate_user) .all(check_something) .get(function(req, res, next){ res.send('hello world'); });
Parameters
Name | Types | Description |
---|---|---|
handler | function |
Returns
Route
for chaining
# acceptParams(str)
private method
Parse accept params str
returning an object with .value
, .quality
and .params
.
Parameters
Name | Types | Description |
---|---|---|
str | String |
Returns
Object
# compileQueryParser(val)
private method
Compile "query parser" value to function.
Parameters
Name | Types | Description |
---|---|---|
val | String |
Function |
Returns
Function
# createETagGenerator(options)
private method
Create an ETag generator function, generating ETags with the given options.
Parameters
Name | Types | Description |
---|---|---|
options | object |
Returns
function
# exports.compileETag(val)
private method
Compile "etag" value to function.
Parameters
Name | Types | Description |
---|---|---|
val | Boolean |
String |
Returns
Function
# exports.compileTrust(val)
private method
Compile "proxy trust" value to function.
Parameters
Name | Types | Description |
---|---|---|
val | Boolean |
String |
Returns
Function
# exports.contentDisposition(filename)
private method
Generate Content-Disposition header appropriate for the filename. non-ascii filenames are urlencoded and a filename* parameter is added
Parameters
Name | Types | Description |
---|---|---|
filename | String |
Returns
String
# exports.etag(body, encoding)
private method
Return strong ETag for body
.
Parameters
Name | Types | Description |
---|---|---|
body | String |
Buffer |
encoding | String |
Returns
String
# exports.flatten(arr)
private method
Flatten the given arr
.
Parameters
Name | Types | Description |
---|---|---|
arr | Array |
Returns
Array
# exports.isAbsolute(path)
private method
Check if path
looks absolute.
Parameters
Name | Types | Description |
---|---|---|
path | String |
Returns
Boolean
# exports.normalizeType(type)
private method
Normalize the given type
, for example "html" becomes "text/html".
Parameters
Name | Types | Description |
---|---|---|
type | String |
Returns
Object
# exports.normalizeTypes(types)
private method
Normalize types
, for example "html" becomes "text/html".
Parameters
Name | Types | Description |
---|---|---|
types | Array |
Returns
Array
# exports.wetag(body, encoding)
private method
Return weak ETag for body
.
Parameters
Name | Types | Description |
---|---|---|
body | String |
Buffer |
encoding | String |
Returns
String
# parseExtendedQueryString(str)
private method
Parse an extended query string with qs.
Parameters
Name | Types | Description |
---|---|---|
str | String |
Returns
Object
# setCharset(type, charset)
private method
Set the charset in a given Content-Type string.
Parameters
Name | Types | Description |
---|---|---|
type | String |
|
charset | String |
Returns
String
# lookup(name)
private method
Lookup view by the given name
Parameters
Name | Types | Description |
---|---|---|
name | string |
# render(options, callback)
private method
Render with the given options.
Parameters
Name | Types | Description |
---|---|---|
options | object |
|
callback | function |
# resolve(dir, file)
private method
Resolve the file within the given directory.
Parameters
Name | Types | Description |
---|---|---|
dir | string |
|
file | string |
# tryStat(path)
private method
Return a stat, maybe.
Parameters
Name | Types | Description |
---|---|---|
path | string |
Returns
fs.Stats
# View(name, options)
Initialize a new View
with the given name
. Options: - defaultEngine
the default template engine name - engines
template engine require() cache - root
root path for view lookup
Parameters
Name | Types | Description |
---|---|---|
name | string |
|
options | object |
# shouldHaveBody(buf)
Assert that a supertest response has a specific body.
Parameters
Name | Types | Description |
---|---|---|
buf | Buffer |
# shouldHaveHeader(header)
Assert that a supertest response does have a header.
Parameters
Name | Types | Description |
---|---|---|
header | string |
Header name to check |
# shouldNotHaveHeader(header)
Assert that a supertest response does not have a header.
Parameters
Name | Types | Description |
---|---|---|
header | string |
Header name to check |