What is the purpose of fetch() in JavaScript?

Asked 24 days ago Updated 18 days ago 101 views

1 Answer


1

The fetch() function in JavaScript is used to make HTTP requests to servers and retrieve or send data asynchronously. It is a modern replacement for XMLHttpRequest and is based on Promises, making asynchronous code cleaner and easier to work with.

Basic Syntax

fetch(url, options)
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

Purpose of fetch()

  • Retrieve data from an API (GET requests).
  • Send data to a server (POST, PUT, PATCH, DELETE, etc.).
  • Upload files or form data.
  • Communicate with RESTful APIs.
  • Handle asynchronous network operations using Promises or async/await.

Example 1: GET Request

// Send a GET request to the API
fetch("https://jsonplaceholder.typicode.com/users")
  // Convert the response to JSON
  .then(response => response.json())
  // Display the received data
  .then(data => console.log(data))
  // Handle any errors
  .catch(error => console.error(error));

Example 2: POST Request

// Send a POST request with JSON data
fetch("https://jsonplaceholder.typicode.com/posts", {
  // Specify the HTTP method
  method: "POST",

  // Set the request headers
  headers: {
    "Content-Type": "application/json"
  },

  // Convert the JavaScript object to a JSON string
  body: JSON.stringify({
    title: "Hello",
    body: "This is a post.",
    userId: 1
  })
})
  // Convert the response to JSON
  .then(response => response.json())
  // Display the server response
  .then(data => console.log(data))
  // Handle errors
  .catch(error => console.error(error));

Using async/await

// Define an asynchronous function
async function getUsers() {
  try {
    // Wait for the HTTP response
    const response = await fetch("https://jsonplaceholder.typicode.com/users");

    // Convert the response body to JSON
    const users = await response.json();

    // Display the users
    console.log(users);
  } catch (error) {
    // Handle errors
    console.error(error);
  }
}

// Call the function
getUsers();

Key Features

  • Promise-based API for asynchronous programming.
  • Supports all common HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.).
  • Allows custom headers, request bodies, and other options.
  • Works with JSON, text, blobs, streams, and form data.
  • Integrates naturally with async/await.

Summary

fetch() is the standard JavaScript API for performing network requests. It enables web applications to communicate with servers, consume APIs, send data, upload files, and retrieve resources asynchronously while providing a simpler and more modern interface than XMLHttpRequest.

Write Your Answer