The Fetch API is a modern JavaScript interface for fetching resources (such as JSON, XML, or even images) across the network. It provides a more powerful and flexible way to make HTTP requests compared to the older XMLHttpRequest (XHR).
Making a Simple GET Request
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Making a POST Request with Data
fetch('https://api.example.com/save', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
catch
block.whatwg-fetch
.In conclusion, the Fetch API in JavaScript provides a powerful and versatile way to make network requests. Its simplicity, modern standards compliance, and flexibility make it a preferred choice for developers. From basic usage to advanced customization, understanding Fetch API opens up a wide range of possibilities for interacting with remote servers and APIs in web applications. Happy coding !❤️