THE SCENARIO:
I'm currently developing an AngularJs app that requires making a CORS request to fetch data from an api on a different domain.
The api I'm working with outputs a simple json structure for testing purposes:
[{"id":0,"name":"First"},{"id":1,"name":"Second"},{"id":2,"name":"Third"}]
My goal is to retrieve this data and display it within my app.
$HTTP CALL ISSUE:
When making the $http call, I encountered the following error related to the api being on a different domain:
No 'Access-Control-Allow-Origin' header is present on the requested resource
CORS REQUEST - THE IMPLEMENTATION:
// Function to create the XHR object.
$scope.createCORSRequest = function(method, url)
{
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr)
{
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
}
else if (typeof XDomainRequest != "undefined")
{
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
}
else
{
// CORS not supported.
xhr = null;
}
return xhr;
}
// Helper method to parse the title tag from the response.
$scope.getTitle = function(text)
{
return text.match('<title>(.*)?</title>')[1];
}
// Perform the actual CORS request.
$scope.makeCorsRequest = function()
{
var url = 'http://DOMAIN.COM/main/json_export_test';
var xhr = $scope.createCORSRequest('GET', url);
console.log('----- xhr -----');
console.log(xhr);
if (!xhr)
{
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function()
{
var text = xhr.responseText;
var title = $scope.getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function()
{
alert('Oops, there was an error making the request.');
};
xhr.send();
}
Upon running the makeCorsRequest function, the xhr.onerror alert is triggered, but I am unsure of the reason behind this issue.
THE API FUNCTIONALITY:
Below is the simple php function used within the api for testing purposes:
public function json_export_test()
{
$data = array(
array(
"id" => 0,
"name" => "First"
),
array(
"id" => 1,
"name" => "Second"
),
array(
"id" => 2,
"name" => "Third"
)
);
echo json_encode($data);
}
THE QUERY:
How can I successfully execute a CORS request?
EDIT - THE RESOLUTION:
Following the proposed solution, here's how the api code looks after modification:
public function json_export_test()
{
header('Access-Control-Allow-Origin: *');
$data = array(
array(
"id" => 0,
"name" => "First"
),
array(
"id" => 1,
"name" => "Second"
),
array(
"id" => 2,
"name" => "Third"
)
);
echo json_encode($data);
}