Fetch API and HTTP Requests
Making HTTP requests with the Fetch API
Challenge
Section titled “Challenge”You need to fetch data from APIs, handle errors gracefully, manage request timeouts, and cancel in-flight requests.
Explanation
Section titled “Explanation”The Fetch API provides a modern interface for making HTTP requests. It returns Promises, making it easier to work with async operations.
Basic Fetch
Section titled “Basic Fetch”// GET requestfetch('/api/users') .then(response => { if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.json(); }) .then(data => console.log(data)) .catch(error => console.error(error));
// With async/awaitasync function getUsers() { const response = await fetch('/api/users'); if (!response.ok) throw new Error(`HTTP ${response.status}`); return await response.json();}POST Request
Section titled “POST Request”async function createUser(userData) { const response = await fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(userData) });
if (!response.ok) throw new Error('Failed to create user'); return await response.json();}Handling Errors
Section titled “Handling Errors”async function fetchData(url) { try { const response = await fetch(url);
if (!response.ok) { if (response.status === 404) { throw new Error('Resource not found'); } else if (response.status === 401) { throw new Error('Unauthorized'); } else { throw new Error(`HTTP ${response.status}`); } }
return await response.json(); } catch (error) { if (error instanceof TypeError) { console.error('Network error:', error); } else { console.error('Error:', error.message); } throw error; }}Request Timeout
Section titled “Request Timeout”async function fetchWithTimeout(url, timeout = 5000) { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), timeout);
try { const response = await fetch(url, { signal: controller.signal }); clearTimeout(timeoutId); return await response.json(); } catch (error) { if (error.name === 'AbortError') { throw new Error('Request timeout'); } throw error; }}Cancel Request
Section titled “Cancel Request”const controller = new AbortController();
const button = document.getElementById('fetch-button');const cancelButton = document.getElementById('cancel-button');
button.addEventListener('click', async () => { try { const response = await fetch('/api/data', { signal: controller.signal }); console.log(await response.json()); } catch (error) { if (error.name === 'AbortError') { console.log('Request cancelled'); } }});
cancelButton.addEventListener('click', () => { controller.abort();});