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.


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


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 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., url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();, 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() {
  // supports CORS.
  var url = '';

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

  // 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.');


No comments:

Post a Comment