Skip to content

Instantly share code, notes, and snippets.

@hontas
Created May 24, 2017 22: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 hontas/df2b9c2e6b04dd4f62c42266c0ce0c92 to your computer and use it in GitHub Desktop.
Save hontas/df2b9c2e6b04dd4f62c42266c0ce0c92 to your computer and use it in GitHub Desktop.
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