Fetch API and AbortController Detection
Detect Fetch API and AbortController support for modern HTTP requests. Covers request configuration, streaming responses, and timeout handling.
Network
Detailed Explanation
Fetch API Detection
The Fetch API is the modern replacement for XMLHttpRequest, providing a cleaner promise-based interface for making HTTP requests from the browser.
Detection
const hasFetch = typeof fetch !== 'undefined';
const hasAbortController = typeof AbortController !== 'undefined';
const hasRequest = typeof Request !== 'undefined';
const hasResponse = typeof Response !== 'undefined';
Basic Usage
async function fetchData(url) {
const response = await fetch(url, {
method: 'GET',
headers: {
'Accept': 'application/json',
},
});
if (!response.ok) {
throw new Error(\`HTTP \${response.status}\`);
}
return response.json();
}
Request Cancellation
function fetchWithTimeout(url, timeout = 5000) {
const controller = new AbortController();
const timeoutId = setTimeout(
() => controller.abort(),
timeout
);
return fetch(url, { signal: controller.signal })
.finally(() => clearTimeout(timeoutId));
}
Streaming Responses
async function fetchStream(url) {
const response = await fetch(url);
const reader = response.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
processChunk(value);
}
}
Fetch vs XMLHttpRequest
| Feature | Fetch | XMLHttpRequest |
|---|---|---|
| Promise-based | Yes | No |
| Streaming | Yes | No |
| Request cancellation | AbortController | xhr.abort() |
| Upload progress | No (yet) | Yes |
| Cookie handling | Configurable | Automatic |
Credentials and CORS
credentials: 'same-origin'(default) - send cookies for same-origin onlycredentials: 'include'- always send cookiesmode: 'cors'- enable cross-origin requests with CORS headers
Use Case
The standard way to make HTTP requests in modern web applications. Used for REST API calls, file uploads, server-sent event handling, and streaming data. AbortController is critical for cancelling requests when components unmount in React/Vue.