3.1.0Module exports.
Module exports.
Module exports.
Module exports.
Module exports.
Module exports.
Re-usable server.
(express)
Associated express application
({name: string, useHttps: boolean, useHttp2: boolean, securityOptions: object, callback: function (Server), showPublicIP: boolean, silent: boolean, gracefulClose: boolean, autoRun: boolean}
= {name:'Server',useHttps:false,securityOptions:{},callback:(server)=>{},showPublicIP:false,silent:false,gracefulClose:true,autoRun:false})
Options including the server's name, HTTPS, options needed for the HTTPs server (public keys and certificates), callback called within the
listen
event and whether it should show its public
IP and whether it needs to be silent (
which won't affect the public IP log
) and if it should run automatically upon being instantiated.
Get the associated application (Express instance).
express:
Associated Express instance
Set the Express application associated to the router.
(express)
Express app
Changes the HTTPS flag without affecting the server instance.
Use this method at your own risk!
(boolean)
New flag
See if whether or not the server is using HTTP/2.
boolean:
Version 2 flag
Changes the HTTP version flag without affecting the server instance.
Use this method at your own risk!
(boolean)
New flag
Get the server options (that is the ones used for the HTTPS and HTTP/2 mode).
Object:
Options
Change the server options without affecting the server instance.
Use this method at your own risk!
(Object)
New options
Get the server's instance.
(http.Server | https.Server | http2.Server):
Server instance
Change the server's instance.
However it's recommended to restart the server otherwise the event handlers won't work properly.
((http.Server | https.Server | http2.Server))
New server instance
Run/start the server.
(http.Server | https.Server | http2.Server):
Server
Create a middleware to parse json and urlencoded bodies.
(object?)
function:
Initialize a new View with the given name.
Options:
defaultEngine the default template engine nameengines template engine require() cacheroot root path for view lookupInitialize Route with the given path,
(String)
Initialize a new Router with the given options.
(Object?)
Router:
which is an callable function
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(); }); });
app:
for chaining
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.
(any)
Request prototype.
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().
(String)
String:
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"
(String | Array | Boolean):
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.
(number | array):
Return the value of param name when present or defaultValue.
To utilize request bodies, req.body
should be an object. This can be done by using
the bodyParser() middleware.
(String)
(Mixed?)
String:
Check if the incoming request contains the "Content-Type"
header field, and it contains the give 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
false | null)(any)
(String | false | null):
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.
String:
Short-hand for:
req.protocol === 'https'
Boolean:
Return the remote address from the trusted proxy.
The is the remote address on the socket unless "trust proxy" is set.
String:
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.
Array:
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"].
Array:
Short-hand for url.parse(req.url).pathname.
String:
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.
String:
Check if the request is fresh, aka Last-Modified and/or the ETag still match.
Boolean:
Check if the request is stale, aka "Last-Modified" and / or the "ETag" for the resource has changed.
Boolean:
Check if the request was an XMLHttpRequest.
Boolean:
Response prototype.
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' });
(Object)
ServerResponse:
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.sentHeader
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 filenamesheaders object of headers to serve with filedotfiles serve dotfiles, defaulting to false; can be "allow" to send themOther 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.');
}
});
});
(any)
(any)
(any)
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.sentHeader
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 filenamesheaders object of headers to serve with filedotfiles serve dotfiles, defaulting to false; can be "allow" to send themOther 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.');
}
});
});
(any)
(any)
(any)
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
ocurred. 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().
(any)
(any)
(any)
(any)
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');
(String)
ServerResponse:
for chaining
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('<p>hey</p>');
},
'appliation/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('<p>hey</p>');
},
json: function(){
res.send({ message: 'hey' });
}
});
By default Express passes an Error
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.
(Object)
ServerResponse:
for chaining
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');
ServerResponse:
for chaining
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().
ServerResponse:
for chaining
Set cookie name to value, with the given options.
Options:
maxAge max-age in milliseconds, converted to expiressigned sign the cookiepath defaults to "/"Examples:
// "Remember Me" for 15 minutes res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
// save as above res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
ServerResponse:
for chaining
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');
(String)
ServerResponse:
for chaining
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
(any)
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 cachefilename filename of the view being rendered(any)
(any)
(any)
Create a logger middleware.
Function:
middleware
Define a format with the given name.
Define a token function with the given name, and callback fn(req, res).
Compile a format string into a function.
(string)
function:
Create a basic buffering stream.
Lookup and compile a named format function.
(string)
function:
JSON parser.
Raw parser.
Text parser.
URL-encoded parser.
Create a middleware to parse JSON bodies.
(object?)
function:
Create a middleware to parse urlencoded bodies.
(object?)
function: