Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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