L'API nativa fetch() di JavaScript offre un'interfaccia asincrona per effettuare chiamate di rete nei browser moderni e in Node.js.
Richieste Fondamentali
Richiesta GET (JSON)
async function loadUserData() {
const response = await fetch('https://api.example.com/user/1');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
}
Richiesta POST (Invio di JSON)
async function createUser(payload) {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(payload)
});
return await response.json();
}
Invio di Dati Form (multipart/form-data)
const formData = new FormData();
formData.append('username', 'alice');
formData.append('avatar', fileInput.files[0]);
// Omettere l'header Content-Type per lasciare che il browser imposti automaticamente il boundary
await fetch('/upload', {
method: 'POST',
body: formData
});
Annullamento Richieste e Timeout (AbortController)
const controller = new AbortController();
const signal = controller.signal;
// Annulla la richiesta automaticamente dopo 5 secondi
const timeoutId = setTimeout(() => controller.abort(), 5000);
try {
const res = await fetch('https://api.example.com/data', { signal });
const data = await res.json();
clearTimeout(timeoutId);
return data;
} catch (err) {
if (err.name === 'AbortError') {
console.warn('Richiesta annullata per timeout');
} else {
console.error('Fetch error:', err);
}
}
Intestazioni, Autenticazione e Credenziali
const headers = new Headers();
headers.set('Authorization', 'Bearer token_xyz123'); // Header di autenticazione con token Bearer
headers.set('X-Custom-Header', 'custom-value');
const response = await fetch('/api/secure', {
headers,
credentials: 'include' // Invia cookie nelle richieste cross-origin
});