Skip to content

Instantly share code, notes, and snippets.

@simlegate
Created March 14, 2017 08:14
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 simlegate/582bb54629fd50c64b5dbcaac053f712 to your computer and use it in GitHub Desktop.
Save simlegate/582bb54629fd50c64b5dbcaac053f712 to your computer and use it in GitHub Desktop.
Fetch Api Wrapper
function http(method, url, request) {
let init = { method: 'GET' }
if(method != 'GET') {
init.body = request.body
}
return fetch(url, init).
then(function(response){
if(response.ok){
response.json().then(function(json){
response.parsedJson = json
return Promise.resolve(response);
})
}
let error = new Error(response.statusText);
error.response = response
throw error;
}).catch(function(error){
return Promise.reject(error);
})
}
function get(url, request) {
return http("GET", url, request)
}
function post(url, request) {
return http("POST", url, request)
}
get("https://jsonplaceholder.typicode.com/posts/11").then(function(response){
console.log(response)
}).catch(function(error){
console.log(error.response)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment