Created
August 2, 2021 04:10
-
-
Save totoprayogo1916/74a0a72f08aebaf858561c2d7b4be321 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
/** | |
* Usage: | |
* makeRequest("GET", "URL_GET_JSON", { postId: 1}) | |
* .then(data => { | |
* console.log(data); | |
* }); | |
*/ | |
function makeRequest(method, url, qs_params) { | |
return new Promise((resolve, reject) => { | |
const q = buildQueryString(qs_params); | |
const qs = qs_params ? '?' + q : ''; | |
const xhr = new XMLHttpRequest(); | |
if (method === 'GET') { | |
xhr.open('GET', `${url}${qs}`); | |
} else { | |
xhr.open('POST', `${url}`); | |
} | |
xhr.onload = function() { | |
if (xhr.status >= 200 && xhr.status < 400) { | |
resolve(JSON.parse(xhr.responseText)); | |
} else { | |
resolve(xhr.responseText); | |
} | |
}; | |
xhr.onerror = () => reject(xhr.statusText); | |
if (method == "POST" && q) { | |
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); | |
xhr.send(q); | |
} else { | |
xhr.send(); | |
} | |
}); | |
} | |
function buildQueryString(params) { | |
return Object.entries(params).map(d => `${d[0]}=${d[1]}`).join('&'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment