Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
The fetch() function is the modern, promise-based way to make HTTP requests. It replaces the older XMLHttpRequest with a cleaner, more powerful APIthat works seamlessly with async/await and provides better error handling.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));How it works:
fetch() returns a Promise.then() receives the Response object.json() parses the response body as JSON (also returns a Promise).then() receives the parsed data.catch() handles network errorsasync function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}Why async/await is better: More readable, easier error handling, and looks like synchronous code.
The Response object contains information about the HTTP response:
response.ok - true if status 200-299response.status - HTTP status coderesponse.statusText - status messageresponse.headers - Headers objectresponse.url - final URL.json() - Parse JSON.text() - Get as text.blob() - Get as Blob (files).arrayBuffer() - Get as binary.formData() - Parse form dataconst response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();response.ok!await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John Doe',
email: 'john@example.com'
})
});Key points:
method specifies HTTP methodheaders sets Content-Type for JSONbody must be a string (use JSON.stringify)await fetch('https://api.example.com/users/123', {
method: 'PUT', // or 'PATCH' for partial update
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Jane Doe' })
});await fetch('https://api.example.com/users/123', {
method: 'DELETE'
});| Option | Description | Example |
|---|---|---|
method | HTTP method | 'GET', 'POST', 'PUT' |
headers | Request headers | {'Authorization': 'Bearer ...'} |
body | Request payload | JSON.stringify(data) |
credentials | Send cookies | 'include', 'same-origin' |
mode | CORS mode | 'cors', 'no-cors' |
cache | Cache mode | 'no-cache', 'reload' |
signal | Abort signal | controller.signal |
const controller = new AbortController();
fetch('https://api.example.com/data', {
signal: controller.signal
});
// Cancel the request
controller.abort();Useful for canceling requests when user navigates away or when implementing request timeouts.
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
try {
const response = await fetch(url, { signal: controller.signal });
clearTimeout(timeoutId);
return await response.json();
} catch (error) {
if (error.name === 'AbortError') {
console.log('Request timed out');
}
}// Bearer token authentication
fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer your-token-here',
'Content-Type': 'application/json'
}
});
// Basic authentication
const credentials = btoa('username:password');
fetch('https://api.example.com/data', {
headers: {
'Authorization': `Basic ${credentials}`
}
});async function fetchWithErrorHandling(url) {
try {
const response = await fetch(url);
// Check HTTP status
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
// Parse JSON with error handling
try {
return await response.json();
} catch (parseError) {
throw new Error('Invalid JSON response');
}
} catch (error) {
if (error.name === 'TypeError') {
// Network error
console.error('Network error:', error);
} else if (error.name === 'AbortError') {
// Request aborted
console.error('Request aborted');
} else {
// Other errors
console.error('Fetch error:', error.message);
}
throw error;
}
}1. Not checking response.ok - 404 and 500 errors won't trigger catch
2. Forgetting await on .json() - It returns a Promise!
3. Not handling JSON parse errors - Response might not be JSON
4. CORS issues - Server must allow cross-origin requests
async function loadUserDashboard(userId) {
const dashboardDiv = document.getElementById('dashboard');
// Show loading state
dashboardDiv.innerHTML = '<p>Loading...</p>';
try {
// Fetch user data
const response = await fetch(
`https://api.example.com/users/${userId}`
);
if (!response.ok) {
throw new Error(`User not found: ${response.status}`);
}
const user = await response.json();
// Display user data
dashboardDiv.innerHTML = `
<div class="user-card">
<h2>${user.name}</h2>
<p>Email: ${user.email}</p>
<p>Joined: ${new Date(user.joinedDate)
.toLocaleDateString()}</p>
</div>
`;
} catch (error) {
// Display error message
dashboardDiv.innerHTML = `
<div class="error">
<p>Failed to load user data: ${error.message}</p>
<button onclick="loadUserDashboard(${userId})">
Retry
</button>
</div>
`;
}
}
// Call the function
loadUserDashboard(123);Email: john.doe@example.com
Joined: 12/1/2024
💡 Loading state: "Loading..."
❌ Error state (if API fails):
"Failed to load user data: User not found: 404"
✅ Loading states
✅ Success rendering
✅ Error handling
Returns promises, works with async/await
Always verify HTTP status codes
.json(), .text(), .blob() for different formats
Cancel requests with AbortController