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.
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();
}.json(). The initial fetch response is a raw HTTP Response object (containing headers and metadata), NOT your JSON data. You must call await res.json() to parse the data stream into a JS object.If a fetch request returns a 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.
Submitting a user login form to the backend authentication server.
const response = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ email, password })
});Test your understanding of Fetch API with these quick questions.
Question 1
Which object does the `fetch()` method return?
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.
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();
}.json(). The initial fetch response is a raw HTTP Response object (containing headers and metadata), NOT your JSON data. You must call await res.json() to parse the data stream into a JS object.If a fetch request returns a 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.
Submitting a user login form to the backend authentication server.
const response = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ email, password })
});Test your understanding of Fetch API with these quick questions.
Question 1
Which object does the `fetch()` method return?