whatwg-fetch

repository·main·Indexed 12 days ago

https://github.com/jakechampion/fetch

A window.fetch polyfill (version 3.6.20) that implements a subset of the Fetch specification. It allows developers to use Promise-based web requests in older browsers that only support XMLHttpRequest, providing implementations for the fetch() function, Request, Response, and Headers classes.

Tokens
3.1K
Snippets
14
Records
14
Agent score
48%

What's inside whatwg-fetch

  1. Import and use whatwg-fetch

    main

    You can automatically polyfill window.fetch by importing the package. If you need to access the polyfill implementation specifically (e.g., to use abort functionality in browsers with outdated native fetch), you can import it as a named export.

    // Automatically polyfills window.fetch
    import 'whatwg-fetch';
    
    // Access the polyfill implementation directly
    import {fetch as fetchPolyfill} from 'whatwg-fetch';
    
    window.fetch(...);    // uses native browser version if available
    fetchPolyfill(...);  // uses polyfill implementation
  2. Handle HTTP error statuses in fetch

    main

    By default, fetch() resolves even if the server returns an error status (like 404 or 500). To make the Promise reject on non-2xx statuses, implement a custom response handler that checks response.status.

    function checkStatus(response) {
      if (response.status >= 200 && response.status < 300) {
        return response
      } else {
        var error = new Error(response.statusText)
        error.response = response
        throw error
      }
    }
    
    fetch('/users')
      .then(checkStatus)
      .then(response => response.json())
      .then(data => console.log('success', data))
      .catch(error => console.log('failed', error))
  3. Configure credentials and cookies

    main

    To ensure consistent cookie behavior across different browsers, explicitly set the credentials option:

    • Use credentials: 'include' for CORS requests to allow sending credentials to other domains.
    • Use credentials: 'same-origin' for standard requests to ensure cookies are sent to the same domain, especially when targeting older browsers (Firefox 39-60, Chrome 42-67, Safari 10.1-11.1.2) where the default might have been 'omit'.
    // For CORS
    fetch('https://example.com/users', { credentials: 'include' })
    
    // For same-origin (recommended for compatibility)
    fetch('/users', { credentials: 'same-origin' })
  4. Abort fetch requests

    main

    To abort a request, you must use the AbortController and AbortSignal APIs. Since browsers requiring this polyfill often lack native support for these APIs, you may need to include an additional polyfill like yet-another-abortcontroller-polyfill.

    import 'yet-another-abortcontroller-polyfill'
    import {fetch as fetchPolyfill} from 'whatwg-fetch'
    
    // Use native fetch if it supports signals, otherwise use polyfill
    const abortableFetch = ('signal' in new Request('')) ? window.fetch : fetchPolyfill
    
    const controller = new AbortController()
    
    abortableFetch('/avatars', {
      signal: controller.signal
    }).catch(function(ex) {
      if (ex.name === 'AbortError') {
        console.log('request aborted')
      }
    })
    
    // Trigger abort
    controller.abort()
  5. Post form data and file uploads

    main

    Use the FormData API to send form data or files via fetch. This automatically sets the appropriate content type.

    // Post form
    var form = document.querySelector('form')
    fetch('/users', {
      method: 'POST',
      body: new FormData(form)
    })
    
    // File upload
    var input = document.querySelector('input[type="file"]')
    var data = new FormData()
    data.append('file', input.files[0])
    data.append('user', 'hubot')
    
    fetch('/avatars', {
      method: 'POST',
      body: data
    })
  6. Fetch JSON data

    main

    Use fetch() to retrieve JSON and parse it using the .json() method on the response object.

    fetch('/users.json')
      .then(function(response) {
        return response.json()
      }).then(function(json) {
        console.log('parsed json', json)
      }).catch(function(ex) {
        console.log('parsing failed', ex)
      })
  7. Post JSON data

    main

    To send JSON data, set the method to 'POST', include the 'Content-Type': 'application/json' header, and stringify your body using JSON.stringify().

    fetch('/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: 'Hubot',
        login: 'hubot',
      })
    })
  8. Read the body of a Response

    main

    Once a Response is received, you can consume its body using several asynchronous methods. Note: A body can only be read once. Attempting to read it again will throw a TypeError: Already read.

    Methods:

    • response.json(): Parses the body as JSON. Returns a Promise.
    • response.text(): Returns the body as a string. Returns a Promise.
    • response.blob(): Returns the body as a Blob. Returns a Promise.
    • response.arrayBuffer(): Returns the body as an ArrayBuffer. Returns a Promise.
    • response.formData(): Parses the body as FormData. Returns a Promise.

    Cloning: To read the body multiple times, use response.clone() to create a second response object with the same body.

    fetch('/api/data')
      .then(response => {
        const textClone = response.clone();
        
        return Promise.all([
          response.json(),
          textClone.text()
        ]);
      })
      .then(([jsonData, textData]) => {
        console.log(jsonData, textData);
      });
  9. Use the fetch() function

    main

    The fetch() function initiates a network request and returns a Promise that resolves to a Response object. It can take a URL string or a Request object as the first argument, and an optional init object for configuration.

    // Basic usage
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error));
    
    // Usage with init options
    fetch('https://api.example.com/data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ key: 'value' })
    });
  10. Create a Response object

    main

    The Response constructor creates a new Response object representing the response to a request.

    Options:

    • bodyInit: The body of the response.
    • status: The status code (must be between 200 and 599). Defaults to 200.
    • statusText: The status message. Defaults to ''.
    • headers: A Headers object or a plain object.
    • url: The URL of the response.

    Static Methods:

    • Response.error(): Returns a Response object with status: 0 and ok: false.
    • Response.redirect(url, status): Returns a Response object configured for a redirect with the specified url and status (must be one of 301, 302, 303, 307, 308).
    // Create a successful response
    const res = new Response(JSON.stringify({ data: 'ok' }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
    // Create a redirect response
    const redirect = Response.redirect('https://new-location.com', 302);