Simplified demo.html; show proxyError on error

This commit is contained in:
Rob Wu
2013-08-29 17:09:20 +02:00
parent cd97423db9
commit a784fc96f8
2 changed files with 21 additions and 34 deletions

View File

@@ -66,21 +66,19 @@ textarea {
<script>
var protocol = location.protocol === 'http:' ? 'http:' : 'https:';
var cors_api_url = protocol + '//cors-anywhere.herokuapp.com/';
var cors_api_redirect_cache = {};
function doCORSRequest(options, redirectCount) {
function doCORSRequest(options, printResult) {
var x = new XMLHttpRequest();
x.open(options.method, cors_api_url + options.url);
x.onload = function() {
if (x.status >= 200 && x.status < 300 || x.status === 304) {
options.success(options, x.status, x.statusText, x.responseText);
} else {
options.error(options, x.status, x.statusText);
}
};
x.onerror = function() {
options.error(options, x.status, x.statusText);
x.onload = x.onerror = function() {
printResult(
options.method + ' ' + options.url + '\n' +
x.status + ' ' + x.statusText + '\n\n' +
(x.responseText || '')
);
};
if (/^POST/i.test(options.method)) {
x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
x.send(options.data);
}
@@ -89,33 +87,22 @@ textarea {
var urlField = document.getElementById('url');
var dataField = document.getElementById('data');
var outputField = document.getElementById('output');
document.getElementById('get').onclick = function(e) {
e.preventDefault();
doCORSRequest({
method: 'GET',
url: urlField.value,
success: onSuccess,
error: onError
});
};
document.getElementById('get').onclick =
document.getElementById('post').onclick = function(e) {
e.preventDefault();
doCORSRequest({
method: 'POST',
method: this.id === 'post' ? 'POST' : 'GET',
url: urlField.value,
data: dataField.value,
success: onSuccess,
error: onError
data: dataField.value
}, function printResult(result) {
outputField.value = result;
});
};
function onSuccess(options, statusCode, statusText, responseText) {
outputField.value = options.method + ' ' + options.url + '\n' + statusCode + ' ' + statusText + '\n\n' + responseText;
}
function onError(options, statusCode, statusText) {
outputField.value = options.method + ' ' + options.url + '\n' + statusCode + ' ' + statusText;
}
})();
if (typeof console === 'object') {
console.log('// To test a local CORS Anywhere server, set cors_api_url. For example:');
console.log('cors_api_url = "http://localhost:8080/"');
}
</script>
</body>
</html>