Created
July 3, 2021 21:15
-
-
Save brigand/118c9025d128c576172bd234a47cae90 to your computer and use it in GitHub Desktop.
fetchJson
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
// 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