Skip to content

Instantly share code, notes, and snippets.

@brigand
Created July 3, 2021 21:15
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 brigand/118c9025d128c576172bd234a47cae90 to your computer and use it in GitHub Desktop.
Save brigand/118c9025d128c576172bd234a47cae90 to your computer and use it in GitHub Desktop.
fetchJson
// Based on: https://jsfiddle.net/t2g9ub43/1/
const fetchJson = async (url, { ...opts } = {}) => {
opts.headers = new Headers(opts.headers);
opts.headers.set('Accept', 'application/json');
return fetch(url, opts).then((resp) => {
const ct = resp.headers.get('content-type');
if (!ct || !ct.includes('application/json')) {
throw resp;
}
return resp.json().then((json) =>
Object.assign(resp, { json }),
);
});
};
fetchJson('https://jsonplaceholder.typicode.com/todos/1').then(
console.log,
console.error,
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment