0
Q:

fetch

//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
19
fetch('http://example.com/movies.json')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    console.log(data);
  });
12
fetch('http://example.com/songs')
	.then(response => response.json())
	.then(data => console.log(data))
	.catch(err => console.error(err));
10
// 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 :)
});
2
fetch('http://example.com/movies.json')
  .then((response) => {
    return response.json();
  })
  .then((myJson) => {
    console.log(myJson);
  });
16
(async () => {
  const rawResponse = await fetch('https://httpbin.org/post', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({a: 1, b: 'Textual content'})
  });
  const content = await rawResponse.json();

  console.log(content);
})();
0
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;
});

1
var formData = new FormData();
var fileField = document.querySelector("input[type='file']");

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
0
//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()
})
3
fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));
3

New to Communities?

Join the community