# 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
# 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('node:http') , https = require('node: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.
# defineGetter()
Check if the request is fresh, aka Last-Modified 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 |
# host()
Parse the "Host" header field to a host. When the "trust proxy" setting trusts the socket address, the "X-Forwarded-Host" header field will be trusted.
Returns
String
# 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
# 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
# query()
Parse the query string of req.url. This uses the "query parser" setting to parse the raw string into an object.
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))
Check if the given type(s) is acceptable, returning the best match when true, otherwise false, 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", 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'); // => false // Accept: text/*;q=.5, application/json req.accepts(['html', 'json']); req.accepts('html', 'json'); // => "json"
Parameters
| Name | Types | Description |
|---|---|---|
| type(s) | String |
Array |
Returns
String|Array|Boolean
# req.acceptsCharsets(charsets)
Checks if the specified charsets are acceptable based on the request's Accept-Charset header. Returns the best matching charset or an array of acceptable charsets. The charset argument(s) can be: - A single charset string (e.g., "utf-8") - Multiple charset strings as arguments (e.g., "utf-8", "iso-8859-1") - A comma-delimited list of charsets (e.g., "utf-8, iso-8859-1") Examples: // Accept-Charset: utf-8, iso-8859-1 req.acceptsCharsets('utf-8'); // => "utf-8" req.acceptsCharsets('utf-8', 'iso-8859-1'); // => "utf-8" req.acceptsCharsets('utf-8, utf-16'); // => "utf-8"
Parameters
| Name | Types | Description |
|---|---|---|
| charsets | ...String |
- The charset(s) to check against the Accept-Charset header. |
Returns
String|Array
- The best matching charset, or an array of acceptable charsets.
# req.acceptsEncodings(...encoding)
Check if the given encodings are accepted.
Parameters
| Name | Types | Description |
|---|---|---|
| ...encoding | String |
Returns
String|Array
# req.acceptsLanguages(...lang)
Check if the given langs 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. 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.contentType() when it does not contain "/", or set the Content-Type to type otherwise. When no mapping is found though mime.contentType(), the type is set to "application/octet-stream". 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', pages: [ 'http://api.example.com/users?page=1', 'http://api.example.com/users?page=2' ] });
Parameters
| Name | Types | Description |
|---|---|---|
| links | Object |
Returns
ServerResponse
# 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(). When the set header is "Content-Type", the type is expanded to include the charset if not present using mime.contentType().
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 the HTTP status code for the response. Expects an integer value between 100 and 999 inclusive. Throws an error if the provided status code is not an integer or if it's outside the allowable range.
Parameters
| Name | Types | Description |
|---|---|---|
| code | number |
- The HTTP status code to set. |
Returns
ServerResponse
- Returns itself for chaining methods.
# 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 |
# 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.etag(body, encoding)
private method
Return strong ETag for body.
Parameters
| Name | Types | Description |
|---|---|---|
| body | String |
Buffer |
| encoding | String |
Returns
String
# 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 |