What is the Fetch API?

The Fetch API is a built-in JavaScript feature that allows you to make network requests similar to XMLHttpRequest. However, it is more powerful and flexible, supporting promises and providing a cleaner syntax. The Fetch API is asynchronous, which means it will not block the execution of your code while waiting for the response.

Making a GET Request

To initiate a GET request, you can use the fetch function, which takes a URL as an argument. Below is an example of how to fetch data from a public API.

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.statusText);
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

Explanation:

  1. fetch(url): Initiates the request to the specified URL.
  2. response.ok: Checks if the response status is in the range of 200-299.
  3. response.json(): Parses the JSON response.
  4. .then(): Handles the resolved promise.
  5. .catch(): Catches any errors that occur during the fetch operation.

Making a POST Request

To send data to a server, you can use the POST method. Here’s how to do it using the Fetch API:

const postData = {
  title: 'foo',
  body: 'bar',
  userId: 1,
};

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(postData),
})
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.statusText);
    }
    return response.json();
  })
  .then(data => {
    console.log('Success:', data);
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

Explanation:

  1. method: 'POST': Specifies the request method.
  2. headers: Sets the content type to JSON.
  3. body: Converts the JavaScript object to a JSON string.

Handling Errors

Error handling is crucial when making network requests. The Fetch API does not reject the promise on HTTP error statuses (like 404 or 500). Instead, you need to check the response status manually, as shown in the examples above.

Comparison of Fetch API and XMLHttpRequest

FeatureFetch APIXMLHttpRequest
SyntaxCleaner and more modernVerbose and complex
Promise-basedYesNo
AsynchronousYesYes
Response TypesJSON, text, blob, form dataLimited to text
Error HandlingManual check for response statusAutomatic on network errors

Best Practices

  1. Always check the response: Ensure that the response status is OK before processing the data.
  2. Use async/await for cleaner code: You can simplify the syntax using async/await.

Here’s an example using async/await for a GET request:

async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.statusText);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('There was a problem with the fetch operation:', error);
  }
}

fetchData();

Conclusion

The Fetch API is a powerful tool for making HTTP requests in JavaScript. Its promise-based nature and modern syntax make it a preferred choice for developers. By following the best practices outlined in this tutorial, you can effectively retrieve and send data to servers while handling errors gracefully.

Learn more with useful resources