Introduction to Fetch API in JavaScript: Making Asynchronous Network Requests


The Fetch API is a JavaScript interface that provides a modern and powerful way to make asynchronous network requests in web browsers. It allows you to fetch resources from a server, such as JSON data, HTML pages, or binary files, and handle the response in a flexible manner.

Here are some key features and concepts related to the Fetch API:

  • Making Requests: The Fetch API uses the fetch() function to initiate HTTP requests. You pass in the URL of the resource you want to fetch, along with optional parameters to configure the request, such as request headers, request method (GET, POST, etc.), and request body.
  • Promises: Fetch API uses Promises to handle asynchronous operations. The fetch() function returns a Promise that resolves to the response of the request. You can chain .then() and .catch() methods to handle the response and any errors that occur during the request.
  • Response Handling: Once you have the response, you can use methods like .json(), .text(), or .blob() to extract the content from the response in different formats. For example, .json() parses the response as JSON and returns a Promise that resolves to the parsed data.
  • Error Handling: The Fetch API considers network errors, status codes outside the range of 200-299, and other issues as rejected Promises. You can catch and handle these errors in the .catch() block of the Promise chain.
  • Cross-Origin Requests: Fetch API supports making cross-origin requests, meaning you can fetch resources from a different domain or origin. However, you might encounter CORS (Cross-Origin Resource Sharing) restrictions depending on the server's configuration.
  • Fetch Headers: You can set custom headers in the request to provide additional information to the server or to handle authentication. Headers like Content-Type, Authorization, or custom headers can be added to the request using the Headers object.

The Fetch API is widely supported in modern browsers and is considered a more modern alternative to older techniques like XMLHttpRequest. It offers a cleaner and more intuitive syntax for handling asynchronous requests and responses.

It's important to note that the Fetch API uses the underlying network capabilities of the browser, so it supports the same security considerations as other web-based HTTP requests. Additionally, since the Fetch API relies on Promises, it can be used effectively with modern JavaScript features like async/await for more concise and readable code.

Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="icon" type="image/ico" href="logo.png" />
    <title>Document</title>
    <style>
      @import url("https://fonts.googleapis.com/css2?family=Lobster&family=Poppins:wght@100;200;300;400;500;600;700;800&display=swap");
      * {
        font-family: "Poppins", sans-serif;
      }

      .post {
        background-color: palegreen;
        margin-bottom: 20px;
        padding: 20px;
      }
      .post h4 {
        color: blue;
      }
    </style>
  </head>
  <body>
    <h3>Fetch in JavaScript</h3>

    <div id="txt-output">--</div>
    <button id="btn-text">Get Text</button>

    <hr />

    <div id="json-output"></div>
    <button id="btn-json">Get Json</button>

    <hr />

    <button id="btn-api">Get Api</button>
    <div id="api-output"></div>

    <script src="fetch_api.js"></script>
    <hr />
  </body>
</html>

fetch_api.js

This code snippet demonstrates different examples of using the Fetch API in JavaScript to fetch data from various sources, handle the responses, and update the HTML content. Let's break it down section by section:

Text File Fetch:

const btnText = document.querySelector("#btn-text");
const outputText = document.querySelector("#txt-output");

btnText.addEventListener("click", getTextFile);

function getTextFile() {
  fetch("data.txt")
    .then((res) => res.text())
    .then((data) => {
      outputText.innerHTML = data;
    });
}

In this section, there is a button with the ID "btn-text" and an output element with the ID "txt-output". The getTextFile function is registered as the click event listener for the button. When the button is clicked, it triggers the function.

Inside getTextFile, the fetch function is used to fetch the "data.txt" file. The response is received as a Response object, and the .text() method is called on it to extract the text content of the response. This returns a Promise that resolves to the text data.

In the next .then() block, the text data is received as the data parameter. The HTML content of the output element is updated with the received data.

JSON File Fetch:

