Using Fetch API to Get any Data - in JavaScript

Using Fetch API to Get any Data - in JavaScript
- 10th Mar, 2020 | 3min read

Earlier and now also we use XMLHttpRequest() to get data from a URL and if using jQuery then $.ajax()

But we have now Fetch API which is a newer built-in feature of JavaScript that makes working with requests and responses much easier then before.

In this article, we will learn how to fetch different types of data using Fetch API

Basic Data

For Json data

async function jsonDownload(){
  let dataURL='./data.json'         // Replace with your data link
  const response = await fetch(dataURL);
  const myJsonData = await response.json();
  console.log(JSON.stringify(myJsonData));
}

jsonDownload()
{"file_name":"data.json","data":"Hello","key_length":3}

For text data

async function textDownload(){
  let dataURL = './data.txt'                // Replace with your data link
  const response = await fetch(dataURL);
  const myTextData = await response.text();
  console.log(myTextData);
}

textDownload()
This data text save in a file on server

Media Data

Well, if you want you can also fetch media data using Fetch API

For media image data

async function imageDownload(){
  let dataURL = './logo.png'                  // Replace with your media link
  const response = await fetch(dataURL);
  const myBlob = await response.blob();
  var imgDataLink = URL.createObjectURL(myBlob);
  console.log(imgDataLink);

  //To add image in body element
  var imgElement = document.createElement('img');
  imgElement.src = imgDataLink;
  document.body.append(imgElement)

  //Uncomment below code To delete the media link generated, to avoid direct access
  //URL.revokeObjectURL(imgDataLink);
}

imageDownload()
blob:https://blog.rahul3v.xyz/031d0b2f-dfb7-4383-9baa-6c31cfb22831

Above, It generates any random image media blob link, that you can use directly inside html <img> tag

For media video data

async function videoDownload(){
  let dataURL = './myvideo.mp4'             // Replace with your media link
  const response = await fetch(dataURL);
  const myBlob = await response.blob();
  var videoDataLink = URL.createObjectURL(myBlob);
  console.log(videoDataLink);

  //To add video in body element
  var videoElement = document.createElement('video');
  videoElement.src = videoDataLink;
  videoElement.controls = true;
  document.body.append(videoElement)

//Uncomment below code To delete the media link generated, to avoid direct access
//URL.revokeObjectURL(videoDataLink);
}

videoDownload()
blob:https://blog.rahul3v.xyz/8139b8dc-b36f-48fe-af55-d4ecf64217a3

Above, It generates any random video media blob link, that you can use directly inside html <video> tag. Now you can also use the same concept for audio files and using it inside html <audio> tag

Error handling

Note that with Fetch,

  • Even a 404 or 500 error will not return any error
  • Only a network error or a request not completing will throw an error.

So, To handle file not found error 404 or any server error 500, we have to use try catch statement. The fetch method returns a Response containing some useful information that we can use to handle the errors

async function fetchData(){
  let dataURL = './dataFileNotFound.json'         // Replace with your data link
	try {
    const response = await fetch(dataURL);
    //console.log(response)                       // To see the response, uncomment this line
    if (!response.ok) {
      throw new Error('Network response : ' + response.status + ' - ' + response.statusText);
    }
    const myJsonData = await response.json();
    console.log(JSON.stringify(myJsonData));

  } catch (error) {
    console.log('Problem with fetch operation: ', error.message);
  }
}
fetchData()
Problem with fetch operation: Network response : 404 - Not Found

If there is any network connection problem occur then -

Problem with fetch operation: NetworkError when attempting to fetch resource.

Conclusion

In this article, we have learned what is Fetch API, how to fetch different types of data using it and finally how to handle the error.

Once we get the data, we can use it in any logical way in our code as needed.

NewOld