The Fetch API is a modern JavaScript interface used to make HTTP requests. It allows developers to retrieve resources (e.g., data from a server or a file) across the network. Fetch API is promise-based, making it a simpler and more flexible alternative to older methods like XMLHttpRequest
.
Advantages of Fetch API
1. Simplifies asynchronous requests.
2. Built-in support for modern JavaScript features.
3. Cleaner and more readable than XMLHttpRequest
.
How to Use Fetch API
1. Basic Syntax:
fetch(url, options)
.then(response => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
2. Making a GET Request:
The default method of fetch()
is GET
.
fetch("https://api.example.com/users")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
3. Making a POST Request:
Include a method
and body
in the options object.
fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ name: "John", age: 35 }),
})
.then(response => response.json())
.then(data => console.log("Success:", data))
.catch(error => console.error("Error:", error));
4. Handling Errors:
Fetch doesn’t reject the promise for HTTP errors like 404
or 500
. You must manually check the response.ok
property.
fetch("https://api.example.com/invalid-endpoint")
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.catch(error => console.error("Error:", error));