The Fetch API is designed to replace older techniques like XMLHttpRequest with a cleaner, promise-based syntax. Key Benefits:
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error("Error:", error);
});
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(posts => {
console.log(posts);
})
.catch(error => console.error(error));
This is the recommended modern approach.
async function getPosts() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
getPosts();
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "Learn Fetch API",
body: "Fetch API tutorial for beginners",
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data));
fetch("https://api.example.com/data")
.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));
This makes Fetch API a core skill for frontend and full-stack developers.