Skip to content
Plurafy

Fetch API and HTTP Requests

Making HTTP requests with the Fetch API

You need to fetch data from APIs, handle errors gracefully, manage request timeouts, and cancel in-flight requests.

The Fetch API provides a modern interface for making HTTP requests. It returns Promises, making it easier to work with async operations.

// GET request
fetch('/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/await
async function getUsers() {
const response = await fetch('/api/users');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
}
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();
}
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;
}
}
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;
}
}
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();
});