Cross Origin Resource Sharing

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the resource originated.

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

jQuery AJAX is an excellent method for displaying the response object of a JSON API within an HTML page without reloading or using an iFrame.

Example:

I will first show you sample jQuery Ajax syntax followed by the html for the div container which will display the output.

As you can see, it is possible to query a RESTful JSON API and output the contents directly on a web page (all client-side, in browser). The example above even passes a token through the header to authenticate access to a restricted page.

To make the request to the API server possible, two important steps are taken:

1. /api/v1/.htaccess

Header add Access-Control-Allow-Headers "X-Requested-With, Origin, Content-Type, token, dlid, nonce"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

2. /api/v1/index.php

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  // return only the headers and not the content
  // only allow CORS if we're doing a GET - i.e. no saving for now.
  if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) && $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'GET') {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: X-Requested-With');
  }
  exit;
}

Soon, cAPI will include functionality in the Services Control Panel to define which domains are allowed to make CORS requests.