← Back to JavaScript Course | Chapter 9: Async & Web APIs | Lesson 3 of 26

JS का Fetch API

Fetch वह तरीका है जिससे एक web page किसी server से जानकारी मांगता है, जैसे mail से एक request भेजना और जवाब का इंतज़ार करना। यह pages को बिना refresh किए नया data load करने देता है।
Syntax
javascript
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?

javascript
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

javascript
// 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

javascript
// 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

javascript
// 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

javascript
// 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();
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह मान लेना कि fetch किसी 404 या 500 पर reject होता है, जबकि यह सिर्फ network failure पर reject होता है; response.ok check करें।
  2. response.json() कॉल करना और उसे await करना भूल जाना, इसलिए आपको एक Promise मिलता है, data नहीं।
  3. बिना JSON.stringify और Content-Type: application/json header के एक JSON body भेजना।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.