Skip to content

Instantly share code, notes, and snippets.

@whal-e3
Last active November 14, 2020 10:57
Show Gist options
  • Save whal-e3/a9039f794a0791fc3fff100ecf9001ec to your computer and use it in GitHub Desktop.
Save whal-e3/a9039f794a0791fc3fff100ecf9001ec to your computer and use it in GitHub Desktop.
JS fetch() API
// ajax+XHR -> fetch API
document.getElementById('button1').addEventListener('click', getText);
document.getElementById('button2').addEventListener('click', getJson);
document.getElementById('button3').addEventListener('click', getExternal);
// Get local txt data
function getText() {
fetch('test.txt')
.then(res => res.text())
.then(data => {
console.log(data);
document.getElementById('output').innerHTML = data;
})
.catch(err => console.log(err));
}
// Get local json data
function getJson() {
fetch('posts.json')
.then(res => res.json())
.then(data => {
let output = '';
data.forEach(function (post) {
output += `<li>${post.title}</li>`;
});
document.getElementById('output').innerHTML = output;
})
.catch(err => console.log(err));
}
// Get from external API
function getExternal() {
fetch('https://api.github.com/users')
.then(res => res.json())
.then(data => {
let output = '';
data.forEach(function (user) {
output += `<li>${user.login}</li>`;
});
document.getElementById('output').innerHTML = output;
})
.catch(err => console.log(err));
}
// error handling ------------------------------------------------------------------
function handleErrors(res) {
if (!res.ok) throw new Error(res.error);
return res;
}
fetch('https://devcamper.io/api/v1/bootcamps/34343')
.then(res => res.json())
.then(handleErrors)
.then(res => console.log(res.data))
.catch(err => console.log(err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment