Did you know ... Search Documentation:
http_cors.pl -- Enable CORS: Cross-Origin Resource Sharing
PublicShow source

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
See also
- http://en.wikipedia.org/wiki/Cross-site_scripting for understanding Cross-site scripting.
- http://www.w3.org/TR/cors/ for understanding CORS
Source cors_enable is det
Emit the HTTP header 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).
Source cors_enable(+Request, +Options) is det
CORS reply to a Preflight OPTIONS request. Request is the HTTP request. Options provides:
methods(+List)
List of supported HTTP methods. The default is GET, only allowing for read requests.
headers(+List)
List of headers the client asks for and we allow. The default is to simply echo what has been requested for.

Both methods and headers may use Prolog friendly syntax, e.g., get for a method and content_type for a header.

See also
- http://www.html5rocks.com/en/tutorials/cors/