How to make CORS request from Chrome/IE/Firefox?

It is sometimes required to quickly check weather you are able to make a RESTful request to the API. You can quickly make a CORS request from Chrome console or IE console or Firefox console without using any tool. It will also help to quickly test weather there is any preflight or CORS error or not.



Copy the below two javascript functions to the browser console and hit enter.

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    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;
}

function makeCorsRequest(url) {
  // This is a sample server that supports CORS.

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

  // Response handlers.
  xhr.onload = function() {
    var text = xhr.responseText;
    console.log('Response from CORS request to ' + url);
  };

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

  xhr.send();
}

Now, you can make a CORS request by calling the makeCorsRequest(<url>) function.

makeCorsRequest("https://example.com/api/GetResults?id=1");