Did you know ... | Search Documentation: |
library(http/http_cors): Enable CORS: Cross-Origin Resource Sharing |
This small module allows for enabling Cross-Origin Resource Sharing (CORS) for a specific request. Typically, CORS is enabled for API services that you want to have useable from browser client code that is loaded from another domain. An example are the LOD and SPARQL services in ClioPatria.
Because CORS is a security risc (see references), it is disabled by default. It is enabled through the setting http:cors. The value of this setting is a list of domains that are allowed to access the service. Because * is used as a wildcard match, the value [*] allows access from anywhere.
Services for which CORS is relevant must call cors_enable/0
as part of the HTTP response, as shown below. Note that cors_enable/0
is a no-op if the setting http:cors is set to the empty list ([]
).
my_handler(Request) :- ...., cors_enable, reply_json(Response, []).
If a site uses a Preflight OPTIONS
request to
find the server's capabilities and access politics, cors_enable/2
can be used to formulate an appropriate reply. For example:
my_handler(Request) :- option(method(options), Request), !, cors_enable(Request, [ methods([get,post,delete]) ]), format('~n'). % 200 with empty body
Access-Control-Allow-Origin
using
domains from the setting http:cors. This this setting is []
(default), nothing is written. This predicate is typically used for
replying to API HTTP-request (e.g., replies to an AJAX request that
typically serve JSON or XML).OPTIONS
request. Request
is the HTTP request. Options provides:
GET
,
only allowing for read requests.
Both methods and headers may use Prolog friendly syntax, e.g.,
get
for a method and content_type
for a
header.