Created
February 12, 2018 06:20
-
-
Save chanakaDe/2b0652850b0f2b9035204e7eceee8aec to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
// Helper method to parse the title tag from the response. | |
function getTitle(text) { | |
return text.match('<title>(.*)?</title>')[1]; | |
} | |
// Make the actual CORS request. | |
function makeCorsRequest() { | |
// This is a sample server that supports CORS. | |
// var url = 'http://icanhazip.com'; | |
var url = 'http://smart-ip.net/myip'; | |
var xhr = createCORSRequest('GET', url); | |
if (!xhr) { | |
alert('CORS not supported'); | |
return; | |
} | |
// Response handlers. | |
xhr.onload = function () { | |
var text = xhr.responseText; | |
console.log(text); | |
}; | |
xhr.onerror = function () { | |
alert('Woops, there was an error making the request.'); | |
}; | |
xhr.send(); | |
} | |
makeCorsRequest(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment