Sobes.tech
Junior

What does the fetch method accept?

sobes.tech AI

Answer from AI

The fetch method takes one mandatory argument — the request path (RequestInfo or URL) — and one optional argument — a settings object (RequestInit).

Mandatory argument (input):

  • String: URL of the resource.
  • Request object: An instance of the Request class, providing more flexible request configuration (headers, method, etc.).

Optional argument (init): An object with fields describing request settings. Some commonly used fields:

  • method: HTTP request method (GET, POST, PUT, DELETE, OPTIONS, etc.).
  • headers: Request headers. Can be an object of key-value pairs or an instance of the Headers class.
  • body: Request body (for methods other than GET or HEAD). Can be a string, ArrayBuffer, TypedArray, DataView, Blob, FormData, URLSearchParams, or ReadableStream.
  • mode: Request mode (cors, no-cors, same-origin, navigate).
  • credentials: Credential sending configuration (omit, same-origin, include).
  • cache: Caching configuration (default, no-store, reload, no-cache, force-cache, only-if-cached).
  • redirect: How to handle redirects (follow, error, manual).
  • referrer: Value for the Referer header.
  • referrerPolicy: Policy for sending the Referer header.
  • integrity: Value for the Integrity header. Used for Subresource Integrity.
  • keepalive: Boolean indicating that the request should remain active after the page is closed (for sending analytics or reports).
  • signal: An AbortSignal instance for canceling the request.
  • window: The Window object associated with the request (defaults to the current window).

Example usage:

// GET request
fetch('/api/users')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

// POST request with body and headers
fetch('/api/products', {
  method: 'POST', // HTTP method
  headers: {
    'Content-Type': 'application/json', // Data type
    'Authorization': 'Bearer your_token' // Example authorization header
  },
  body: JSON.stringify({ name: 'New product', price: 100 }) // Request body
})
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));
What does the fetch method accept? — QA / QA Automation - sobes.tech