Fetch API
Last Updated: 27th October 2025
- The Fetch API is a standard for making HTTP requests (GET, POST, etc.) and it returns promises.
- It works both in the browser and Node.js.
- syntax:
fetch(url, {
method: "GET", // or POST, PUT, DELETE
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data), // only for POST/PUT
})
.then((response) => response.json())
.then((data) => console.log("✅ Data:", data))
.catch((err) => console.error("❌ Error:", err));
Get Request
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((res) => res.json())
.then((data) => console.log("✅ Data:", data))
.catch((err) => console.error("❌ Error:", err));
Default method is GET.
Post Request
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title: "Learn JS",
body: "Async with Fetch API",
userId: 1,
}),
})
.then((res) => res.json())
.then((data) => console.log("✅ Created:", data))
.catch((err) => console.error("❌ Error:", err));
- Method is POST.
- Headers are set.
Content-Typeis set toapplication/json. It means we are sending JSON data. - Body is set. It is a JSON stringified object.
AbortController — Cancel a Request
Sometimes you want to cancel an API request (for example, slow or no network).AbortController helps you abort a fetch() request.
const controller = new AbortController();
const signal = controller.signal;
fetch("https://jsonplaceholder.typicode.com/posts", { signal })
.then((res) => res.json())
.then((data) => console.log("✅ Data:", data))
.catch((err) => {
if (err.name === "AbortError") console.log("❌ Request canceled");
else console.error("Error:", err);
});
// Cancel after 1 second
setTimeout(() => controller.abort(), 1000);
Hinglish Tip 🗣: Agar user “Back” kare ya page change ho jaye, to request ko cancel karne ke liye AbortController perfect hai.