Responses

Responses

When using add_path to add a handler for a path, it is possible to change several aspects of the response, including the HTTP Status code, the response headers, as well as returning buffers instead of strings. The functionality to do so are available in the context argument.

Sending headers

The function context.response.set_header() Can be used to set headers in the response.

global.server.add_path("demos/headers", function(_context) {
	_context.response.set_header("Access-Control-Allow-Origin", "*"); 
	_context.response.send_string("OK");
});

In the above example, the endpoint sets the header Access-Control-Allow-Origin to the value *.

Json

A convenient function is provided to send structs or other serializable things as JSON.

global.server.add_path("demos/json", function(_context) {
	_context.response.send_json({a: 1, b: 2});
});

In the above example, a struct is being sent. This will get automatically run through json_stringify() and the right content-type headers will be set.

Empty

Sometimes an empty response is needed. This is a special-type of HTTP response that has no body (not even a string).

global.server.add_path("demos/empty", function(_context) {
	_context.response.send_empty();
});

In the above example, no response body will be sent. The status code of 204 will be used by default, unless otherwise specified. Some servers should send such a response for actions that result in no output.

Status Codes

The various send functions have optional arguments to set the status code. The default in most cases is 200, other than the send_empty() which defaults to 204.

global.server.add_path("demos/empty", function(_context) {
	_context.response.send_json({error: not found}, 400);
});

In the above example, a JSON is being sent with a status code of 400. This is useful for some clients that read the status code to decide if an action has succeded or not.