Keith

XHR Fetch and Axios Sandbox

by Keith Rowles • 03/08/2023JavaScript

Two computer monitors displaying programming code

XHR

Here is the HTML:

<section id="control-center">
  <button id="get-btn">GET Data</button>
</section>

<div class="container">
  <h1>XHR</h1>
  <ul id="people" class="list-unstyled"></ul>
</div>

I am using the following API: https://reqres.in/api/users.

Here is the Javascript:

const getBtn = document.getElementById('get-btn');

const sendHttpRequest = (method, url, data) => {
  const promise = new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.responseType = 'json';
    if (data) {
      xhr.setRequestHeader('Content-Type', 'application/json');
    }
    xhr.onload = () => {
      if (xhr.status >= 400) {
        reject(xhr.response);
      } else {
        resolve(xhr.response);
      }
    };
    xhr.onerror = () => {
      reject('Something went wrong');
    };
    xhr.send(JSON.stringify(data));
  });
  return promise;
};

const getData = () => {
  sendHttpRequest('GET', 'https://reqres.in/api/users')
    .then((responseData) => {
      console.log(responseData);

      document.getElementById('people').innerHTML = responseData.data
        .map(function (person) {
          return `
          <li class="row mb-4">
          <img src="${person.avatar}" class="col-md-4" />
          <div class="col-md-3">
          <strong>${person.first_name} ${person.last_name}</strong>
          <div>Email: ${person.email}</div>
          </div>
          </li>
          `;
        })
        .join('');
    })
    .catch((err) => {
      console.log(err);
      document.getElementById('people').innerHTML =
        '<li class="text-danger">' + err.message + '</li>';
    });
};

getBtn.addEventListener('click', getData);
Open Code Pen

Fetch

The JS is using the fetch() api.

Open JS Fiddle

Axios

Using GitHub API: https://api.github.com/users

Using the Axios library.

Open Code Pen