how to create a fetch function

Solutions on MaxInterview for how to create a fetch function by the best coders in the world

showing results for - "how to create a fetch function"
Allison
23 Apr 2017
1const url = 'http://api.open-notify.org/astros.json'
2
3const fetchurl = (url:string):void=>{
4
5       fetch(url).then(res=>res.json()).then(jsonRes=>{
6             
7            console.log(jsonRes)
8       })
9}
10
11fetchurl(url)
12
Andrea
18 Jul 2018
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
similar questions
queries leading to this page
how to create a fetch function