Skip to content

Instantly share code, notes, and snippets.

@jinweijie
Forked from isorna/cors.helper.js
Last active October 16, 2015 04:13
Show Gist options
  • Save jinweijie/11e731c9b07f53bdf52f to your computer and use it in GitHub Desktop.
Save jinweijie/11e731c9b07f53bdf52f to your computer and use it in GitHub Desktop.
function createCORSRequest (poMethod, pcURL) {
var oXHR = new XMLHttpRequest();
if ('withCredentials' in oXHR) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
oXHR.open(poMethod, pcURL, true);
} else if (typeof XDomainRequest != 'undefined') {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
oXHR = new XDomainRequest();
oXHR.open(poMethod, pcURL);
} else {
// Otherwise, CORS is not supported by the browser.
oXHR = null;
}
return oXHR;
}
function makeCorsRequest (pcURL) {
var oXHR = createCORSRequest('GET', pcURL);
if (!oXHR) {
throw new Error('CORS not supported');
} else {
/* For windows authentication, must be withCredentials = true*/
oXHR.withCredentials = true;
oXHR.onload = function() {
var cResponseText = oXHR.responseText;
console.log(cResponseText);
// process the response.
};
oXHR.onerror = function() {
console.error('There was an error! ' + oXHR.statusText);
};
oXHR.send();
}
}
makeCorsRequest ('http://localhost:9000/api/Values');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment