Web Fetch API

The Fetch API is a modern, promise-based interface in JavaScript that allows you to make HTTP requests to servers, such as retrieving or sending data. It replaces older methods like XMLHttpRequest, making asynchronous calls simpler and cleaner.

1. What is the Fetch API?

The Fetch API provides a fetch() method that allows you to asynchronously request resources over the network. It returns a Promise, which resolves to the Response object representing the response to the request.

2. Basic Syntax

javascriptCopyEditfetch(url, options)
  .then(response => {
    // handle the response
  })
  .catch(error => {
    // handle errors
  });
  • url: The URL to which the request is sent.
  • options: (optional) An object containing any custom settings such as method, headers, body, etc.

3. GET Request Example

A simple GET request to fetch data from a public API:

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

4. POST Request Example

To send data to a server, use the POST method:

javascriptCopyEditfetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'Fetch API Tutorial',
    body: 'This is a sample post',
    userId: 1
  })
})
  .then(response => response.json())
  .then(data => {
    console.log('Success:', data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

5. Common Options in Fetch

  • method: HTTP method (GET, POST, PUT, DELETE, etc.)
  • headers: Custom headers (e.g., Content-Type, Authorization)
  • body: Data sent with requests (used in POST, PUT)
  • mode: CORS mode (cors, no-cors, same-origin)
  • credentials: Include cookies (omit, same-origin, include)

6. Handling JSON Responses

Often, APIs return JSON. Use .json() to parse the body:

javascriptCopyEditfetch('/data.json')
  .then(res => res.json())
  .then(data => console.log(data));

If the response isn’t JSON, you can use .text() or .blob() instead.

7. Error Handling

Always include .catch() to handle network errors. To catch HTTP errors (e.g., 404, 500), check response.ok:

javascriptCopyEditfetch('/api')
  .then(response => {
    if (!response.ok) {
      throw new Error('HTTP error: ' + response.status);
    }
    return response.json();
  })
  .catch(error => {
    console.error('Fetch failed:', error);
  });

8. Async/Await with Fetch

For cleaner code, especially in larger projects, you can use async/await:

javascriptCopyEditasync function getData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    if (!response.ok) {
      throw new Error('HTTP error: ' + response.status);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

getData();

9. CORS Issues

If your request is going to another domain, the server must allow cross-origin requests. If it doesn’t, you’ll run into CORS (Cross-Origin Resource Sharing) errors. Always check server-side CORS settings if requests fail unexpectedly.

10. Summary

The Fetch API is a powerful, modern tool for working with HTTP requests in JavaScript. It’s simpler and cleaner than older techniques and works well with promises and async/await.

Key Takeaways:

  • Use fetch() for GET and POST requests.
  • Always handle errors with .catch() or try/catch.
  • Use .json() to parse JSON responses.
  • Customize requests using headers, body, and method.

Leave a Reply

Your email address will not be published. Required fields are marked *