30 Days of JAVASCRIPT #5/30

·

3 min read

Fetch API

Working with the Fetch API in JavaScript

The Fetch API is a modern way to make HTTP requests in JavaScript. It provides a simple and powerful interface for fetching resources from a server and handling the response. In this blog post, we will explore how to use the Fetch API and provide an example code to demonstrate its usage. Let's get started!

Fetching Data

The fetch() function is the heart of the Fetch API. It takes a URL as its parameter and returns a Promise that resolves to the Response object representing the resource. Here's an example:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In the above code snippet, we use fetch() to make a GET request to the specified URL. We then use the .then() method to extract the JSON data from the response by calling response.json(). Finally, we log the retrieved data to the console. If an error occurs during the request, the .catch() method handles it and logs an error message.

Handling Different Types of Data

The Fetch API supports various types of data, including JSON, text, and blobs. By default, fetch() assumes the response type is text. However, we can use the various response methods to parse and handle different data types. Here's an example that retrieves an image as a blob:

fetch('https://api.example.com/image')
  .then(response => response.blob())
  .then(blob => {
    const img = document.createElement('img');
    img.src = URL.createObjectURL(blob);
    document.body.appendChild(img);
  })
  .catch(error => console.error(error));

In the above code, we use the .blob() method to convert the response into a blob object. We then create an <img> element, assign the blob URL to its src attribute using URL.createObjectURL(), and append it to the <body> element. This allows us to display the fetched image on the web page.

Sending Data

Fetch API also allows us to send data to the server using different request methods such as POST, PUT, and DELETE. We can define the request method, headers, and body data for the request. Here's an example that sends a POST request with JSON data to create a new user:

fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ name: 'John Doe', age: 30 }),
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In this example, we specify the request method as POST and provide the Content-Type header to indicate that the body data is in JSON format. We use JSON.stringify() to convert the data object into a JSON string and send it as the request body. Finally, we log the response data to the console.

The Fetch API is a powerful tool for handling HTTP requests in JavaScript. It provides a modern and intuitive interface for fetching resources from a server and handling the response. By utilizing the various methods and options available, we can retrieve and send data with ease and efficiency.

I hope this blog post has given you an understanding of how to use the Fetch API. Feel free to experiment with the provided examples, and may your data fetching adventures be successful and seamless!