Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created July 27, 2019 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeoncross/c8d07641682aecd9a710fd7c42257e4a to your computer and use it in GitHub Desktop.
Save xeoncross/c8d07641682aecd9a710fd7c42257e4a to your computer and use it in GitHub Desktop.
Basica fetch() wrapper to make sure we always get a JSON response even if there is an error, or the server returns some other content type.
// Look into wrapping fetch so it always returns JSON
export default function fetchjson(url, data, options) {
const defaults = {
// credentials: 'same-origin',
credentials: 'omit',
method: data ? 'post' : 'get',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': data ? 'application/json' : 'text/plain; charset=utf-8',
},
body: data ? JSON.stringify(data) : null,
};
return fetch(url, {...defaults, ...options}).then((response) => {
// match "application/json" or "text/javascript"
const contentType = response.headers.get('content-type');
const isJson = /json|javascript/.test(contentType);
return isJson
? response.json()
: response.text().then(data => ({
error: !response.ok,
status: response.statusText,
contentType,
data,
}));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment