Friday 24 February 2012

cross-site xmlhttprequest with CORS

cross-site xmlhttprequest with CORS

 

CORS defines how browsers and servers communicate when accessing sources across origins using HTTP headers to allow both the browser and the server to know enough about each other to determine if the request or response should succeed or fail.





withCredentials

Standard CORS requests do not send or set any cookies by default. In order to include cookies as part of the request, you need to set the XmlHttpRequest’s .withCredentials property to true:
xhr.withCredentials = true;
In order for this to work, the server must also enable credentials by setting the Access-Control-Allow-Credentials response header to “true”. See the server section for details.
Access-Control-Allow-Credentials: true
 
 


http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
http://www.html5rocks.com/en/tutorials/cors/
http://enable-cors.org/


======================
ADD HEADERS

For Apache

Apache can be configured to expose this header using mod_headers, this is enabled by default in Apache however you may want to ensure it's enabled by running the following command:

a2enmod headers

To expose the header you simply add the following line inside , , or sections, or within a .htaccess file:

Header set Access-Control-Allow-Origin *

* = ALL ...you can specify a domain only

Note: you can also use add rather than set, but be aware that add can add the header multiple times, so it's likely safer to use set. Eventually, you may need to reload Apache to make sure your changes are applied.



======================




// Create the XHR object.
function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // XHR for Chrome/Safari/Firefox.
    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.
function getTitle(text) {
  return text.match('(.*)?')[1];
}

// Make the actual CORS request.
function makeCorsRequest() {
  // bibliographica.org supports CORS.
  var url = 'http://bibliographica.org/';

  var xhr = createCORSRequest('GET', url);
  if (!xhr) {
    alert('CORS not supported');
    return;
  }

  // Response handlers.
  xhr.onload = function() {
    var text = xhr.responseText;
    var title = getTitle(text);
    alert('Response from CORS request to ' + url + ': ' + title);
  };

  xhr.onerror = function() {
    alert('Woops, there was an error making the request.');
  };

  xhr.send();
}

No comments:

Post a Comment