Last active
August 8, 2018 14:59
-
-
Save amitasaurus/e23e717e206e5de35bab401206f77830 to your computer and use it in GitHub Desktop.
Promise based XHR Wrapper
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
let _Http = obj => { | |
return new Promise((resolve, reject) => { | |
let xhr = new XMLHttpRequest(); | |
xhr.open(obj.method || "GET", obj.url); | |
if (obj.headers) { | |
Object.keys(obj.headers).forEach(key => { | |
xhr.setRequestHeader(key, obj.headers[key]); | |
}); | |
} | |
xhr.onload = () => { | |
if (xhr.status >= 200 && xhr.status < 300) { | |
resolve(JSON.parse(xhr.response)); | |
} else { | |
reject(xhr.statusText); | |
} | |
}; | |
xhr.onerror = () => reject(xhr.statusText); | |
xhr.send(JSON.stringify(obj.body)); | |
}); | |
}; | |
//Guildelines to use | |
/* | |
_http({ | |
method: 'POST', //GET by default | |
url: 'data.json', | |
body: JSON.stringify(payload) | |
headers: { | |
'my-custom-header': 'value' | |
} | |
}) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment