how to write fetch in javascript code example
Example 1: fetch and then javascript send parameters
const url = 'https://randomuser.me/api';
let data = {
name: 'Sara'
}
let fetchData = {
method: 'POST',
body: data,
headers: new Headers()
}
fetch(url, fetchData)
.then(function() {
});
Example 2: 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 3: work with fetches in js
function yourfunction() {
return fetch(API)
.then(response => response.json())
.then(data => data.content)
}