Skip to content

Instantly share code, notes, and snippets.

@jacobgardner
Last active March 20, 2017 18:52
Show Gist options
  • Save jacobgardner/b8ad19bcacf336b4eb27ada802cc94b8 to your computer and use it in GitHub Desktop.
Save jacobgardner/b8ad19bcacf336b4eb27ada802cc94b8 to your computer and use it in GitHub Desktop.
function request(method, endpoint, {payload, headers: {}} = {}) {
return new Promise((resolve, reject) => {
const ajaxRequest = new XMLHTTPRequest();
ajaxRequest.open(method, endpoint);
for (const key of Object.keys(headers)) {
ajaxRequest.setRequestHeader(key, headers[key]);
}
ajaxRequest.onreadystatechange = () => {
if(ajaxRequest.readyState === 4) {
if (ajaxRequest.status >= 400) {
reject(new Error(ajaxRequest.responseText));
} else {
resolve(ajaxRequest);
}
}
};
if (payload) {
ajaxRequest.send(payload);
} else {
ajaxRequest.send();
}
});
}
request('POST', 'thatEndpoint.php', {
headers: {
'Content-Type': 'multipart/form-data',
}
}).then((response) => {
if (response.status === 302) {
const newLocation = response.getResponseHeader('Location');
// redirect or whatever
} else {
// Show errors from response.
}
}).catch((err) => {
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment