fetch get example

Example 1: js fetch 'post' json

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

//																		Yeah

Example 2: Add no cores to fetch

// There were no quick access to mode and credentials to other fetch answers.
// Data you'll be sending
const data = { funny: "Absolutely not", educational: "yas" }

fetch('https://example.com/api/', {
  method: 'POST', // The method
  mode: 'no-cors', // It can be no-cors, cors, same-origin
  credentials: 'same-origin', // It can be include, same-origin, omit
  headers: {
    'Content-Type': 'application/json', // Your headers
  },
  body: JSON.stringify(data),
}).then(returnedData => {
  // Do whatever with returnedData
}).catch(err => {
  // In case it errors.
})

Example 3: javascript fetch api

fetch('http://example.com/movies.json')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    console.log(data);
  });

Example 4: http request javascript fetch

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

Example 5: .fetch method

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

Example 6: 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()
})