JavaScript Client to Test CORS: Difference between revisions
Jump to navigation
Jump to search
Line 8: | Line 8: | ||
<!DOCTYPE html> | <!DOCTYPE html> | ||
<html> | <html> | ||
<head> | |||
<script> | |||
var stageUrl = 'https://c2shocjc3d.execute-api.us-west-2.amazonaws.com/v17'; | |||
function invokeOptions() { | |||
invoke('OPTIONS'); | |||
} | |||
function invokeGet() { | |||
invoke('GET'); | |||
} | |||
function invoke(method) { | |||
var url = stageUrl + '/inhabitants'; | |||
var xhr = createCORSRequest(method, url); | |||
xhr.withCredentials = false; | |||
xhr.onload = function() { | |||
document.getElementById("result").innerHTML = xhr.responseText; | |||
}; | |||
xhr.onerror = function() { | |||
document.getElementById("result").innerHTML = "ERROR: " + xhr.responseText; | |||
}; | |||
xhr.send(); | |||
} | |||
var createCORSRequest = function(method, url) { | |||
var | var xhr = new XMLHttpRequest(); | ||
xhr.overrideMimeType("application/json"); | |||
if ("withCredentials" in xhr) { | |||
xhr.open(method, url, true); | |||
} | |||
else { | |||
// CORS not supported. | |||
xhr = null; | |||
} | |||
return xhr; | |||
}; | |||
</script> | </script> | ||
</head> | </head> | ||
<body> | |||
<h1>CORS TEST</h1> | |||
<button type="button" onclick="invokeOptions()">Invoke OPTIONS</button> | |||
<br> | |||
<br> | |||
<button type="button" onclick="invokeGet()">Invoke GET</button> | |||
<p id="result"></p> | |||
</body> | |||
</html> | </html></syntaxhighlight> | ||
</syntaxhighlight> |
Revision as of 23:55, 29 March 2019
Internal
Example
<!DOCTYPE html>
<html>
<head>
<script>
var stageUrl = 'https://c2shocjc3d.execute-api.us-west-2.amazonaws.com/v17';
function invokeOptions() {
invoke('OPTIONS');
}
function invokeGet() {
invoke('GET');
}
function invoke(method) {
var url = stageUrl + '/inhabitants';
var xhr = createCORSRequest(method, url);
xhr.withCredentials = false;
xhr.onload = function() {
document.getElementById("result").innerHTML = xhr.responseText;
};
xhr.onerror = function() {
document.getElementById("result").innerHTML = "ERROR: " + xhr.responseText;
};
xhr.send();
}
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
xhr.overrideMimeType("application/json");
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
}
else {
// CORS not supported.
xhr = null;
}
return xhr;
};
</script>
</head>
<body>
<h1>CORS TEST</h1>
<button type="button" onclick="invokeOptions()">Invoke OPTIONS</button>
<br>
<br>
<button type="button" onclick="invokeGet()">Invoke GET</button>
<p id="result"></p>
</body>
</html>