HTTP server
Functions for starting the server, CORS, proxies, redirects and error handling.
On this page
Functions and settings of the HTTP server that are not routes: HTTP(), CORS(), PROXY(), REDIRECT(), error pages and error helpers. The guide HTTP server: CORS, proxy and errors explains them with examples; this page is the exact reference. The sitemap has its own page: Sitemap.
API
method
HTTP(mode, [options], [middleware])
Starts the HTTP server and loads the application.
HTTP(mode, [options], [middleware])| Parameter | Type | Description |
|---|---|---|
mode |
String |
'debug' or 'release'. |
options? |
Object |
Start options, see HTTP options. |
middleware? |
Function |
function(listen); the server listens only when you call listen(). Same as options.middleware. |
Returns undefined
Loads the configuration, the sitemap and all files of the application, then listens. mode is 'debug' or 'release'. Command-line arguments are read too: a number sets the port when options.port is empty, and any other argument that is not a URL and does not start with -- becomes unixsocket. The start script normally calls this function for you.
require('total4');
HTTP('release', { port: 8000 });
require('total4');
HTTP('release', { port: 8000 }, function(listen) {
// prepare something, then:
listen();
});
method
HTTPS(mode, options, [middleware])
Starts the application with an HTTPS server.
HTTPS(mode, options, [middleware])| Parameter | Type | Description |
|---|---|---|
mode |
String |
'debug' or 'release'. |
options |
Object |
Start options with https: { key, cert }. |
middleware? |
Function |
function(listen), as in HTTP(). |
Returns undefined
Works as HTTP() but creates a Node.js https server. options.https is passed to https.createServer(): a key or cert string that contains a dot is read as a file, other strings are decoded from base64. Other TLS options of Node.js can be added to the same object.
require('total4');
HTTPS('release', {
port: 443,
https: {
key: 'keys/server.key',
cert: 'keys/server.crt'
}
});
type
{ port, ip, unixsocket, unixsocket777, config, https, middleware, id }
The options object of HTTP() and HTTPS().
{ port, ip, unixsocket, unixsocket777, config, https, middleware, id }| Parameter | Type | Description |
|---|---|---|
port? |
Number |
The port. Default: CONF.default_port or 8000 |
ip? |
String |
The IP address. Default: CONF.default_ip or '0.0.0.0' |
unixsocket? |
String |
A Unix socket path to listen on instead of a port. |
unixsocket777? |
Boolean |
Sets the permissions of the socket file to 0777. Default: false |
config? |
Object |
Values copied into CONF before the configuration is used. |
https? |
Object |
{ key, cert } and other TLS options for HTTPS(). |
middleware? |
Function |
function(listen) that starts listening. |
id? |
String |
The identifier of the instance, kept in F.id. |
The same object is passed to the start script require('total4/release')(options) or require('total4/debug')(options), which hands it to HTTP(). The defaults of port and IP come from the config keys default_port, default_ip and default_unixsocket (see Configuration). ip: 'auto' listens on 0.0.0.0.
// index.js
const options = {};
options.port = 8000;
options.ip = '127.0.0.1';
options.config = { name: 'Shop' };
require('total4/release')(options);
property
F.server
The Node.js HTTP or HTTPS server of the application.
F.serverReturns http.Server
Created when the server starts. You can use it to read the address or to attach listeners of Node.js.
ON('ready', function() {
F.server.on('connection', function(socket) {
socket.setTimeout(60000);
});
});
property
F.port
The port the server listens on.
F.portReturns Number
Set when the server starts, from options.port, the command line, default_port or 8000.
ON('ready', function() {
console.log('Listening on ' + F.ip + ':' + F.port);
});
property
F.ip
The IP address the server listens on.
F.ipReturns String
Set when the server starts, from options.ip, default_ip or 0.0.0.0.
ON('ready', function() {
console.log(F.ip);
});
config
allow_performance : true
Tunes sockets of the HTTP server for many connections.
allow_performance : trueReturns Boolean
With true, each incoming socket gets setNoDelay(true) and keep-alive, and the global HTTP agent of Node.js can open up to 9999 sockets. Default: false.
allow_performance : true
method
CORS([url], [flags], [credentials])
Allows cross-origin requests to a path.
CORS([url], [flags], [credentials])| Parameter | Type | Description |
|---|---|---|
url? |
String |
The path, for example /api/*, or a list of origins. |
flags? |
Array |
Origins, methods, max age and credentials. |
credentials? |
Boolean |
Sends Access-Control-Allow-Credentials: true. flags can be true for the same effect. Default: false |
Returns Object The rule, with remove() to delete it.
Registers a CORS rule. The framework answers preflight OPTIONS requests with 200 and adds the Access-Control-* headers to the other requests. A url that ends with * or contains { covers all paths below it. In flags, origins are 'https://host', 'http://host' or '//host'; HTTP methods are 'get', 'post', 'put', 'patch', 'delete', 'head', 'options' (default: all); a number is the max age in seconds; true or 'credentials' allows credentials. Without origins, the config key default_cors is used, and without it every origin is allowed. A request from another origin gets an empty 404. Calling CORS() again with the same URL extends the existing rule.
Without arguments, every path and every origin is allowed. A first argument that starts with http:// or https:// is a comma-separated list of origins allowed on every path.
exports.install = function() {
CORS('/api/*', ['https://app.example.com', 'get', 'post', 'credentials']);
};
CORS();
CORS('https://app.example.com, https://admin.example.com');
var rule = CORS('/public/*');
// ...
rule.remove();
config
default_cors_maxage : 120
How long browsers can cache a CORS preflight answer.
default_cors_maxage : 120Returns Number
The value of Access-Control-Max-Age in seconds for CORS() rules without their own number flag. Default: 120.
default_cors_maxage : 600
method
PROXY(url, target, [copypath], [before], [after], [check], [timeout])
Forwards requests under a path to another server.
PROXY(url, target, [copypath], [before], [after], [check], [timeout])| Parameter | Type | Description |
|---|---|---|
url |
String |
The path prefix, ending with /. |
target |
String |
The target address or Unix socket path. null removes the proxy. |
copypath? |
Boolean|String |
true, false, 'replace' or 'extend'. |
before? |
Function |
function(uri, req, res) called before the request is sent; change uri.headers or uri.path here. |
after? |
Function |
function(response) called with the response of the target before it is sent to the client. |
check? |
Function |
function(req, res); return false to skip the proxy for this request. |
timeout? |
Number |
Timeout in milliseconds. Default: 10000 |
Returns Object The proxy, with remove() to delete it.
Every request whose path starts with url (lower case, ending with /) is sent to target and the answer is streamed back. The target is an http:// or https:// address or a Unix socket path. Proxies are checked before redirects, middleware and routes, and WebSocket connections are forwarded too. The request gets the headers X-Forwarded-For, X-Forwarded-Url and X-Forwarded-Host. When the target fails, the client gets the error page 503.
copypath: not set appends the whole request path to the path of the target; 'replace' and 'extend' remove the url prefix; true removes it only when the target has a path; false always uses only the path of the target. When copypath is a function, it is before, and the next argument is after. When check is a number, it is timeout. PROXY(url, null) removes the proxy.
exports.install = function() {
PROXY('/api/', 'http://127.0.0.1:8001', 'replace');
};
PROXY('/files/', 'https://files.example.com', function(uri, req, res) {
uri.headers['x-token'] = CONF.filestoken;
});
PROXY('/service/', '/tmp/service.socket', 'replace');
method
REDIRECT(from, to, [path], [permanent])
Redirects a host or a URL to another address.
REDIRECT(from, to, [path], [permanent])| Parameter | Type | Description |
|---|---|---|
from |
String |
A full address (protocol://host) or a path. |
to |
String |
The new address or path. |
path? |
Boolean |
For hosts: keep the path and query. For paths: make the redirect permanent. Default: false |
permanent? |
Boolean |
For hosts: answer 301. Default: false |
Returns undefined
With a full address in from (http://example.com), every request to that protocol and host is redirected before routing; path keeps the path and query, permanent answers 301 instead of 302.
With a path in from, a GET route is created that redirects to to and keeps the query string. In this form the third argument makes the redirect permanent, and an array in the third or fourth position is passed as route flags. A path to a static file (/docs.pdf) creates a file route instead.
REDIRECT('http://example.com', 'https://www.example.com', true, true);
exports.install = function() {
REDIRECT('/old-shop/', '/shop/', true);
};
method
res.redirect(url, [permanent])
Answers a request with a redirect.
res.redirect(url, [permanent])| Parameter | Type | Description |
|---|---|---|
url |
String |
The target address. |
permanent? |
Boolean |
Sends 301 Moved Permanently. Default: false |
Returns Response The response.
Sends 302, or 301 when permanent is true, with the Location header. Useful in middleware and file handlers, where there is no controller.
MIDDLEWARE('signin', function($) {
if ($.user)
$.next();
else
$.res.redirect('/signin/');
});
method
ROUTE('#code', action)
Declares the page for an error status.
ROUTE('#code', action)| Parameter | Type | Description |
|---|---|---|
code |
String |
The status, for example #404. |
action |
Function |
The action that answers. |
Returns undefined
A status route runs when the request ends with that status: #400, #401, #403, #404, #408, #409, #431, #500, #501 or #503. The controller has the problem or error in this.exception; set this.status yourself. Without a status route, the framework answers with its built-in HTML error page, or with JSON errors when default_errorbuilder_errors is on or the request is XHR (default_errorbuilder_forxhr). A timeout answers 503, a body over the size limit 431.
exports.install = function() {
ROUTE('#404', notfound);
ROUTE('#500', servererror);
};
function notfound() {
this.status = 404;
this.view('404');
}
function servererror() {
this.status = 500;
this.plain('Something went wrong');
}
config
default_errorbuilder_forxhr : true
Answers XHR requests with JSON errors instead of the HTML error page.
default_errorbuilder_forxhr : trueReturns Boolean
When a request with X-Requested-With: XMLHttpRequest ends with an error status and there is no status route, the answer is an ErrorBuilder JSON array. Default: true.
default_errorbuilder_forxhr : false
method
res.throw400([problem])
Answers with the error status 400 Bad Request.
res.throw400([problem])| Parameter | Type | Description |
|---|---|---|
problem? |
String |
A description passed to this.exception of the status route. |
Returns Response The response.
Runs the status route #400 or the built-in error page. For a HEAD request only the status is sent. It also emits the event error400. Use it in middleware and file handlers; in actions use controller.throw400().
MIDDLEWARE('apikey', function($) {
if ($.headers['x-api-key'] === CONF.apikey)
$.next();
else
$.res.throw400('Invalid API key');
});
method
res.throw401([problem])
Answers with the error status 401 Unauthorized.
res.throw401([problem])| Parameter | Type | Description |
|---|---|---|
problem? |
String |
A description passed to this.exception of the status route. |
Returns Response The response.
Runs the status route #401 or the built-in error page. For a HEAD request only the status is sent. It also emits the event error401. Use it in middleware and file handlers; in actions use controller.throw401().
MIDDLEWARE('admin', function($) {
if ($.user && $.user.sa)
$.next();
else
$.res.throw401();
});
method
res.throw403([problem])
Answers with the error status 403 Forbidden.
res.throw403([problem])| Parameter | Type | Description |
|---|---|---|
problem? |
String |
A description passed to this.exception of the status route. |
Returns Response The response.
Runs the status route #403 or the built-in error page. For a HEAD request only the status is sent. It also emits the event error403. Use it in middleware and file handlers; in actions use controller.throw403().
MIDDLEWARE('admin', function($) {
if ($.user && $.user.sa)
$.next();
else
$.res.throw403();
});
method
res.throw404([problem])
Answers with the error status 404 Not Found.
res.throw404([problem])| Parameter | Type | Description |
|---|---|---|
problem? |
String |
A description passed to this.exception of the status route. |
Returns Response The response.
Runs the status route #404 or the built-in error page. For a HEAD request only the status is sent. It also emits the event error404. Use it in middleware and file handlers; in actions use controller.throw404().
MIDDLEWARE('apikey', function($) {
if ($.headers['x-api-key'] === CONF.apikey)
$.next();
else
$.res.throw404('Invalid API key');
});
method
res.throw500([error])
Answers with the error status 500 Internal Server Error.
res.throw500([error])| Parameter | Type | Description |
|---|---|---|
error? |
Error |
The error; it is logged with F.error(). |
Returns Response The response.
Runs the status route #500 or the built-in error page. For a HEAD request only the status is sent. It also emits the event error500. Use it in middleware and file handlers; in actions use controller.throw500().
FILE('/report.pdf', function(req, res) {
makereport(function(err, filename) {
if (err)
res.throw500(err);
else
res.file(filename);
});
});
method
res.throw503([error])
Answers with the error status 503 Service Unavailable.
res.throw503([error])| Parameter | Type | Description |
|---|---|---|
error? |
Error |
The error; it is logged with F.error(). |
Returns Response The response.
Runs the status route #503 or the built-in error page. For a HEAD request only the status is sent. It also emits the event error503. Use it in middleware and file handlers; in actions use controller.throw503().
FILE('/report.pdf', function(req, res) {
makereport(function(err, filename) {
if (err)
res.throw503(err);
else
res.file(filename);
});
});
method
F.error(err, [name], [uri])
Logs an error.
F.error(err, [name], [uri])| Parameter | Type | Description |
|---|---|---|
err |
Error|String |
The error. Nothing happens when it is empty. |
name? |
String |
Where it happened, printed with the error. |
uri? |
String|Object |
The URL of the request. |
Returns undefined
Calls DEF.onError. The default handler prints the error to the console, keeps it in F.errors and emits the event error. Without arguments it returns a callback function(err) that logs errors.
Fs.readFile(filename, function(err, data) {
if (err) {
F.error(err, 'readconfig');
return;
}
// ...
});
method
ERROR([name])
Returns a callback that logs its error.
ERROR([name])| Parameter | Type | Description |
|---|---|---|
name? |
String |
A label printed with the error. |
Returns Function function(err).
The callback function(err) calls F.error(err, name) when err is not empty. Use it where you need a callback but do not care about the result.
F.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export'));
delegate
DEF.onError = function(err, name, uri)
The function that handles every error logged by the framework.
DEF.onError = function(err, name, uri)| Parameter | Type | Description |
|---|---|---|
err |
Error|String |
The error. |
name |
String |
The place where it happened. |
uri |
Object|String |
The URL of the request, when there is one. |
F.error(), errors in actions and throw500() all end here. The default prints ERROR ======= date: name ---> error (url) and the stack, keeps the last five errors in F.errors and emits ON('error'). Replace it to send errors elsewhere; you can call the original one from yours.
var onerror = DEF.onError;
DEF.onError = function(err, name, uri) {
onerror(err, name, uri);
RESTBuilder.POST('https://logs.example.com/', { error: err + '', name: name }).callback(NOOP);
};
property
F.errors
The last five logged errors.
F.errorsReturns Array
Each item is { error, name, url, date }. Filled by the default DEF.onError.
exports.install = function() {
ROUTE('GET /api/errors/', function() {
this.json(F.errors);
});
};
method
SUCCESS([success], [value])
Returns the { success, value, error } answer object.
SUCCESS([success], [value])| Parameter | Type | Description |
|---|---|---|
success? |
Boolean|Error|ErrorBuilder|Function |
The result, an error, or a callback to wrap. Default: true |
value? |
Object |
A value for the value property. |
Returns Object { success, value, error }.
SUCCESS() gives { success: true }. SUCCESS(true, value) adds value (a schema instance is cleaned first). An Error or an ErrorBuilder with errors gives success: false and the text of the error in error. With a function, it returns a callback (err, value) that calls your function with SUCCESS(err, value) as the second argument. The function returns one shared object, so read or send it at once and do not keep it.
function save() {
var self = this;
NOSQL('orders').insert(self.body).callback(function(err) {
self.json(SUCCESS(err ? false : true));
});
}
this.json(SUCCESS(true, { id: UID() }));
method
FINISHED(stream, callback)
Calls a function when a request, a response or a stream ends.
FINISHED(stream, callback)| Parameter | Type | Description |
|---|---|---|
stream |
Stream|Request|Response |
What to watch. |
callback |
Function |
Called once at the end. |
Returns undefined
For a request or a response, the callback runs when its socket closes or fails, also when the client goes away. For other streams it runs when they end. Several callbacks can wait on one stream.
function report() {
var self = this;
var filename = PATH.temp(UID() + '.pdf');
makepdf(filename, function() {
FINISHED(self.res, () => F.Fs.unlink(filename, NOOP));
self.res.file(filename, 'report.pdf');
});
}
method
DESTROY(stream)
Destroys a stream and closes its file descriptor.
DESTROY(stream)| Parameter | Type | Description |
|---|---|---|
stream |
Stream |
The stream. |
Returns Stream The same stream.
A file read stream is destroyed and closed even if it is still opening. Other Node.js streams are destroyed with destroy().
var stream = F.Fs.createReadStream(filename);
FINISHED(this.res, () => DESTROY(stream));
stream.pipe(this.res);
property
EMPTYCONTROLLER
A controller without a request.
EMPTYCONTROLLERReturns Controller
The framework uses it for VIEW() and MAIL(), where there is no HTTP request. Its req has an empty URL, query, body and files. You can use it to call controller helpers outside a request; do not answer with it.
var url = EMPTYCONTROLLER.sitemap_url('detail', 'book');