JS का Fetch API
fetch(url)
.then(response => response.json())
.then(data => {
// use data
})
.catch(error => {});
Fetch क्या है?
Fetch API HTTP requests बनाता है और एक Promise return करता है। वह Promise response headers आते ही resolve हो जाता है, पूरी body के download होने पर नहीं — body को पढ़ने के लिए response.json() जैसा एक अलग step चाहिए।
उदाहरण: What Is Fetch?
fetch("data.php")
.then(response => console.log(response)); // Promise resolves once headers arrive
Responses संभालना
response का data इस्तेमाल करने से पहले उसे जांचें। एक fetch() Promise सिर्फ network failure पर reject होता है; एक 404 या 500 response अभी भी एक successful fetch है, इसलिए data पर भरोसा करने से पहले response.ok या response.status जांचें।
उदाहरण: 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 एक POST request के साथ JSON data भेज सकता है। method: POST, एक JSON.stringify() किया गया body, और application/json पर सेट किया गया Content-Type header वाला एक options object पास करके POST भेजें।
उदाहरण: 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 fail हो सकती हैं। async functions के साथ try...catch इस्तेमाल करें। चूंकि fetch() HTTP error statuses पर reject नहीं होता, पूरी call को सिर्फ try/catch में लपेटना काफी नहीं है — आपको try block के अंदर response.ok की भी एक explicit जांच चाहिए।
उदाहरण: 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 इस्तेमाल
Fetch API data load करने और server को data भेजने के लिए उपयोगी है। एक typical pattern किसी API से data load करने और उसके आने पर page update करने के लिए fetch(), response.json(), और error handling को मिलाता है।
उदाहरण: 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();
- यह मान लेना कि
fetchकिसी 404 या 500 पर reject होता है, जबकि यह सिर्फ network failure पर reject होता है;response.okcheck करें। response.json()कॉल करना और उसेawaitकरना भूल जाना, इसलिए आपको एक Promise मिलता है, data नहीं।- बिना
JSON.stringifyऔरContent-Type: application/jsonheader के एक JSON body भेजना।
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