1(async () => {
2 const rawResponse = await fetch('https://httpbin.org/post', {
3 method: 'POST',
4 headers: {
5 'Accept': 'application/json',
6 'Content-Type': 'application/json'
7 },
8 body: JSON.stringify({a: 1, b: 'Textual content'})
9 });
10 const content = await rawResponse.json();
11
12 console.log(content);
13})();
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// Example POST method implementation:
2async function postData(url = '', data = {}) {
3 // Default options are marked with *
4 const response = await fetch(url, {
5 method: 'POST', // *GET, POST, PUT, DELETE, etc.
6 mode: 'cors', // no-cors, *cors, same-origin
7 cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
8 credentials: 'same-origin', // include, *same-origin, omit
9 headers: {
10 'Content-Type': 'application/json'
11 // 'Content-Type': 'application/x-www-form-urlencoded',
12 },
13 redirect: 'follow', // manual, *follow, error
14 referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
15 body: JSON.stringify(data) // body data type must match "Content-Type" header
16 });
17 return response.json(); // parses JSON response into native JavaScript objects
18}
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