Skip to content

Instantly share code, notes, and snippets.

@phothinmg
Forked from lddefensor/makeRequest.js
Created December 31, 2024 20:36
Show Gist options
  • Save phothinmg/18d3362403d1506c425141f696b56505 to your computer and use it in GitHub Desktop.
Save phothinmg/18d3362403d1506c425141f696b56505 to your computer and use it in GitHub Desktop.
Pure JS HTTPRequest Implementation using Promise
function makeRequest(method, url, data){
return new Promise(
function(resolve, reject)
{
var http = new XMLHttpRequest();
http.open(method, url);
http.onload= function(){
if(this.status >= 200 && this.status < 300)
{
var response = http.response;
try
{
response = JSON.parse(response);
resolve(response);
}
catch (error)
{
reject({
status: this.status,
statusText: error
});
}
}
else
{
reject({
status: this.status,
statusText: http.statusText
});
}
};
http.onerror = function(){
reject({
status: this.status,
statusText: http.statusText
});
};
if(method === 'POST')
{
data = data || {};
http.send(JSON.stringify(data));
}
else http.send();
}
);
}
function getRequest(url){
return makeRequest('GET', url);
}
function postRequest(url, data){
return makeRequest('POST', url, data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment