I'm having a strange issue in trying to migrate a 3rd-party page retrieval from PHP (using cURL) into Javascript.
Using PHP I can retrieve the page with no issues, but with Javascript I keep getting the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access.
I've searched a fair bit and all I can find are answers explaining that the Access-Control-Allow-Origin header has to be set on the server side and if it isn't then there's basically no way to retrieve the page.
But in this case I know the server is willing to give up the loot, because the PHP function successfully retrieves the page. It's only when I request it in the Javascript function that it throws that error.
Here's the (working) PHP function:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_URL => <3rd party URL>,
));
$resp = curl_exec($curl);
curl_close($curl);
...and here's the (not-working) Javascript function:
var getHTML = function ( url, callback ) {
// Feature detection
if ( !window.XMLHttpRequest ) return;
// Create new request
var xhr = new XMLHttpRequest();
// Setup callback
xhr.onload = function() {
if ( callback && typeof( callback ) === 'function' ) {
callback( this.responseXML );
}
}
// Get the HTML
xhr.open( 'GET', url );
xhr.responseType = 'document';
xhr.send();
};
getHTML( <3rd party URL>, function (resp) {
console.log(resp);
});