Fetch API

Fetch API is a new standard for dealing with http requests.

Get Local Text File Data

document.getElementById('button1').addEventListener('click', getText);

function getText() {
  fetch('test.txt')
    .then(function(res){
      return res.text();
    })
    .then(function(data) {
      console.log(data);
      document.getElementById('output').innerHTML = data;
    })
    .catch(function(err){
      console.log(err);
    });
}

Get Local JSON Data

document.getElementById('button2').addEventListener('click', getJson);

// Get local json data
function getJson() {
  fetch('posts.json')
    .then(function(res){
      return res.json();
    })
    .then(function(data) {
      console.log(data);
      // This is an array so we have to loop through it
      let output = '';

      data.forEach(function(post){
        output += `<li>${post.title}</li>`;
      });
      document.getElementById('output').innerHTML = output;

    })
    .catch(function(err){
      console.log(err);
    });
}

Get external API data

document.getElementById('button3').addEventListener('click', getExternal);

function getExternal() {
  fetch('https://api.github.com/users')
    .then(function(res){
      return res.json();
    })
    .then(function(data) {
      console.log(data);
      // This is an array so we have to loop through it
      let output = '';

      data.forEach(function(user){
        output += `<li>${user.login}</li>`;
      });
      document.getElementById('output').innerHTML = output;

    })
    .catch(function(err){
      console.log(err);
    });
}
Was this page helpful?

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *