Fetch API
Overview
The fetch() API is the modern, native browser method for making network requests (HTTP requests) to a server.
It completely replaces the older, clunky XMLHttpRequest (AJAX). fetch natively returns a Promise, making it extremely easy to use with async/await.
One crucial quirk: fetch only throws a network Error if the user loses internet connection. It does NOT throw an error for bad HTTP statuses (like 404 or 500). You must check response.ok manually.
Syntax
async function loadTodos() {
const res = await fetch('https://jsonplaceholder.typicode.com/todos/1');
// You MUST check if the HTTP status was successful (200-299)
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}
const data = await res.json();
console.log(data);
}async function createTodo() {
const res = await fetch('https://api.example.com/todos', {
method: 'POST', // Override the default GET
headers: {
'Content-Type': 'application/json' // Tell server we are sending JSON
},
body: JSON.stringify({ title: "Buy Milk", completed: false })
});
return await res.json();
}Common Pitfalls
- Forgetting to call
.json(). The initialfetchresponse is a raw HTTP Response object (containing headers and metadata), NOT your JSON data. You must callawait res.json()to parse the data stream into a JS object.
Interview Questions
404 Not Found status, does the Promise reject and trigger the catch block?No! fetch only rejects a promise if there is a fundamental network failure (like the wifi turning off). For all HTTP error statuses (404, 500, 401), the promise resolves normally. You must manually check if response.ok is true.
Real-World Example
Submitting a user login form to the backend authentication server.
const response = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ email, password })
});Check Your Knowledge
Test your understanding of Fetch API with these quick questions.