AJAX - Async HTTP requests from JavaScript

HTTP (Hyper Text Transfer Protocol) is the method we use to request resources across the web. HTTP needs the transfer of data to happen across the web using TCP (Transmission Control Protocol).

Fetch API

Fetch is an easy-to-use interface to build and send requests over the web.

With ES2017, async/await was introduced to make a cleaner approach of returning promises.

(async function() {
  const url = 'https://v2.jokeapi.dev/joke/';
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        "Authorization": 'Bearer 1234',
      },
      body: JSON.stringify(data)
    });
    const data = await response.json();
    console.log("here's your joke", data);
  } catch(error) {
    console.log(error);
  }
})();

If you want to just run fetch with all the default options:

(async function() {
  const url = 'https://v2.jokeapi.dev/joke/';
  const response = await fetch(url);
  const data = await response.json();
  console.log("here's your jokes", data);
})();

Fetch uses Promises to deliver requests, providing flexibility when making different types of requests and handling them.


References:
  1. MDN: Fetch API