Advance JavaScript (DOM, BOM, Web API) / Web API

Network Requests

✍️ Fetch API

  • The Fetch API is a modern way to make HTTP requests from the browser.

  • It is Promise-based, which makes handling async operations cleaner and easier.

  • The fetch() function is available globally and lets you communicate with servers to get or send data.


📩 Sending a Request

  • fetch() needs only the URL:

fetch(url);
  • Since it returns a Promise, you handle it using then() and catch():

fetch(url)
  .then(response => {
    // handle response
  })
  .catch(error => {
    // handle error
  });
  • When the request completes, it returns a Response object.


📖 Reading the Response

  • To read JSON data, use response.json():

fetch(url)
  .then(response => response.json())
  .then(data => console.log(data));
  • Other response methods:

    • text() → plain text

    • blob() → files/images

    • formData() → form data

    • arrayBuffer() → binary data


💻 Handling HTTP Status

  • You can check the status using status or ok:

const response = await fetch(url);

if (response.ok) {
  console.log("Request successful");
} else {
  throw new Error(`Error: ${response.status}`);
}
  • response.ok is true for status codes 200–299.


🔅Fetch API example

We’ll fetch a list of users from this API:

<https://jsonplaceholder.typicode.com/users>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Fetch API Demo</title>
  <script src="js/app.js" defer></script>
</head>
<body>
  <ul id="content"></ul>
  <p id="message"></p>
  <p id="loading"></p>
</body>
</html>

Elements used:

  • #content → shows user list

  • #message → shows errors

  • #loading → shows loading text

1️⃣ Fetch users

const getUsers = async () => {
  const response = await fetch('<https://jsonplaceholder.typicode.com/users>');
  return response.json();
};

2️⃣ Render users

const renderUsers = (users) => {
  return users
    .map(user => `<li>${user.name} (${user.email})</li>`)
    .join('');
};

3️⃣ Load data on page load

(async () => {
  // Get references to DOM elements
  const loading = document.getElementById('loading'); // Shows loading state
  const content = document.getElementById('content'); // Displays user list
  const message = document.getElementById('message'); // Displays error messages

  // Show loading message before starting the API call
  loading.textContent = 'Loading...';

  try {
    // Call the API to fetch users (async operation)
    const users = await getUsers();

    // Render the fetched users inside the content element
    content.innerHTML = renderUsers(users);
  } catch (error) {
    // If any error occurs (network / API / parsing),
    // show a user-friendly error message
    message.textContent = 'Error fetching users';
  } finally {
    // This block always runs (success or error)
    // Clear the loading message once the request is complete
    loading.textContent = '';
  }
})();