Get JSON data from an URL

AJAX request using ES6 Promises

by Edgar Martinez

HTML

<div id="using-fetch"></div>
<div id="using-XMLHttpRequest"></div>

JavaScript

// Note: the url needs https because we request from https
// and the server should allow all origins (Access-Control-Allow-Origin: *)
let $div1_ = document.querySelector('#using-fetch');
let $div2_ = document.querySelector('#using-XMLHttpRequest');

/**
 * Get JSON data from an URL using fetch()
 */
fetch('http://wolf.pointmp3.com/download/?t=02013503720aec1603529a7d23eabea27a68e6ff&p=eyJpdiI6IncwRW02Wmlic0FZdEJJdXM5NkIwUHc9PSIsInZhbHVlIjoiUTFZTVVqdXp4dkpHaFp3ZUREY0NJcU9tR1VNM0lHS0M2aERRWE9oZFdpQU8rRjRLeGZBYWFON0E1Y09MZEY0UW5jS2M5OVpjUlVSTEl0MEtEbHEwbmN4bXR6a3ZqTlB5VjFDR3F5K2tBXC9mdWJsTEFuUGxFQVF6Q1VJWlFmUW5cLyIsIm1hYyI6IjY3MjJmODJjODVmN2JjMWViYmVmMzNhZmYwMmQ3MTJmNTdmZTkxNmY4NzVkOGVlNDc5MjBmY2MzMzM0Mjg4ZGQifQ==&id=jvipPYFebWc')
  .then(response => {
    console.log()
    } else $div1_.textContent = 'Network response was not ok.';
  })
  .catch(error =>
    $div1_.textContent = 'Fetch error: ' + error
  );

/**
 * Get JSON data from an URL using XMLHttpRequest() and promises
 */
let getJSON = url => {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open('get', url, true); // asynchronous
    xhr.responseType = 'json';
    xhr.onload = () => {
      if (xhr.status === 200) resolve(xhr.response); // then
      else reject(xhr.status); // catch
    };
    xhr.send();
  });
};

getJSON('https://httpbin.org/ip')
  .then(data => {
    $div2_.textContent = JSON.stringify(data);
  })
  .catch(status => {
    $div2_.textContent = 'Error: ' + status;
  });