.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:
- Call the fetch function and give it’s going to give it a single argument which is the path to the resource. In this case it will be a local file.
- 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.
- 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.
- 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.
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!