Saturday, 17 August 2013

Cross Domain XHR failing inspite of Access-Control-Allow-Origin header

Cross Domain XHR failing inspite of Access-Control-Allow-Origin header

I am new to XHR and am trying to solve a simple use case. I have a web
server, from where my javascript would fetch data. But instead of serving
the data itself, the server would redirect the javascript XHR request to
an alternate location (for example a file on Amazon's S3) to fulfill the
request.
This brought me into the world of cross domain XHR, and I am unable to get
even a simple example working inspite of reading a bit about it. I am
adding "Access-Control-Allow-Origin: *" to the header in my main domain
which serves the web page containing the javascript. But it does not work.
What am I missing? I need this to work regardless of browser so am looking
for something the initial server can do other than serving as a proxy,
which defeats the purpose of offloading the request to S3.
Chrome : Gives "Exception: NetworkError: DOM Exception 19" on the second
call.
IE: Shows a warning but opens second url after confirmation.
Firefox: Just says "Exception: Faliure" on the second call.
Code follows for test.php:
<?php
header('Content-type: text/html');
header('Access-Control-Allow-Origin: *');
?>
<!DOCTYPE html>
<html>
<header>
<script type="text/javascript">
var request;
var url1 = "data/file.csv";
var url2 = "http://stackoverflow.com/users/1293955/ng-algo";
try
{
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
request = new XMLHttpRequest();
}
else {
// code for IE6, IE5
request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load data. 'false' indicates that further script
// is not executed until data is loaded and parsed
alert("Test1 with url: "+url1);
request.open('GET', url1, false);
request.send();
alert(request.responseText);
alert("Test2 with url: "+url2);
request.open('GET', url2, false);
request.send();
alert(request.responseText);
} catch (e) { alert("Exception: "+e.message); }
</script>
</header>
This is a test page
</html>

No comments:

Post a Comment