const btnJson = document.querySelector("#btn-json");
const outputJson = document.querySelector("#json-output");

btnJson.addEventListener("click", getJsonData);

function getJsonData() {
  fetch("users.json")
    .then((res) => res.json())
    .then((users) => {
      let data = "<ul>";
      users.forEach((user) => {
        data += `<li>${user.name} : ${user.age}</li>`;
      });
      data += "</ul>";
      outputJson.innerHTML = data;
    });
}

This section is similar to the previous one but fetches a JSON file ("users.json") instead. The response is parsed as JSON using the .json() method, which returns a Promise that resolves to the parsed JSON data.

In the subsequent .then() block, the JSON data is received as the users parameter. It loops over each user and constructs an HTML string to display the user's name and age in a list (<ul>). The HTML content of the output element is then updated with the generated data.

API Data Fetch:

const btnApi = document.querySelector("#btn-api");
const outputApi = document.querySelector("#api-output");

btnApi.addEventListener("click", getApiData);

async function getApiData() {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts");
  const jsonData = await response.json();
  let output = "";
  jsonData.forEach((post) => {
    output += `<div class='post'>
            <h4>${post.title}</h4>
            <p>${post.body}</p>
      </div>`;
  });

  outputApi.innerHTML = output;
}

In this section, a button with the ID "btn-api" and an output element with the ID "api-output" are defined. The getApiData function is registered as the click event listener for the button.

Inside getApiData, an asynchronous function is declared using the async keyword. It fetches data from the "https://jsonplaceholder.typicode.com/posts" URL, which represents a JSON API endpoint. The response is obtained using await and then parsed as JSON using .json().

Once the JSON data is received as jsonData, a loop iterates over each post and constructs an HTML string representing a post's title and body. The generated HTML is appended to the output variable.

Finally, the HTML content of the output element is updated with the output string, displaying the posts in a styled format.

Console Output:

console.log("Start");

function hello() {
  console.log("Hello World");
}

console.log("end");

console.log("Start");
document.getElementById("btn").addEventListener("click", function callback() {
  console.log("Hello World");
});
console.log("end");

In this part, console log statements are used to output messages in the browser's console.

The statements console.log("Start"); and console.log("end"); will log the corresponding messages in the console.

The hello function is defined but not invoked, so it won't log anything unless explicitly called.

The final block sets up an event listener for a button with the ID "btn". When the button is clicked, the anonymous callback function logs "Hello World" in the console.

Overall, this code demonstrates fetching data from text files, JSON files, and a remote API using the Fetch API. The fetched data is then used to update the content of specific HTML elements. Additionally, there are console log statements to demonstrate logging messages at different stages of the code execution.

data.txt

This is sample text from data.txt

users.json

The provided data is an array of four objects, each representing information about a person. Let's break down the structure and the properties of each object:

[
  {
    "name": "Tiya",
    "age": 25,
    "gender": "Male",
    "contact": 7859586895,
    "isMarried": false,
    "city": "Salem"
  },
  {
    "name": "Ram",
    "age": 32,
    "gender": "Male",
    "contact": 859658585,
    "isMarried": true,
    "city": "Chennai"
  },
  {
    "name": "Sara",
    "age": 18,
    "gender": "Female",
    "contact": 8596857585,
    "isMarried": false,
    "city": "Salem"
  },
  {
    "name": "Sam",
    "age": 24,
    "gender": "Male",
    "contact": 856968575,
    "isMarried": true,
    "city": "Chennai"
  }
]

Each object represents a person's information and contains properties such as name, age, gender, contact number, marital status, and city.

For example, in the first object, "Tiya" is a 25-year-old male from Salem. The isMarried property is set to false, indicating that Tiya is not married. The contact number is 7859586895.

Similarly, the other objects represent individuals with their respective information.

This data can be useful for various purposes, such as displaying a list of people, filtering based on certain criteria, or performing data analysis.

List of Programs


JS Practical Questions & Answers


JS Practical Project