javascript fetch json

JavaScript
//Obj of data to send in future like a dummyDb
const data = { username: 'example' };

//POST request with body equal on data in JSON format
fetch('https://example.com/profile', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
.then((response) => response.json())
//Then with the data from the response in JSON...
.then((data) => {
  console.log('Success:', data);
})
//Then with the error genereted...
.catch((error) => {
  console.error('Error:', error);
});

//																		Yeahfetch('./yourjson.json')
  .then((response) => response.json())
  .then((data) => {
  	console.log(data);
  })fetch('http://example.com/movies.json')
  .then((response) => {
    return response.json();
  })
  .then((myJson) => {
    console.log(myJson);
  });const _fetch = async props => {
   const { endpoint, options } = props
   return await fetch(endpoint, options)
   .then(async res => {
      if (res.ok) {
         return await res.clone().json().catch(() => res.text())
      }
      return false
   })
   .catch(err => {
      console.error("api", "_fetch", "err", err)
      return false
   })
}var myHeaders = new Headers();

var myInit = { method: 'POST',
               headers: myHeaders,
               mode: 'cors',
               cache: 'default' };

fetch('flowers.jpg',myInit)
.then(function(response) {
  return response.blob();
})
.then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});

//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()
})

Source

Also in JavaScript: