fetch browser code example
Example 1: javascript fetch api
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});
Example 2: fetch api javascript
fetch('http://example.com/songs')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
Example 3: fetch api javascript
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((myJson) => {
console.log(myJson);
});
Example 4: fetch api in js
var myData = async () => {
try {
const raw_response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!raw_response.ok) {
throw new Error(raw_response.status);
}
const json_data = await raw_response.json();
console.log(json_data);
}
catch (error) {
console.log(error);
}
}
fetchUsers();
Example 5: 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()
})
Example 6: .fetch method
fetch('http://example.com/data.json')
.then(data => data);
.catch(err => console.log(err));