Search code examples
javascriptphpxmlhttprequest

PHP can read 3rd party URL, Javascript can't. Why?


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);
});

Solution

  • Browsers have built-in security mechanisms that don't allow you to make cross-site requests unless specific headers are set on the server. It's not about the server not willing to return the data but the browser which wants to protect your personal information. You can find more information in this post.