JS Fetch API
What Is Fetch?
The Fetch API makes HTTP requests and returns a Promise. That Promise resolves once the response headers arrive, not once the full body has downloaded — reading the body itself requires a separate step like response.json().
Example: What Is Fetch?
fetch("data.php")
.then(response => console.log(response)); // Promise resolves once headers arrive
Handling Responses
Check the response before using its data. A fetch() Promise only rejects on network failure; a 404 or 500 response is still a successful fetch, so check response.ok or response.status before trusting the data.
Example: Handling Responses
fetch("data.php")
.then(response => {
if (!response.ok) {
console.log("Request failed:", response.status);
return;
}
return response.json();
})
.then(data => console.log(data));
POST Request
Fetch can send JSON data with a POST request. Send a POST by passing an options object with method: POST, a JSON.stringify()'d body, and a Content-Type header set to application/json.
Example: POST Request
fetch("save.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Sam" }),
}).then(response => console.log(response.status));
Error Handling
Network requests can fail. Use try...catch with async functions. Because fetch() doesn't reject on HTTP error statuses, wrapping the whole call in try/catch alone isn't enough — you also need an explicit check for response.ok inside the try block.
Example: Error Handling
async function loadData() {
try {
const response = await fetch("data.php");
if (!response.ok) throw new Error("Request failed: " + response.status);
const data = await response.json();
console.log(data);
} catch (error) {
console.log("Error:", error.message);
}
}
loadData();
Practical API Use
Fetch is useful for loading API data and sending data to a server. A typical pattern combines fetch(), response.json(), and error handling to load data from an API and update the page once it arrives.
Example: Practical API Use
async function loadUser() {
const response = await fetch("user.php");
const data = await response.json();
document.body.innerHTML = `<p>${data.message}</p>`;
}
loadUser();
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML