How to Fetch API in javaScript

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryJavaScript

In this tutorial we will learn how to fetch API in javaScript.

 

How to fetch API in javaScript

Fetching API in JavaScript can be done using the fetch() method. Here's an example:

 

fetch('https://example.com/data')
  .then(response => response.json())
  .then(data => {
    // Do something with the data
  })
  .catch(error => console.error(error))

In the above code, we are using the fetch() method to make a GET request to https://example.com/data. We are then using the .json() method on the response object to convert the data to a JavaScript object. Finally, we are using a promise chain to handle the data and any errors that might occur during the fetch.

 

You can also specify additional options when making a fetch request, such as the request method, headers, and body. Here's an example:

fetch('https://example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'John',
    age: 30
  })
})
.then(response => response.json())
.then(data => {
  // Do something with the data
})
.catch(error => console.error(error))

 

In this example, we are making a POST request with a JSON payload containing a name and age property. We are also specifying a content-type header to indicate that the payload is in JSON format.

Comments 0

Leave a comment