1fetch('http://example.com/songs')
2 .then(response => response.json())
3 .then(data => console.log(data))
4 .catch(err => console.error(err));
1fetch('http://example.com/movies.json')
2 .then((response) => {
3 return response.json();
4 })
5 .then((myJson) => {
6 console.log(myJson);
7 });
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
1fetch('http://example.com/movies.json')
2 .then((response) => {
3 return response.json();
4 })
5 .then((data) => {
6 console.log(data);
7 });
8
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}
19
20postData('https://example.com/answer', { answer: 42 })
21 .then(data => {
22 console.log(data); // JSON data parsed by `data.json()` call
23 });
24
1/*
2The fetch() method in JavaScript is used to request
3to the server and load the information in the webpages.
4The request can be of any APIs that returns the data of the format JSON or XML.
5This method returns a promise.
6*/
7
8//Syntax:
9fetch( url, options )
10/*
11URL: It is the URL to which the request is to be made.
12Options: It is an array of properties. It is an optional parameter.
13*/