🌐 Fetch API = Modern HTTP
XMLHttpRequest is old. Fetch API is modern. Promise-based, cleaner, 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));
📝 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);
}
// Headers
const response = await fetch('/api/users', {
headers: {
'Authorization': 'Bearer token',
'Content-Type': 'application/json'
}
});
// Request with credentials
fetch('/api/users', {
credentials: 'include'
});
// Fetch Tips
- Use async/await for readability
- Check response.ok for errors
- Set appropriate headers
- Use credentials when needed
- Handle errors properly
💡 Fetch Tips
- Use async/await for readability
- Check response.ok for errors
- Set appropriate headers
- Use credentials when needed
- Handle errors properly
“Fetch API is modern. Promise-based, clean, powerful. Essential for any web app.”
