1//Obj of data to send in future like a dummyDb
2const data = { username: 'example' };
3
4//POST request with body equal on data in JSON format
5fetch('https://example.com/profile', {
6 method: 'POST',
7 headers: {
8 'Content-Type': 'application/json',
9 },
10 body: JSON.stringify(data),
11})
12.then((response) => response.json())
13//Then with the data from the response in JSON...
14.then((data) => {
15 console.log('Success:', data);
16})
17//Then with the error genereted...
18.catch((error) => {
19 console.error('Error:', error);
20});
21
22// Yeah
1// There were no quick access to mode and credentials to other fetch answers.
2// Data you'll be sending
3const data = { funny: "Absolutely not", educational: "yas" }
4
5fetch('https://example.com/api/', {
6 method: 'POST', // The method
7 mode: 'no-cors', // It can be no-cors, cors, same-origin
8 credentials: 'same-origin', // It can be include, same-origin, omit
9 headers: {
10 'Content-Type': 'application/json', // Your headers
11 },
12 body: JSON.stringify(data),
13}).then(returnedData => {
14 // Do whatever with returnedData
15}).catch(err => {
16 // In case it errors.
17})
1//Most API's will only allow you to fetch on their website.
2//This means you couldn't run this code in the console on
3// google.com because:
4// 1. Google demands the fetch request be from https
5// 2. open-notify's API blocks the request outside of their website
6
7fetch('http://api.open-notify.org/astros.json')
8.then(function(response) {
9 return response.json();
10})
11.then(function(json) {
12 console.log(json)
13});
14
15// Here is another example. A method (function) that
16// grabs Game of Thrones books from an API ...
17
18function fetchBooks() {
19 return fetch('https://anapioficeandfire.com/api/books')
20 .then(resp => resp.json())
21 .then(json => renderBooks(json));
22}
23
24function renderBooks(json) {
25 const main = document.querySelector('main')
26 json.forEach(book => {
27 const h2 = document.createElement('h2')
28 h2.innerHTML = `<h2>${book.name}</h2>`
29 main.appendChild(h2)
30 })
31}
32
33document.addEventListener('DOMContentLoaded', function() {
34 fetchBooks()
35})
36