Topic 29 of 37
The Modern fetch() API
Overview
The fetch API provides a modern, Promise-based interface for fetching resources across the network. It replaced the old XMLHttpRequest (XHR) callback-based system.
Syntax
Always check 'response.ok' before attempting to parse the JSON.
Fetching and Error Handling
javascript
async function submitData(data) {
try {
const response = await fetch('/api/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
// fetch only rejects on network failure, NOT on 404/500 errors!
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Network or parsing error:", error);
}
}Common Pitfalls
- Forgetting to call .json() on the response object and wondering why your data isn't showing up.
Interview Tips
- A very common trick question: 'Does fetch reject on a 404 error?'. Answer: No, it only rejects on a network failure (e.g. offline).
Real-World Example
Aborting a fetch request if it takes too long using AbortController.
example
javascript
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
fetch('/api/slow', { signal: controller.signal })
.then(res => res.json())
.catch(err => {
if (err.name === 'AbortError') console.log("Request timed out");
});