The Web Fetch API is a modern, powerful, and more flexible interface for making network requests (fetching resources across the network). It is the successor to the old XMLHttpRequest and is built on Promises, making it much easier to handle asynchronous data.
Use the buttons below to trigger real network requests. One fetches a local text file, and the other fetches live JSON data from an external API:
The fetch() method takes one mandatory argument: the path to the resource you want to fetch. It returns a Promise that resolves into a Response object.
fetch("example.txt")
.then(response => response.text())
.then(data => {
console.log(data); // "Hello World"
})
.catch(error => {
console.error("Error: ", error);
});
When working with modern web applications, you will mostly fetch JSON data. The Fetch API provides a .json() method to automatically parse the response.
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(x => x.json())
.then(y => {
console.log(y.title); // Title of the post
});
.catch() to handle network failures like lost internet connection or server downtime.
| Feature | Fetch API | XMLHttpRequest (XHR) |
|---|---|---|
| Syntax | Promise-based (Modern) | Callback-based (Old) |
| Simplicity | Very Simple | Complex/Verbose |
| Status Handling | Does not reject on 404/500 | Handles status manually |
fetch() promise will not reject on HTTP error status (like 404 or 500). It only rejects on network failure. You should check response.ok to ensure the request was successful.