Fetch on JavaScript

Fetch on JavaScript

2023, Oct 24    

I am currently working on the final project before the final project for this week. I’ve had a desire to try my hand at frontend development since last time, so I took on the role of connecting the users’ part in the frontend. As expected, there have been many challenges from the beginning, but I am progressing slowly while reviewing the previous lectures and practicing.

This team seems to have a reasonable level of skill, and the progress is fast, which puts my mind at ease.

In the process, I am using the most fundamental feature of JavaScript, which is the Fetch function in various ways.

In this post, we will take a closer look at Fetch.

The Fetch in JavaScript is a modern API for making HTTP requests to retrieve data from a web server or send data to a server. It provides a more powerful and flexible way to work with network requests than older techniques like XMLHttpRequest. Fetch is designed to work with Promises, which makes it easier to handle asynchronous operations and manage the response data.

Here is a detailed explanation of how to use the Fetch function in JavaScript:

  1. Making a Simple GET Request: To retrieve data from a server, you can use the Fetch function as follows:

    fetch('https://example.com/api/data')
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json(); // Parse the response as JSON
      })
      .then(data => {
        // Use the data from the response
        console.log(data);
      })
      .catch(error => {
        // Handle any errors that occur during the fetch
        console.error('Fetch error:', error);
      });
    

    In this example, we use the fetch function to make a GET request to the specified URL. The response is then checked for its status, and if it’s successful (status 200-299), we parse the response as JSON and use the data. If there’s an error in the request or response, it’s caught and handled in the catch block.

  2. Making Other Types of Requests: Fetch can be used to make various types of requests, including POST, PUT, DELETE, etc. You can specify the HTTP method and other options in the fetch function:

    fetch('https://example.com/api/resource', {
      method: 'POST',  // or 'PUT', 'DELETE', etc.
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ key: 'value' }),
    })
    .then(response => {
      // Handle the response here
    })
    .catch(error => {
      // Handle any errors
    });
    

    In this example, we make a POST request with a JSON payload. You can customize the request method, headers, and data as needed.

  3. Handling Headers: You can access response headers using the headers property of the response object. For example:

    fetch('https://example.com/api/data')
      .then(response => {
        console.log(response.headers.get('Content-Type'));
      });
    
  4. Handling Timeouts and Aborting Requests: You can set a timeout for a request by using Promise.race with fetch and a custom timeout promise. This allows you to abort a request if it takes too long.

    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => {
        reject('Request timed out');
      }, 5000); // 5-second timeout
    });
    
    Promise.race([
      fetch('https://example.com/api/data'),
      timeoutPromise,
    ])
    .then(response => {
      // Handle the response or timeout error
    })
    .catch(error => {
      console.error(error);
    });
    
  5. Using async/await: You can simplify Fetch requests by using async/await, which makes your code cleaner and easier to read. Here’s an example of how to use Fetch with async/await:

    async function fetchData() {
      try {
        const response = await fetch('https://example.com/api/data');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const data = await response.json();
        console.log(data);
      } catch (error) {
        console.error('Fetch error:', error);
      }
    }
    
    fetchData();
    

This covers the basic usage of the Fetch function in JavaScript. It’s a powerful tool for making network requests and handling responses in a modern and efficient way.