Home  Js   Fetch api i ...

fetch API in JavaScript

The fetch API in JavaScript is a powerful tool for making HTTP requests to servers. It provides a simpler and more flexible way to make network requests compared to the older XMLHttpRequest API. Here’s a detailed explanation of the fetch API and its options:

Basic Usage

The most basic usage of fetch involves calling it with a URL:

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

Fetch Options

The fetch function can take a second argument, an options object, to configure the request. Here are all the possible options:

  1. Method

    • method: The HTTP method to use (e.g., GET, POST, PUT, DELETE).
    fetch('https://api.example.com/data', {
      method: 'POST'
    });
    
  2. Headers

    • headers: An object representing the headers to include in the request.
    fetch('https://api.example.com/data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer token'
      }
    });
    
  3. Body

    • body: The body of the request. This can be a Blob, BufferSource, FormData, URLSearchParams, ReadableStream, or USVString.
    fetch('https://api.example.com/data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ key: 'value' })
    });
    
  4. Mode

    • mode: The mode of the request (e.g., cors, no-cors, same-origin).
    fetch('https://api.example.com/data', {
      mode: 'cors'
    });
    
  5. Credentials

    • credentials: Indicates whether to send cookies with the request. Options are omit, same-origin, or include.
    fetch('https://api.example.com/data', {
      credentials: 'include'
    });
    
  6. Cache

    • cache: The cache mode of the request (e.g., default, no-store, reload, no-cache, force-cache, only-if-cached).
    fetch('https://api.example.com/data', {
      cache: 'no-cache'
    });
    
  7. Redirect

    • redirect: How to handle redirects (e.g., follow, error, manual).
    fetch('https://api.example.com/data', {
      redirect: 'follow'
    });
    
  8. Referrer

    • referrer: A string specifying the referrer of the request.
    fetch('https://api.example.com/data', {
      referrer: 'client'
    });
    
  9. Referrer Policy

    • referrerPolicy: The referrer policy (e.g., no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, unsafe-url).
    fetch('https://api.example.com/data', {
      referrerPolicy: 'no-referrer'
    });
    
  10. Integrity

    • integrity: Contains the subresource integrity value of the request.
    fetch('https://api.example.com/data', {
      integrity: 'sha256-abcdef'
    });
    
  11. Keepalive

    • keepalive: Boolean that indicates whether the request can outlive the page.
    fetch('https://api.example.com/data', {
      keepalive: true
    });
    
  12. Signal

    • signal: An AbortSignal to abort the request.
    const controller = new AbortController();
    const signal = controller.signal;
    
    fetch('https://api.example.com/data', { signal })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => {
        if (error.name === 'AbortError') {
          console.log('Request aborted');
        }
      });
    
    // Abort the request
    controller.abort();
    

Complete Example

Here's a complete example using many of these options:

const controller = new AbortController();
const signal = controller.signal;

fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token'
  },
  body: JSON.stringify({ key: 'value' }),
  mode: 'cors',
  credentials: 'include',
  cache: 'no-cache',
  redirect: 'follow',
  referrer: 'client',
  referrerPolicy: 'no-referrer',
  integrity: 'sha256-abcdef',
  keepalive: true,
  signal
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('Request aborted');
    } else {
      console.error('Error:', error);
    }
  });

// To abort the request
controller.abort();
Published on: Aug 01, 2024, 01:20 AM  
 

Comments

Add your comment