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

JS Fetch API

Fetch is how a web page asks a server for information, like sending a request through the mail and waiting for the reply. It lets pages load new data without refreshing.
Syntax
javascript
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?

javascript
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

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

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

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

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. #}

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.