THE SITUATION:
I am making an app in AngularJs. I need to make a CORS request to fetch data from an api on a different address.
On the api i output a very simple json, for test purpose:
[{"id":0,"name":"First"},{"id":1,"name":"Second"},{"id":2,"name":"Third"}]
I need to fetch these data and display on my app.
$HTTP CALL:
making the $http call i get the following error, because the api is on a different domain:
No 'Access-Control-Allow-Origin' header is present on the requested resource
CORS REQUEST - THE CODE:
// 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];
}
// Make 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('Woops, there was an error making the request.');
};
xhr.send();
}
When i run the function makeCorsRequest i get the alert called by xhr.onerror
But i have no clues why it isn't working.
THE API:
This is the very simple php function in the api, for test purpose:
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 QUESTION:
How can i make a simple CORS request?
EDIT - THE SOLUTION:
This is how it looks the api after having edited it, thanks to the reply:
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);
}
In general: You just make a normal request using XMLHttpRequest
. The browser will handle the rest. (The exception is in old browsers which either don't support CORS or which require you to use XDomainRequest
instead of XMLHttpRequest
— but you seem to be accounting for that already).
The error message you are getting indicates that you are not getting a CORS response, so the browser doesn't have permission to give the other site's data to your JavaScript.
You need to include Access-Control-Allow-Origin: *
(or something more specific) in the HTTP response to the cross-origin request.