Skip to content

Instantly share code, notes, and snippets.

@donbrae
Last active August 1, 2022 13:50
Show Gist options
  • Save donbrae/2277dd0362789957fd5ce9ed4894c93b to your computer and use it in GitHub Desktop.
Save donbrae/2277dd0362789957fd5ce9ed4894c93b to your computer and use it in GitHub Desktop.
Example: `fetch` JSON file.
// Fetch JSON data
fetch('https://jsonplaceholder.typicode.com/todos/').then(response => {
// Success
if (response.ok)
return response.json(); // Returns to then()
// Error
return Promise.reject(response);
}).then(data => {
console.log(data); // JSON
}).catch(err => {
console.error(err); // Error
});
// Fetch JSON data and log value of specific response header (x-ratelimit-remaining)
fetch('https://api.github.com/users/donbrae/gists?per_page=15').then(response => {
const headers = {};
for (let entry of response.headers.entries()) {
headers[entry[0]] = entry[1];
}
console.log(`x-ratelimit-remaining: ${headers['x-ratelimit-remaining']}`);
// Success
if (response.ok)
return response.json(); // Returns to then()
// Error
return Promise.reject(response);
}).then(data => {
console.log(data);
}).catch(err => {
console.error(err); // Error
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment