I'm trying to make an XMLHttpRequest to retrieve an XML document located on a remote server. The application I'm developing will eventually be hosted on the same server that the request needs to access, though at the moment I'm developing it from another location. When I make the request from Javascript, I receive an error stating:
XMLHttpRequest cannot load [url] No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
Many similar questions have been posted here already (such as here) regarding this and the general solution seems to be making modifications to the server to add additional headers to allow external access. However in my current situation, modifying the server is not an option so I am wondering if there is any other client-side workaround I can implement to complete this request. If possible I would like to be able to find a solution without using jQuery.
Here is the code I'm using to make the request:
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function () {
responseHandler(request);
};
request.send(null);
For the moment I came up with a workaround using a PHP proxy to make the request (so my Javascript call goes to the locally-hosted PHP script, which then retrieves the XML file from the server) because PHP does not seem to enforce this access control policy like Javascript does. In PHP, I make the request like this:
header('Content-type: application/xml');
header("Access-Control-Allow-Origin: *");
echo file_get_contents($url);
I had to add the headers on the PHP proxy so that I can test the application on multiple devices running on my local network.
Any suggestions would be much appreciated.