Created
July 27, 2019 16:08
-
-
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.
This file contains 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
// 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