fetch api in js 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
const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
Example 3: http request javascript fetch
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
Example 4: .fetch method
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
Example 5: 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 6: 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()
})