javascript built in fetch code example
Example 1: fetch api javascript
fetch('http://example.com/songs')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
Example 2: how to create a fetch function
const url = 'http://api.open-notify.org/astros.json'
const fetchurl = (url:string):void=>{
fetch(url).then(res=>res.json()).then(jsonRes=>{
console.log(jsonRes)
})
}
fetchurl(url)
Example 3: fetch api javascript
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((myJson) => {
console.log(myJson);
});
Example 4: how to use fetch() javascript
fetch('http://api.open-notify.org/astros.json')
.then(function(response) {
return response.json();
})
.then(function(json) {
console.log(json)
});
function fetchBooks() {
return fetch('https://anapioficeandfire.com/api/books')
.then(resp => resp.json())
.then(json => renderBooks(json));
}
function renderBooks(json) {
const main = document.querySelector('main')
json.forEach(book => {
const h2 = document.createElement('h2')
h2.innerHTML = `<h2>${book.name}</h2>`
main.appendChild(h2)
})
}
document.addEventListener('DOMContentLoaded', function() {
fetchBooks()
})