What is the use of the fetch() method in JavaScript?

The fetch() method is a JavaScript API that allows you to make network requests, such as HTTP requests, to retrieve resources or data from a server. It returns a Promise object that resolves to the response of the network request.

For example:

fetch("https://jsonplaceholder.typicode.com/users")
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

In this example, we’re using fetch() to make a GET request to the JSONPlaceholder API to retrieve a list of users. The response from the API is returned as a Response object, which we then call the json() method on to parse the response body as JSON. The resulting JSON data is then logged to the console.

If the network request encounters an error, such as a network failure or an invalid response, the catch() method is called with the error as an argument.

You can also use the fetch() method to make requests with different HTTP methods, such as POST, PUT, and DELETE, by passing in an options object as a second argument to fetch().

Here is an example of making a POST request to submit a form:

const form = document.querySelector("form");

form.addEventListener("submit", (event) => {
  event.preventDefault();

  const formData = new FormData(form);

  fetch("https://example.com/api/form-submit", {
    method: "POST",
    body: formData,
  })
    .then((response) => response.json())
    .then((data) => console.log(data))
    .catch((error) => console.error(error));
});

In this example, we’re using fetch() to make a POST request to submit a form to an API. We’re using the FormData API to create a new FormData object from the form element, which we then pass as the body of the request. The method option is set to 'POST' to indicate that this is a POST request.

If the POST request is successful, the API will return a response that we can parse as JSON using the json() method. The resulting JSON data is then logged to the console.

You can also set headers on the request using the headers option.

Here’s an example of setting a custom header:

fetch("https://example.com/api", {
  headers: {
    Authorization: "Bearer " + token,
  },
})
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

In this example, we’re setting the 'Authorization' header with a token value, which is concatenated with the string 'Bearer' using the + operator. This will set the header value to something like 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'.

The fetch() method can also be used to upload files to a server using the FormData API.

Here’s an example of uploading a file:

const input = document.querySelector('input[type="file"]');

input.addEventListener("change", (event) => {
  const file = input.files[0];
  const formData = new FormData();

  formData.append("file", file);

  fetch("https://example.com/api/upload", {
    method: "POST",
    body: formData,
  })
    .then((response) => response.json())
    .then((data) => console.log(data))
    .catch((error) => console.error(error));
});

In this example, we’re using the input element to allow the user to select a file. When the user selects a file, we create a new FormData object and append the selected file to it with the name 'file'. We then use fetch() to make a POST request to upload the file to the API.

The fetch() method also supports authentication using cookies or tokens. Here’s an example of using cookies for authentication:

fetch("https://example.com/api/data", {
  credentials: "include",
})
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

In this example, we’re making a request to an API that requires authentication using cookies. We set the credentials option to 'include', which tells the browser to include cookies in the request.

Finally, it’s important to note that the fetch() method returns a Promise, which means that it’s asynchronous. This means that you can use it with other asynchronous features in JavaScript, such as async/await.

Here’s an example of using fetch() with async/await:

async function fetchData() {
  try {
    const response = await fetch("https://example.com/api/data");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

fetchData();

In this example, we’re using the async keyword to define an asynchronous function called fetchData(). Within this function, we use await to wait for the fetch() method to resolve to a response object, and then we use await again to wait for the response object to be parsed as JSON using the json() method. The resulting data is then logged to the console.

Overall, the fetch() method is a powerful tool for making network requests in JavaScript. It provides a flexible and easy-to-use API for retrieving and sending data to servers, and can be used with other JavaScript features to build complex and robust applications.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: