Last active
September 9, 2025 16:54
-
-
Save mscalora/44175b4b9df6a4e3216dcdc0728cf88b to your computer and use it in GitHub Desktop.
Client-side js helper function for GETing
This file contains hidden or 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
| function get(url, data, successCallback, errorCallback, responseType) { | |
| const urlObj = new URL(url); | |
| const params = urlObj.searchParams; | |
| Object.entries(data||{}).forEach(([key, value]) => params.set(key, value)); | |
| url = urlObj.toString(); | |
| fetch(url) | |
| .then(response => { | |
| if (!response.ok) { throw new Error(response.status); } | |
| const contentType = response.headers.get('content-type'); | |
| const isJson = responseType === 'json' || (responseType === 'auto' && contentType && contentType.includes('application/json')); | |
| return isJson ? response.json() : response.text(); | |
| }) | |
| .then(result => successCallback(result)) | |
| .catch(error => errorCallback(parseInt(error.message, 10) || 0)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment