is fetch for only json code example
Example 1: fetch api javascript
// This will fetch api.example.com/comments with a header and a body
fetch(`https://api.example.com/comments`, {
method: 'POST', //This could be any http method
headers: {
'Authorization': 'Basic SGVsbG8gdGhlcmUgOikgSGF2ZSBhIGdvb2QgZGF5IQ==',
'Content-Type': 'application/json',
},
body: JSON.stringify({
UID: 58,
Comment: "Fetch is really easy!",
}),
})
.then((response) => response.json)
.then((newComment) => {
// Do something magical with your newly posted comment :)
});
Example 2: how to use fetch() javascript
//Most API's will only allow you to fetch on their website.
//This means you couldn't run this code in the console on
// google.com because:
// 1. Google demands the fetch request be from https
// 2. open-notify's API blocks the request outside of their website
fetch('http://api.open-notify.org/astros.json')
.then(function(response) {
return response.json();
})
.then(function(json) {
console.log(json)
});
// Here is another example. A method (function) that
// grabs Game of Thrones books from an API ...
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()
})