The Web Developer Bootcamp 2024

Colt Steele

Back to Ajax Index Page


fetch() Http Request

The Fetch API provides a JavaScript interface for making HTTP requests and processing the responses. Fetch is the modern replacement for XMLHttpRequest:

  • unlike XMLHttpRequest, which uses callbacks, Fetch is promise-based and is integrated with features of the modern web such as service workers and Cross-Origin Resource Sharing (CORS)
With the Fetch API, you make a request by calling fetch(), which is available as a global function in both window and worker contexts. You pass it a Request object or a string containing the URL to fetch, along with an optional argument to configure the request. The fetch() function returns a Promise which is fulfilled with a Response object representing the server's response. You can then check the request status and extract the body of the response in various formats, including text and JSON, by calling the appropriate method on the response.

Some of the reason that fetch is better than XHR are:

  • with XHR the coding is very clunky
  • XHR does not support Promises or Async
  • coding is very messy when trying to make subsequent requests

More Info At : W3Schools JavaScript Fetch API and MDN Using the Fetch API


fetch() Example

As in our XHR HTTP Request discussion, we're going to be sending a data request to the Star Wars API. This time we are going to make three API requests for the data on three different people from the Star Wars Universe. And as in our XHR HTTP Request discussion, we will be logging the results of our API fetch Request to the console.

First we need to create a fetch() function and pass in the URL of our web API:

  • fetch("https://swapi.tech/api/people/1/);

Because fetch() always returns a Promise, we need to process the result of the returned Promise.

  • .then to process a resolved result, and
  • .catch to process a rejected result
like so:
  • .then((res) => {
    • console.log("RESOLVED!", res);
  • })
  • .catch((err>) => {
    • console.log("ERROR!", err);
  • })
**note that if the Promise result is a reject, then it will log "ERROR! " and the error that caused the rejection.

However, if our Promise is resolved, then it returns a Response Object. This Response Object does NOT contain any of the Json data we are looking for. This is because the Promise is resolved as soon as it receives any http headers.

If we look at the properties of our Response Object, we see that the body property is not our requested data, but a readable stream.

So we need to "break down" this body: Readable Stream with further processing. We do this by modifying our .then function with:

  • res.json()
which actually returns yet another Promise. So we need to add a .then to process our resolve, to our original .then that we already created, like so:
  • .then((res) => {
    • console.log("RESOLVED!", res);
    • return res.json();
  • })
  • .then((data) => {
    • console.log(data.result.properties);
  • })
What this does is return the results of the Response Object Promise:
  • return res.json();
and the next .then logs the actual data (data.result.properties) to the console. And because in our original fetch() function, we asked for people/1, our query logged the data for "Luke Skywalker".


Here's the final Code for our single fetch request:

  • JavaScript
  • single fetch request
  •  
  • fetch("https://swapi.tech/api/people/1/);
    • .then((res) => {
      • console.log("RESOLVED!", res);
      • return res.json();
    • })
    • .then((data) => {
      • console.log(data.result.properties);
    • })
    • .catch((e) => {
      • console.log("ERROR!", e);
    • })
which results in much simpler, more refined code than in our XHR HTTP Request example.


Multiple Fetch Requests

Earlier we mentioned that we want to send three requests for three different Star Wars People. We're going to use an async functions to accomplish this. We are going to send a request for persons 2 / 4 / 6 in the Star Wars API.

Here's the code:

  • JavaScript
  • multiple fetch request
  •  
  • const loadStarWarsPeople = async (id) => {
  • let apiAddress = `https://swapi.tech/api/people/${id}/`;
    • try {
      • const res = await fetch(apiAddress);
      • const data = await res.json();
      • console.log(data.result.properties);
    • } catch (err) {
      • console.log("ERROR!!!", err);
    • }
  • };
  •  
  • for (let i = 2; i < 7; i = i + 2) {
    • loadStarWarsPeople(i);
  • }

- So we set a counter that counts, 2 / 4 / 6. Then we call the function loadStarWarsPeople() with the current count number.

- We then create the async function loadStarWarsPeople(), which receives the current count number (id).

- We then build the Star Wars Web API address using this current count number.

- We then try to send our API Request, which

  • awaits the result of the fetch request - if resolved - returns an object
  • awaits the result of the res.JSON() request
    • this is the body: readable stream from the above object
  • and then logs, to the console, our Star Wars person data for this request

- We the catch any errors that occur in the fetch process.

Back to Top