Created
March 14, 2017 08:14
-
-
Save simlegate/582bb54629fd50c64b5dbcaac053f712 to your computer and use it in GitHub Desktop.
Fetch Api Wrapper
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
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