It is an API in JavaScript that let you make network requests and return the response as a Promise object.
Below is the example that shows how to make a GET request to an API endpoint and log the response:
Syntax:
1 2 3 4 |
fetch("https://dummyApi.demo.com/data") .then(res => res.json()) .then(data => console.log(data)) .catch(error => console.error(error)); |
In this example, the fetch
function is called with the mentioned URL . The fetch
function returns a Promise, which is passed to the then
method to wait for the response. The response.json
method is used to parse the response as JSON data. In this example then
method is used to log the data when it becomes available. The catch
method is used to catch any errors that occur during the network request.
Below example make POST requests and send data with the fetch
function. Below is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fetch("https://dummyApi.demo.com/data", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ key: "DummyValue" }) }) .then(res => res.json()) .then(data => console.log(data)) .catch(error => console.error(error)); |
In above example, the fetch
function is called with the URL of the API endpoint and an options object. The options object specifies the method
as "POST"
request. Also it sets the headers
and body
properties to send data in request.