Last active
August 9, 2016 09:40
-
-
Save deepak/2710298cd1fa1a6fcbb4b6e371e620a6 to your computer and use it in GitHub Desktop.
Wrapping fetch to handle errors
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
var api_fetch = { | |
checkStatus(response) { | |
if (response.status >= 200 && response.status < 300) { | |
return Promise.resolve(response); | |
} else { | |
return Promise.reject(response); | |
} | |
}, | |
parseJson(response) { | |
return response.json(); | |
}, | |
handleError(response) { | |
if (response && response.status === 401) { | |
console.log('Unauthorized request', response); | |
} else { | |
console.log('Request failed', response); | |
} | |
}, | |
post(endpoint, body) { | |
const url = `http://0.0.0.0:3000/${endpoint}`; | |
const init = { | |
method: "POST", | |
headers: { | |
"Accept": "application/json", | |
"Content-Type": "application/json" | |
}, | |
body: JSON.stringify(body) | |
}; | |
fetch(url, init) | |
.then(this.checkStatus) | |
.then(this.parseJson) | |
.then(function(data) { | |
console.log('Request succeeded with JSON response', data); | |
}).catch(this.handleError); | |
} | |
}; | |
api_fetch.post("login", { | |
"login" : "deepak", | |
"password" : "bad-password" | |
}); | |
api_fetch.post("login", { | |
"login" : "deepak", | |
"password" : "password" | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment