JS Fetch API
fetch(url)
.then(response => response.json())
.then(data => {
// use data
})
.catch(error => {});
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().
उदाहरण: 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.
उदाहरण: Handling Responses
// Define the method `fetch` taking `"data.php"`
// Define the method `fetch` taking `"data.php"`
fetch("data.php")
// On success, run this with the resolved value as `response`
// On success, run this with the resolved value as `response`
.then(response => {
// Check whether `!response.ok`
// Check whether `!response.ok`
if (!response.ok) {
// Print `"Request failed:", response.status` to the console
// Print `"Request failed:", response.status` to the console
console.log("Request failed:", response.status);
// Return early, with no value
// Return early, with no value
return;
}
// Return `response.json()` from this function
// Return `response.json()` from this function
return response.json();
})
// On success, run this with the resolved value as `data`
// On success, run this with the resolved value as `data`
.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.
उदाहरण: POST Request
// Send a POST request with a JSON body to save.php
fetch("save.php", {
method: "POST",
headers: { "Content-Type": "application/json" }, // tell the server we're sending JSON
body: JSON.stringify({ name: "Sam" }), // convert the JS object into a JSON string
}).then(response => console.log(response.status)); // log only the HTTP status code
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.
उदाहरण: Error Handling
// Define the asynchronous function `loadData` with no parameters
// Define the asynchronous function `loadData` with no parameters
async function loadData() {
// Try running this block; jump to `catch` if it throws
// Try running this block; jump to `catch` if it throws
try {
// Declare the constant `response`, set to `await fetch("data.php")`
// Declare the constant `response`, set to `await fetch("data.php")`
const response = await fetch("data.php");
if (!response.ok) throw new Error("Request failed: " + response.status);
// Declare the constant `data`, set to `await response.json()`
// Declare the constant `data`, set to `await response.json()`
const data = await response.json();
// Print `data` to the console
// Print `data` to the console
console.log(data);
// Catch any error, bound to `error`
// Catch any error, bound to `error`
} catch (error) {
// Print `"Error:", error.message` to the console
// Print `"Error:", error.message` to the console
console.log("Error:", error.message);
}
}
// Call `loadData()`
// Call `loadData()`
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.
उदाहरण: Practical API Use
// Define the asynchronous function `loadUser` with no parameters
// Define the asynchronous function `loadUser` with no parameters
async function loadUser() {
// Declare the constant `response`, set to `await fetch("user.php")`
// Declare the constant `response`, set to `await fetch("user.php")`
const response = await fetch("user.php");
// Declare the constant `data`, set to `await response.json()`
// Declare the constant `data`, set to `await response.json()`
const data = await response.json();
// Assign `<p>${data.message}</p>` to `document.body.innerHTML`
// Assign `<p>${data.message}</p>` to `document.body.innerHTML`
document.body.innerHTML = `<p>${data.message}</p>`;
}
// Call `loadUser()`
// Call `loadUser()`
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