-
-
Save rightfold/b265bb1ace0e7b44478f to your computer and use it in GitHub Desktop.
This file contains 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 parseHeaders(data) { | |
const headers = { }; | |
const lines = data.split('\n'); | |
for (let i = 0; i < lines.length; ++i) { | |
const colonPos = lines[i].indexOf(':'); | |
const key = lines[i].slice(0, colonPos).toLowerCase().trim(); | |
const value = lines[i].slice(colonPos + 1).trim(); | |
if (key === '') { | |
continue; | |
} | |
if (headers.hasOwnProperty(key)) { | |
headers[key] += ', ' + value; | |
} else { | |
headers[key] = value; | |
} | |
} | |
return headers; | |
} | |
class AjaxError extends Error { } | |
class AjaxAbortedError extends Error { } | |
function Request(method, url, headers, body) { | |
this.method = method; | |
this.url = url; | |
this.headers = headers !== void 0 ? headers : { }; | |
this.body = body !== void 0 ? body : null; | |
} | |
function Response(status, headers, body) { | |
this.status = status; | |
this.headers = headers; | |
this.body = body; | |
} | |
function ajax(request) { | |
return new Promise(function(resolve, reject) { | |
const ajax = new XMLHttpRequest(); | |
ajax.addEventListener('load', function() { | |
const headers = parseHeaders(ajax.getAllResponseHeaders()); | |
const response = new Response(ajax.status, headers, ajax.responseText); | |
resolve(response); | |
}); | |
ajax.addEventListener('error', function() { | |
reject(new AjaxError()); | |
}); | |
ajax.addEventListener('abort', function() { | |
reject(new AjaxAbortedError()); | |
}); | |
for (let key in request.headers) { | |
if (request.headers.hasOwnProperty(key)) { | |
ajax.setRequestHeader(key, request.headers[key]); | |
} | |
} | |
ajax.open(request.method, request.url); | |
ajax.send(request.body); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment