🌐 Fetch = Modern HTTP Requests
XMLHttpRequest is old. Fetch API is modern, promise-based. Cleaner, simpler, more powerful.
❌ XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/users');
xhr.onload = function() {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send();
✅ Fetch API
fetch('/api/users')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// Or async/await:
const response = await fetch('/api/users');
const data = await response.json();
console.log(data);
🎯 Fetch Examples
// GET
const response = await fetch('/api/users');
const users = await response.json();
// POST
const newUser = { name: 'Alice', email: 'alice@example.com' };
const response = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newUser)
});
// PUT
const response = await fetch('/api/users/1', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice Updated' })
});
// DELETE
const response = await fetch('/api/users/1', {
method: 'DELETE'
});
// Error handling
try {
const response = await fetch('/api/users');
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
} catch (error) {
console.error('Fetch error:', error);
}
💡 Benefits
- Promise-based (no callbacks)
- Cleaner syntax
- Built-in JSON parsing
- Streaming responses
- Request/response interceptors
“Fetch API is modern. Promise-based, clean, powerful. Essential for any web app.”
