Fetch API in JavaScript

According to MDN web docs the Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources across the network.

.The fetch function is a function that allows you to fetch stuff. Anything from data to images from different sources and different places.

Theres this idea in web programming of making an HTTP request. You can make a GET request and POST request. In the blog I will show you both. Fetch can both retrieve and send.

Our program will:

  1. Deal with the response. This is when we receive the response. This involves the idea of a promise. The response is a stream of data.
  2. Once we receive the data we need it will need to be read. This is where we will complete and grab the data in the response.
  3. Make an <img> element with the data retrieved.

We will begin with a basic html file and start by adding an image to the body. The next thing is to add script tag that will hold the fetch function. We’ll do everything in one file.

Within the script tag we will add the fetch. The next thing to do is add fetch and console.log puppies. This will show up in our console.

.then has also been added. An argument response has been added by using the JavaScript arrow syntax to then do something with that response. That response will be converted to a blob. Below is how the response was displayed in the console. All the metadata in return is displayed.

To convert the response into an image blob we will have another promise. We will be able to chain the two responses. Both the response and the blob have been displayed on the console.

The image element in the body allows us to get the element by using document.getElementById. This will allow us to take the data of that image which comes in as a blob and place it into the source attribute of the imagine DOM element. We are also going to change the second .then to blob.

This however, will not work because the data blob isn’t in the format that the image DOM element expects. This will output an error in the console.

We will be able to use createObjectURL that takes a blob object and turns it into the format that an image DOM element would expect. This will finally output the image of the puppies.

Thanks for reading!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store