HTTP server: CORS, proxy and errors
Start the HTTP server, allow cross-origin requests, forward and redirect requests, and design error pages.
This page covers the parts of the HTTP server that are not routes: starting the server, CORS, reverse proxies, redirects, the sitemap and error pages. Routes themselves are explained in Routing.
Starting the server
The start script calls HTTP() (or HTTPS() when you pass https keys). You can also call it yourself:
require('total4');
HTTP('release', {
port: 8000,
ip: '127.0.0.1',
config: { name: 'My app' }
});The first argument is the mode: 'debug' or 'release'. The options are:
| Option | What it does |
|---|---|
port | The port. Without it, the config key default_port is used, and then 8000 |
ip | The address to listen on. Without it, default_ip, and then 0.0.0.0 |
unixsocket | Listens on a Unix socket instead of a port |
unixsocket777 | Sets the permissions of the socket file to 0777 |
config | An object whose values are written into CONF |
https | { key, cert } for an HTTPS server |
middleware | function(listen) that decides when the server starts listening |
id | The identifier of the instance, kept in F.id |
A number on the command line (node index.js 8080) sets the port when the options do not have one. Any other argument that does not start with -- and is not a URL is used as a Unix socket path.
require('total4');
HTTPS('release', {
port: 443,
https: { key: 'keys/server.key', cert: 'keys/server.crt' }
});A key or cert that contains a dot is read as a file. Without a dot, it is decoded from base64. After the start, F.server is the Node.js server and F.port and F.ip hold the address.
CORS
CORS() lets browsers on other origins call your routes. It answers the preflight OPTIONS request itself with status 200.
exports.install = function() {
// All paths below /api/, from two origins, with cookies
CORS('/api/*', ['https://app.example.com', 'https://admin.example.com', 'credentials']);
ROUTE('GET /api/products/', products);
};The flags in the array are:
- Origins:
'https://example.com','http://example.com'or'//example.com'. - HTTP methods:
'get','post','put','patch','delete','head','options'. Without them, all methods are allowed. - A number: the
Access-Control-Max-Agein seconds (otherwisedefault_cors_maxage,120). trueor'credentials': sendsAccess-Control-Allow-Credentials: true.
Without origins, the config key default_cors gives the list. Without that, any origin is allowed. A request from an origin that is not on the list gets an empty 404.
Two short forms cover the whole application:
CORS(); // every path, every origin
CORS('https://app.example.com, https://example.com'); // every path, these originsThe routing flag cors (ROUTE('POST /api/orders/', fn, ['cors'])) registers a CORS rule for that one URL. CORS() returns an object with remove(), which deletes the rule again.
Reverse proxy
PROXY(url, target) sends every request whose path starts with url to another server and streams its answer back. The url must end with /.
exports.install = function() {
PROXY('/api/', 'http://127.0.0.1:8001');
};The target can be an http:// or https:// address or the path of a Unix socket. Proxies run before redirects, middleware and routes, and also forward WebSocket connections.
The third argument says how the path is passed on:
copypath | /api/users/?page=2 to http://server/v1 becomes |
|---|---|
| not set | /v1/api/users/?page=2 |
true, 'replace' or 'extend' | /v1/users/?page=2 (the prefix is removed) |
false | /v1 |
With a target without a path (http://server), 'replace' removes the prefix and true keeps it. The framework adds the headers X-Forwarded-For, X-Forwarded-Url and X-Forwarded-Host. If the target does not answer, the client gets the error page 503.
PROXY('/files/', 'http://127.0.0.1:8002', 'replace', function(uri, req, res) {
uri.headers['x-token'] = CONF.filestoken;
}, null, req => req.method === 'GET', 5000);Redirects
REDIRECT() has two forms. With full addresses it redirects a whole host, before routing:
// http://example.com/anything -> https://www.example.com/anything
REDIRECT('http://example.com', 'https://www.example.com', true, true);The third argument keeps the path and the query, the fourth makes the redirect permanent (301). With paths, it creates a route that redirects one URL and keeps the query string:
REDIRECT('/old-shop/', '/shop/', true); // 301 Moved Permanently
REDIRECT('/docs.pdf', 'https://cdn.example.com/docs.pdf');Error pages
Every error status first looks for a status route: #400, #401, #403, #404, #408, #409, #431, #500, #501 and #503.
exports.install = function() {
ROUTE('#404', notfound);
ROUTE('#500', servererror);
};
function notfound() {
this.status = 404;
this.view('404');
}
function servererror() {
this.status = 500;
this.view('500', { error: this.exception });
}Without such a route, the framework answers with its built-in HTML page. For XHR requests (default_errorbuilder_forxhr) and when default_errorbuilder_errors is on, it answers with JSON errors instead. In middleware and file handlers, res.throw404() and its siblings start the same process. See also Controllers.
F.error(err, name) logs an error, and ERROR(name) returns a callback that does it:
F.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export'));SUCCESS() builds the { success: true } object that $.success() also returns. FINISHED(stream, fn) calls fn when a request, response or stream ends, and DESTROY(stream) closes a stream.