Last active
August 16, 2023 09:56
-
-
Save ownaginatious/503a75a68a7bc376d11944950af855c7 to your computer and use it in GitHub Desktop.
React native XHR request
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
request = (opts) => { | |
return new Promise((resolve, reject) => { | |
let xhr = new XMLHttpRequest(); | |
let url = opts.url; | |
let params = opts.query_params; | |
if (params && typeof params === 'object') { | |
params = Object.keys(params).map(function(key) { | |
return encodeURIComponent(key).replace(/%20/g, '+') + | |
'=' + encodeURIComponent(params[key]).replace(/%20/g, '+'); | |
}).join('&'); | |
url = url + '?' + params; | |
} | |
xhr.open(opts.method, url); | |
xhr.onload = function() { | |
if (xhr.status >= 200 && xhr.status < 300) { | |
resolve(xhr.response); | |
} else { | |
reject({ | |
status: xhr.status, | |
statusText: xhr.statusText | |
}); | |
} | |
}; | |
xhr.onerror = function() { | |
reject({ | |
status: xhr.status, | |
statusText: xhr.statusText | |
}); | |
}; | |
if (opts.headers) { | |
Object.keys(opts.headers).forEach(function(key) { | |
xhr.setRequestHeader(key, opts.headers[key]); | |
}); | |
} | |
if (opts.method.toUpperCase() == 'POST'){ | |
xhr.send(opts.body); | |
} else { | |
xhr.send() | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment