Skip to content

Instantly share code, notes, and snippets.

@hontas hontas/index.js

Created May 24, 2017
Embed
What would you like to do?
fetch handler
const NO_CONTENT = 204;
const getHeaders = {
'accept': 'application/json'
};
const postHeaders = {
'Content-Type': 'application/json'
};
export function getJSON(url) {
return fetch(url, { headers: getHeaders })
.then(handleResponse);
}
export function postJSON(url, content) {
return fetch(url, {
headers: postHeaders,
credentials: 'include',
method: 'POST',
body: JSON.stringify(content)
});
}
function handleResponse(response) {
const contentType = response.headers.get('Content-Type');
const { status, statusText } = response;
if (contentType === 'application/json') {
return response.json()
.then(json => {
if (response.ok) {
return json;
} else {
return Promise.reject(Object.assign({}, json, { status, statusText }));
}
});
}
if (contentType === 'text/html') {
return response.text();
}
console.log(`Content-Type: '${contentType}' not supported - returning response.`);
return Promise.resolve(response);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.