
The Fetch API is a modern JavaScript interface that allows you to make network requests to retrieve resources from a server. It is a powerful tool that provides an easy-to-use interface for making HTTP requests, and it is a crucial part of any modern web application.
To use the Fetch API, you need to include the following code in your JavaScript file:
fetch('http://example.com/api/endpoint')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
This code makes a GET request to the specified URL and retrieves the response in the form of a promise. The .then() method is used to handle the response and transform it into JSON format, and the .catch() method is used to handle any errors that may occur.
You can also use the Fetch API to make other types of HTTP requests, such as POST, PUT, and DELETE. Here is an example of a POST request using the Fetch API:
fetch('http://example.com/api/endpoint', {
method: 'POST',
body: JSON.stringify({
name: 'John',
age: 30
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
In this example, we are sending a POST request to the specified URL with a JSON payload in the body of the request. We also specify the content type of the request as application/json in the headers.
One of the advantages of using the Fetch API is that it is easy to use and works well with modern JavaScript frameworks such as React and Angular. It also has good browser support, so you can use it in most modern web browsers.
I hope this gives you a good overview of how to use the Fetch API in JavaScript. If you have any questions, feel free to ask!
For detail explanation : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch