I have a problem with an ajax GET Request on REST Server. I made some tests and i will post them here.
In the REST Server i've two methods:
This is the javascript code that performs the ajax request on the server (on the resource_new_get method):
app.updateResources = function(data)
{
if(data == null)
{
$.ajax(
{
url: 'http://<remotehost>/api/events/resource_new?id_event=<ID>',
dataType: 'json',
success: function(d)
{
console.log(d);
},
error: function(error)
{
console.log('error ' + JSON.stringify(error));
}
});
}
else
{
...
}
};
In this case, ajax request runs fine and i'm able to obtain the json response from the server.
But when i perform a request to resource_api_new adding custom headers as follows:
app.updateResources = function(data)
{
if(data == null)
{
$.ajax(
{
url: 'http://<remotehost>/api/events/resource_api_new?id_event=<ID>',
dataType: 'json',
headers: {'Api-Key': '<my_token>'},
success: function(d)
{
console.log(d);
},
error: function(error)
{
console.log('error ' + JSON.stringify(error));
}
});
}
else
{
...
}
};
Which needs a token identified by 'Api-Key' key in the headers to return the json response, error function fires and returns this:
XMLHttpRequest cannot load http://<remotehost>/v2/index.php/api/events/resource_api_new?id_event=<ID>. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://<myhost>' is therefore not allowed access. The response had HTTP status code 404.
When i add at the top of the php file, that contains REST Server, the following line:
header('Access-Control-Allow-Origin: *');
The response return "simply" HTTP status code 404, as follows:
XMLHttpRequest cannot load http://api.gtmasterclub.it/v2/index.php/api/eventi/relatori_api_new?id_evento=159. Response for preflight has invalid HTTP status code 404
I found the solution at the problem:
The Api-Key Header was not included in Access-Control-Allow-Headers and i added simply this:
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Api-Key
Also, i added a constructor to handle the OPTIONS request, as explained here:
HTTP OPTIONS error in Phil Sturgeon's Codeigniter Restserver and Backbone.js
function __construct() {
parent::__construct();
$method = $_SERVER['REQUEST_METHOD'];
if($method == "OPTIONS") {
log_message('debug', 'method OPTIONS called');
die();
}
}
And, in the client script i deleted:
data-type: 'json',