Open In App

What is the use of the Fetch API in JavaScript ?

The Fetch API in JavaScript provides a modern, powerful, and flexible way to make HTTP requests from web browsers or Node.js environments. Its primary purpose is to facilitate fetching resources, typically data, from servers or other sources across the web. In simple terms, the Fetch API in JavaScript is like a messenger that helps your web browser or server talk to other web servers. Its main job is to fetch or get data from those other places on the internet.

Here’s what it does:

Example: Here, We use the fetch() function to send a request to the specified URL ('https://jsonplaceholder.typicode.com/posts/1'). This URL points to a JSON placeholder API that returns mock data. The fetch() function returns a Promise. When the Promise is resolved, it provides an Response object representing the response from the server.

// Fetching data from a URL
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json()) // Convert the response to JSON format
.then(data => {
console.log('Fetched data:', data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Article Tags :