### Install whatwg-fetch Polyfill Source: https://github.com/jakechampion/fetch/blob/main/README.md Installs the `whatwg-fetch` package using npm. This package provides a polyfill for the `window.fetch` API, enabling its use in older browsers. It requires a separate Promise polyfill for older browser versions. ```bash npm install whatwg-fetch --save ``` -------------------------------- ### Fetch and Parse JSON using JavaScript Source: https://github.com/jakechampion/fetch/blob/main/README.md Shows how to use the `fetch` API to request JSON data from a server. The example illustrates handling the response, parsing it as JSON using `response.json()`, and logging the parsed data or any errors during parsing. ```javascript 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) }) ``` -------------------------------- ### Headers Management Source: https://context7.com/jakechampion/fetch/llms.txt Details how to use the `Headers` constructor to create, manipulate, and manage HTTP request and response headers. It covers methods like `append`, `get`, `set`, `delete`, and `has` for effective header control. ```APIDOC ## Headers API ### Description Provides an interface for manipulating HTTP headers. ### Method N/A (This is an object/class for header management, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example (Creating and using headers) ```javascript // Create and manipulate request headers var headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'); headers.append('X-Custom-Header', 'value1'); headers.append('X-Custom-Header', 'value2'); console.log(headers.get('Content-Type')); // Output: application/json console.log(headers.get('X-Custom-Header')); // Output: value1, value2 headers.set('X-Custom-Header', 'new-value'); console.log(headers.has('Authorization')); // Output: true headers.delete('Authorization'); // Use headers in fetch request fetch('https://api.example.com/data', { method: 'GET', headers: headers }) .then(function(response) { console.log('Response content-type:', response.headers.get('Content-Type')); console.log('Cache-Control:', response.headers.get('Cache-Control')); return response.json(); }); ``` ### Response #### Success Response (200 OK - for the fetch example) - **Content-Type** (string) - The content type of the response. - **Cache-Control** (string) - Caching directives for the response. #### Response Example (for the fetch example) ```json { "data": "some data" } ``` ``` -------------------------------- ### Fetch HTML Content using JavaScript Source: https://github.com/jakechampion/fetch/blob/main/README.md An example of using the `fetch` API to retrieve HTML content from a server. It demonstrates how to handle the Promise returned by `fetch`, convert the response to text, and then update the DOM with the received HTML. ```javascript fetch('/users.html') .then(function(response) { return response.text() }).then(function(body) { document.body.innerHTML = body }) ``` -------------------------------- ### GET Request with fetch() Source: https://context7.com/jakechampion/fetch/llms.txt Demonstrates how to perform a GET request to fetch JSON data from a specified URL using the fetch() function. It includes error handling for non-successful HTTP responses and parsing the JSON response. ```APIDOC ## GET /users/{id} ### Description Fetches user data from the API. ### Method GET ### Endpoint `https://api.example.com/users/{id}` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user to fetch. #### Query Parameters None #### Request Body None ### Request Example ```javascript fetch('https://api.example.com/users/123') .then(function(response) { if (!response.ok) { throw new Error('HTTP error! status: ' + response.status); } return response.json(); }) .then(function(data) { console.log('User:', data); }) .catch(function(error) { console.error('Fetch failed:', error); }); ``` ### Response #### Success Response (200) - **id** (number) - The user's unique identifier. - **name** (string) - The user's full name. - **email** (string) - The user's email address. #### Response Example ```json { "id": 123, "name": "John Doe", "email": "john@example.com" } ``` ``` -------------------------------- ### Request Object Creation Source: https://context7.com/jakechampion/fetch/llms.txt Demonstrates how to create reusable Request objects that can be cloned and modified for different HTTP requests. Includes examples for authenticated requests and modifying existing requests. ```APIDOC ## Request - Create reusable request objects The Request constructor creates a request object that can be passed to fetch() and cloned for reuse. It encapsulates URL, method, headers, body, and credentials settings. ### Example Usage ```javascript // Create a reusable authenticated request var apiRequest = new Request('https://api.example.com/protected/data', { method: 'GET', headers: { 'Authorization': 'Bearer token123', 'Accept': 'application/json' }, credentials: 'include', mode: 'cors' }); // Use the request object fetch(apiRequest) .then(function(response) { return response.json(); }) .then(function(data) { console.log('Protected data:', data); }); // Clone and modify for a different endpoint var clonedRequest = apiRequest.clone(); var modifiedRequest = new Request(clonedRequest, { method: 'POST', body: JSON.stringify({ action: 'update' }) }); fetch(modifiedRequest) .then(function(response) { console.log('Update status:', response.status); }); ``` ``` -------------------------------- ### Manage HTTP Headers - Headers Object Source: https://context7.com/jakechampion/fetch/llms.txt Demonstrates the creation and manipulation of HTTP headers using the Headers constructor. It covers common operations like appending, getting, setting, deleting, and checking for the existence of headers. These headers can then be used in fetch() requests. ```javascript var headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'); headers.append('X-Custom-Header', 'value1'); headers.append('X-Custom-Header', 'value2'); console.log(headers.get('Content-Type')); // Output: application/json console.log(headers.get('X-Custom-Header')); // Output: value1, value2 headers.set('X-Custom-Header', 'new-value'); console.log(headers.has('Authorization')); // Output: true headers.delete('Authorization'); // Use headers in fetch request fetch('https://api.example.com/data', { method: 'GET', headers: headers }) .then(function(response) { console.log('Response content-type:', response.headers.get('Content-Type')); console.log('Cache-Control:', response.headers.get('Cache-Control')); return response.json(); }); ``` -------------------------------- ### Fetch JSON Data - GET Request Source: https://context7.com/jakechampion/fetch/llms.txt Demonstrates how to make a GET request to retrieve JSON data using the fetch() function. It handles successful responses by parsing JSON and includes error handling for network or HTTP errors. This is a fundamental pattern for consuming APIs. ```javascript fetch('https://api.example.com/users/123') .then(function(response) { if (!response.ok) { throw new Error('HTTP error! status: ' + response.status); } return response.json(); }) .then(function(data) { console.log('User:', data); // Output: User: { id: 123, name: 'John Doe', email: 'john@example.com' } }) .catch(function(error) { console.error('Fetch failed:', error); }); ``` -------------------------------- ### Process HTTP Responses with Fetch API Source: https://context7.com/jakechampion/fetch/llms.txt Explains how to work with Response objects from the Fetch API. It covers accessing response metadata like status, statusText, ok, headers, and url. The example demonstrates reading the response body as a Blob and creating a download link for a PDF. It also shows how to create a custom Response object, which is useful for service workers. ```javascript fetch('https://api.example.com/document.pdf') .then(function(response) { console.log('Status:', response.status); console.log('Status text:', response.statusText); console.log('Response OK:', response.ok); console.log('Content-Type:', response.headers.get('Content-Type')); console.log('Response URL:', response.url); return response.blob(); }) .then(function(blob) { console.log('Blob size:', blob.size, 'bytes'); var url = URL.createObjectURL(blob); var link = document.createElement('a'); link.href = url; link.download = 'document.pdf'; link.click(); }); var customResponse = new Response( JSON.stringify({ message: 'Custom response' }), { status: 201, statusText: 'Created', headers: { 'Content-Type': 'application/json' } } ); ``` -------------------------------- ### Read binary data from Response using arrayBuffer() Source: https://context7.com/jakechampion/fetch/llms.txt Shows how to read the response body as a raw ArrayBuffer, which is useful for handling binary data like images or audio. The example fetches an image, checks for a successful response, converts the body to an ArrayBuffer, logs its size, and then demonstrates creating a Blob and an object URL to display the image in the DOM. ```javascript // Fetch and process binary image data fetch('https://example.com/images/photo.jpg') .then(function(response) { if (!response.ok) { throw new Error('Failed to fetch image'); } return response.arrayBuffer(); }) .then(function(buffer) { console.log('Image size:', buffer.byteLength, 'bytes'); // Process binary data var uint8Array = new Uint8Array(buffer); console.log('First 4 bytes:', Array.from(uint8Array.slice(0, 4))); // Output: First 4 bytes: [255, 216, 255, 224] (JPEG signature) // Create blob and display image var blob = new Blob([buffer], { type: 'image/jpeg' }); var imageUrl = URL.createObjectURL(blob); var img = document.createElement('img'); img.src = imageUrl; document.body.appendChild(img); }) .catch(function(error) { console.error('Error loading image:', error); }); ``` -------------------------------- ### Create Reusable Request Objects with Fetch API Source: https://context7.com/jakechampion/fetch/llms.txt Demonstrates how to create a reusable Request object using the Request constructor. This object can be passed to fetch() and cloned for modifications. It encapsulates URL, method, headers, body, and credentials. The example shows creating an authenticated request, using it, cloning it, and modifying it for a POST request. ```javascript var apiRequest = new Request('https://api.example.com/protected/data', { method: 'GET', headers: { 'Authorization': 'Bearer token123', 'Accept': 'application/json' }, credentials: 'include', mode: 'cors' }); fetch(apiRequest) .then(function(response) { return response.json(); }) .then(function(data) { console.log('Protected data:', data); }); var clonedRequest = apiRequest.clone(); var modifiedRequest = new Request(clonedRequest, { method: 'POST', body: JSON.stringify({ action: 'update' }) }); fetch(modifiedRequest) .then(function(response) { console.log('Update status:', response.status); }); ``` -------------------------------- ### Ruby: Set X-Request-URL Header for Fetch API Source: https://github.com/jakechampion/fetch/blob/main/README.md A server-side example in Ruby (Rails controller) demonstrating how to set the `X-Request-URL` response header. This workaround is necessary for older browsers to ensure the `response.url` property is reliable after HTTP redirects when using the Fetch API. ```ruby # Ruby on Rails controller example response.headers['X-Request-URL'] = request.url ``` -------------------------------- ### POST Form Data using JavaScript Fetch Source: https://github.com/jakechampion/fetch/blob/main/README.md An example of sending form data using the `fetch` API with the POST method. It utilizes the `FormData` object to easily construct the request body from a form element, suitable for submitting form data. ```javascript var form = document.querySelector('form') fetch('/users', { method: 'POST', body: new FormData(form) }) ``` -------------------------------- ### Fetch API Cookie Handling Source: https://context7.com/jakechampion/fetch/llms.txt Explains how to manage cookie handling in Fetch API requests. It specifies that explicit `credentials` settings are required: 'same-origin' for same-domain requests and 'include' for cross-origin requests to send cookies. The examples show sending cookies for both scenarios, including a POST request for login. ```javascript fetch('https://example.com/api/profile', { credentials: 'same-origin' }) .then(function(response) { return response.json(); }) .then(function(profile) { console.log('User profile:', profile); }); fetch('https://api.example.com/login', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'user@example.com', password: 'secret123' }) }) .then(function(response) { return response.json(); }) .then(function(data) { console.log('Logged in, session cookie stored'); console.log('User token:', data.token); }); ``` -------------------------------- ### Handle HTTP Errors with Fetch API Source: https://context7.com/jakechampion/fetch/llms.txt Details how to handle HTTP errors (like 404 or 500) with the Fetch API, as the Promise only rejects on network failures. The example provides a robust error handling pattern by implementing `checkStatus` and `parseJSON` helper functions. It demonstrates catching errors, checking `error.response.status`, and reading error response bodies. ```javascript function checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response; } var error = new Error(response.statusText); error.response = response; throw error; } function parseJSON(response) { return response.json(); } fetch('https://api.example.com/users/999') .then(checkStatus) .then(parseJSON) .then(function(data) { console.log('Success:', data); }) .catch(function(error) { if (error.response) { console.error('HTTP error:', error.response.status); if (error.response.status === 404) { console.error('User not found'); } else if (error.response.status === 500) { console.error('Server error'); } error.response.json().then(function(errorData) { console.error('Error details:', errorData); }); } else { console.error('Network error:', error.message); } }); ``` -------------------------------- ### Import patterns for whatwg-fetch polyfill Source: https://context7.com/jakechampion/fetch/llms.txt Illustrates different ways to import and use the whatwg-fetch polyfill. It covers automatic polyfilling by importing the library as a side-effect, which patches `window.fetch`. It also shows how to use named exports to access the polyfill implementation directly and conditionally use native fetch or the polyfill. Additionally, it includes Webpack configuration for automatic polyfilling and using the polyfill with a Promise polyfill for older browsers. ```javascript // Automatic polyfill - imports and patches window.fetch import 'whatwg-fetch'; window.fetch('https://api.example.com/data') .then(function(response) { return response.json(); }); // Named import - access polyfill implementation explicitly import { fetch as fetchPolyfill, Headers, Request, Response } from 'whatwg-fetch'; // Use native fetch if available, otherwise use polyfill var actualFetch = window.fetch && !window.fetch.polyfill ? window.fetch : fetchPolyfill; actualFetch('https://api.example.com/users') .then(function(response) { return response.json(); }); // Webpack configuration for automatic polyfilling module.exports = { entry: [ 'whatwg-fetch', // Load polyfill first './src/index.js' ] }; // Use with Promise polyfill for older browsers import 'promise-polyfill/src/polyfill'; import 'whatwg-fetch'; fetch('https://api.example.com/data') .then(function(response) { return response.json(); }) .then(function(data) { console.log('Data loaded:', data); }); ``` -------------------------------- ### Import whatwg-fetch Polyfill in JavaScript Source: https://github.com/jakechampion/fetch/blob/main/README.md Demonstrates how to import the `whatwg-fetch` polyfill into a JavaScript application. Importing the module automatically polyfills `window.fetch` and related APIs. It also shows how to access the polyfill implementation directly if needed. ```javascript import 'whatwg-fetch' window.fetch(...) ``` ```javascript import {fetch as fetchPolyfill} from 'whatwg-fetch' window.fetch(...) // use native browser version fetchPolyfill(...) // use polyfill implementation ``` -------------------------------- ### Cookie Handling Source: https://context7.com/jakechampion/fetch/llms.txt Explains how to manage cookies with the Fetch API, including settings for 'same-origin' and 'include' credentials to send cookies with requests, whether they are same-domain or cross-origin. ```APIDOC ## fetch() - Cookie handling Cookie handling requires explicit credentials settings. Use 'same-origin' for same-domain requests or 'include' for CORS requests to send cookies. ### Example Usage ```javascript // Send cookies with same-origin requests fetch('https://example.com/api/profile', { credentials: 'same-origin' }) .then(function(response) { return response.json(); }) .then(function(profile) { console.log('User profile:', profile); }); // Send cookies with cross-origin requests fetch('https://api.example.com/login', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'user@example.com', password: 'secret123' }) }) .then(function(response) { // Cookies are automatically stored by browser return response.json(); }) .then(function(data) { console.log('Logged in, session cookie stored'); console.log('User token:', data.token); }); ``` ``` -------------------------------- ### POST Request with JSON Data using fetch() Source: https://context7.com/jakechampion/fetch/llms.txt Illustrates how to send JSON data to a server using a POST request. This involves setting the 'Content-Type' header to 'application/json', stringifying the JavaScript object into a JSON string for the request body, and handling the server's response. ```APIDOC ## POST /users ### Description Creates a new user with the provided JSON data. ### Method POST ### Endpoint `https://api.example.com/users` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the new user. - **email** (string) - Required - The email address of the new user. - **role** (string) - Optional - The role of the new user (e.g., 'admin'). ### Request Example ```javascript fetch('https://api.example.com/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Jane Smith', email: 'jane@example.com', role: 'admin' }), credentials: 'same-origin' }) .then(function(response) { if (response.status >= 200 && response.status < 300) { return response.json(); } throw new Error('Server returned ' + response.status); }) .then(function(data) { console.log('Created user ID:', data.id); }) .catch(function(error) { console.error('Failed to create user:', error); }); ``` ### Response #### Success Response (201 Created) - **id** (number) - The ID of the newly created user. #### Response Example ```json { "id": 456 } ``` ``` -------------------------------- ### Access Response Metadata with JavaScript Fetch Source: https://github.com/jakechampion/fetch/blob/main/README.md Demonstrates how to access metadata from an HTTP response obtained via the `fetch` API. It shows how to retrieve response headers like 'Content-Type' and 'Date', as well as the HTTP status code and status text. ```javascript fetch('/users.json').then(function(response) { console.log(response.headers.get('Content-Type')) console.log(response.headers.get('Date')) console.log(response.status) console.log(response.statusText) }) ``` -------------------------------- ### JavaScript: Upload File with Fetch API Source: https://github.com/jakechampion/fetch/blob/main/README.md Demonstrates how to upload a file using the Fetch API. It constructs a FormData object to append the file and user information, then sends a POST request to the '/avatars' endpoint. This requires a file input element in the HTML. ```javascript 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 }) ``` -------------------------------- ### Response Object Processing Source: https://context7.com/jakechampion/fetch/llms.txt Explains how to create and process Response objects from HTTP requests. Covers accessing metadata like status and headers, and reading the response body in various formats (JSON, Blob, etc.). ```APIDOC ## Response - Process HTTP responses The Response constructor creates response objects with status, headers, and body data. Response objects provide methods to read the body as text, JSON, Blob, ArrayBuffer, or FormData. ### Example Usage ```javascript // Working with response metadata and different body types fetch('https://api.example.com/document.pdf') .then(function(response) { console.log('Status:', response.status); console.log('Status text:', response.statusText); console.log('Response OK:', response.ok); console.log('Content-Type:', response.headers.get('Content-Type')); console.log('Response URL:', response.url); return response.blob(); // Read response as blob for binary data }) .then(function(blob) { console.log('Blob size:', blob.size, 'bytes'); var url = URL.createObjectURL(blob); var link = document.createElement('a'); link.href = url; link.download = 'document.pdf'; link.click(); }); // Create custom response (useful for service workers) var customResponse = new Response( JSON.stringify({ message: 'Custom response' }), { status: 201, statusText: 'Created', headers: { 'Content-Type': 'application/json' } } ); ``` ``` -------------------------------- ### JavaScript: Send Credentials with Fetch API for CORS Source: https://github.com/jakechampion/fetch/blob/main/README.md Illustrates how to configure the Fetch API to send credentials (cookies, authorization headers) with cross-origin requests using the `credentials: 'include'` option. It also shows the default 'same-origin' behavior and advises explicit configuration for older browser compatibility. ```javascript fetch('https://example.com:1234/users', { credentials: 'include' }) ``` ```javascript fetch('/users', { credentials: 'same-origin' }) ``` -------------------------------- ### Abort fetch() requests with AbortController Source: https://context7.com/jakechampion/fetch/llms.txt Demonstrates how to cancel a fetch request using AbortController and AbortSignal. It includes setting a timeout to automatically abort a long-running request and handling the 'AbortError' in the catch block. An AbortController polyfill is mentioned as a dependency for browsers lacking native support. ```javascript // Abort a long-running request import 'yet-another-abortcontroller-polyfill'; import { fetch } from 'whatwg-fetch'; var controller = new AbortController(); var signal = controller.signal; // Set timeout to abort after 5 seconds var timeoutId = setTimeout(function() { controller.abort(); }, 5000); fetch('https://api.example.com/large-dataset', { signal: signal, credentials: 'same-origin' }) .then(function(response) { clearTimeout(timeoutId); return response.json(); }) .then(function(data) { console.log('Data loaded:', data.length, 'items'); }) .catch(function(error) { if (error.name === 'AbortError') { console.log('Request aborted - took too long'); } else { console.error('Request failed:', error); } }); // Manual abort on user action document.querySelector('#cancel-button').addEventListener('click', function() { controller.abort(); }); ``` -------------------------------- ### HTTP Error Handling Source: https://context7.com/jakechampion/fetch/llms.txt Details how to handle HTTP error statuses (like 404, 500) with the Fetch API, as the Promise itself only rejects on network failures. Provides a robust pattern for checking `response.ok` or `response.status`. ```APIDOC ## fetch() - Handle HTTP errors The fetch Promise does not reject on HTTP error statuses (404, 500, etc.) but only on network failures. Custom error handling is required to check response.ok or response.status. ### Error Handling Pattern ```javascript function checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response; } var error = new Error(response.statusText); error.response = response; throw error; } function parseJSON(response) { return response.json(); } // Example usage with error handling fetch('https://api.example.com/users/999') .then(checkStatus) .then(parseJSON) .then(function(data) { console.log('Success:', data); }) .catch(function(error) { if (error.response) { console.error('HTTP error:', error.response.status); if (error.response.status === 404) { console.error('User not found'); } else if (error.response.status === 500) { console.error('Server error'); } error.response.json().then(function(errorData) { console.error('Error details:', errorData); }); } else { console.error('Network error:', error.message); } }); ``` ``` -------------------------------- ### Aborting Fetch Requests with AbortController (JavaScript) Source: https://github.com/jakechampion/fetch/blob/main/README.md This snippet shows how to use AbortController to cancel a fetch request. It checks for native browser support for the abortable fetch API and falls back to a polyfill if necessary. The AbortController is instantiated, its signal is passed to the fetch options, and the request is aborted later by calling controller.abort(). The catch block specifically handles AbortError. ```javascript import 'yet-another-abortcontroller-polyfill' import {fetch} from 'whatwg-fetch' // use native browser implementation if it supports aborting const abortableFetch = ('signal' in new Request('')) ? window.fetch : fetch const controller = new AbortController() abortableFetch('/avatars', { signal: controller.signal }).catch(function(ex) { if (ex.name === 'AbortError') { console.log('request aborted') } }) // some time later... controller.abort() ``` -------------------------------- ### POST Request with Form Data using fetch() Source: https://context7.com/jakechampion/fetch/llms.txt Explains how to submit form data, including file uploads, using the fetch API. When a FormData object is used as the request body, the 'Content-Type' header is automatically set to 'multipart/form-data', and the browser handles the boundary creation. ```APIDOC ## POST /upload ### Description Uploads form data, potentially including files, to the server. ### Method POST ### Endpoint `https://api.example.com/upload` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file** (File) - Required - The file to upload. - **description** (string) - Optional - A description for the uploaded file. - **userId** (string) - Required - The ID of the user associated with the upload. ### Request Example ```javascript var formElement = document.querySelector('#upload-form'); var fileInput = document.querySelector('input[type="file"]'); var formData = new FormData(); formData.append('file', fileInput.files[0]); formData.append('description', 'Profile picture'); formData.append('userId', '123'); fetch('https://api.example.com/upload', { method: 'POST', body: formData, credentials: 'same-origin' }) .then(function(response) { return response.json(); }) .then(function(result) { console.log('Upload successful:', result.fileUrl); }) .catch(function(error) { console.error('Upload failed:', error); }); ``` ### Response #### Success Response (200 OK) - **fileUrl** (string) - The URL of the successfully uploaded file. #### Response Example ```json { "fileUrl": "https://cdn.example.com/files/abc123.jpg" } ``` ``` -------------------------------- ### Submit Form Data with File Upload - POST Request Source: https://context7.com/jakechampion/fetch/llms.txt Shows how to submit form data, including file uploads, using fetch(). A FormData object is used to construct the body, which automatically sets the 'Content-Type' to 'multipart/form-data'. This is useful for handling file uploads and complex form submissions. ```javascript var formElement = document.querySelector('#upload-form'); var fileInput = document.querySelector('input[type="file"]'); var formData = new FormData(); formData.append('file', fileInput.files[0]); formData.append('description', 'Profile picture'); formData.append('userId', '123'); fetch('https://api.example.com/upload', { method: 'POST', body: formData, credentials: 'same-origin' }) .then(function(response) { return response.json(); }) .then(function(result) { console.log('Upload successful:', result.fileUrl); // Output: Upload successful: https://cdn.example.com/files/abc123.jpg }) .catch(function(error) { console.error('Upload failed:', error); }); ``` -------------------------------- ### Send JSON Data - POST Request Source: https://context7.com/jakechampion/fetch/llms.txt Illustrates how to send JSON data in a POST request using fetch(). It requires specifying the 'POST' method, setting the 'Content-Type' header to 'application/json', and stringifying the JavaScript object before sending it as the request body. It also includes handling for the response. ```javascript fetch('https://api.example.com/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Jane Smith', email: 'jane@example.com', role: 'admin' }), credentials: 'same-origin' }) .then(function(response) { if (response.status >= 200 && response.status < 300) { return response.json(); } throw new Error('Server returned ' + response.status); }) .then(function(data) { console.log('Created user ID:', data.id); // Output: Created user ID: 456 }) .catch(function(error) { console.error('Failed to create user:', error); }); ``` -------------------------------- ### POST JSON Data using JavaScript Fetch Source: https://github.com/jakechampion/fetch/blob/main/README.md Illustrates how to send JSON data in the body of an HTTP POST request using the `fetch` API. It sets the 'Content-Type' header to 'application/json' and uses `JSON.stringify` to serialize the JavaScript object into a JSON string. ```javascript fetch('/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Hubot', login: 'hubot', }) }) ``` -------------------------------- ### JavaScript: Handle HTTP Errors with Fetch API Source: https://github.com/jakechampion/fetch/blob/main/README.md Provides a custom error handling mechanism for the Fetch API to reject Promises on non-2xx HTTP status codes. It includes helper functions `checkStatus` and `parseJSON` for better error management and JSON parsing. This pattern is useful for ensuring that only successful responses are processed. ```javascript function checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response } else { var error = new Error(response.statusText) error.response = response throw error } } function parseJSON(response) { return response.json() } fetch('/users') .then(checkStatus) .then(parseJSON) .then(function(data) { console.log('request succeeded with JSON response', data) }).catch(function(error) { console.log('request failed', error) }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.