The Fetch API is a modern JavaScript interface for retrieving resources over the network, such as making HTTP requests to an API or loading data from a server. It largely replaces the older XMLHttpRequest
method and provides a simpler, more flexible, and more powerful way to handle network requests.
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json()) // Convert response to JSON
.then(data => console.log(data)) // Log the data
.catch(error => console.error('Error:', error)); // Handle errors
Making a POST Request
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ title: 'New Post', body: 'Post content', userId: 1 })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
✅ Simpler syntax compared to XMLHttpRequest
✅ Supports async/await
for better readability
✅ Flexible request and response handling
✅ Better error management using Promises
The Fetch API is now supported in all modern browsers and is an essential technique for web development.