Skip to content

Instantly share code, notes, and snippets.

@mscalora
Last active September 9, 2025 16:54
Show Gist options
  • Select an option

  • Save mscalora/44175b4b9df6a4e3216dcdc0728cf88b to your computer and use it in GitHub Desktop.

Select an option

Save mscalora/44175b4b9df6a4e3216dcdc0728cf88b to your computer and use it in GitHub Desktop.
Client-side js helper function for GETing
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