Clean β’ Professional
The Fetch API is a modern, built-in web API in JavaScript that allows you to make HTTP requests to servers easily. It is promise-based, meaning it works asynchronously without freezing your web page, making it perfect for loading data dynamically from APIs, sending data to a server, or handling files like images and documents.
A GET request is used to retrieve data from a server. With the Fetch API, itβs simple:
fetch("<https://api.example.com/users>")
.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("Fetch error:", error));
fetch(url) makes a request to the server.response.ok checks if the request succeeded.response.json() converts the response into a usable JSON object..catch() handles errors gracefully.A POST request sends data to the server, like creating a new user:
fetch("<https://api.example.com/users>", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ name: "John", age: 25 })
})
.then(response => response.json())
.then(data => console.log("User created:", data))
.catch(error => console.error("Error:", error));
method: "POST" tells the server you are sending data.headers define the data type (usually JSON).body contains the data, converted to a string with JSON.stringify..then().The Fetch API can handle multiple types of server responses:
response.json() β Parses JSON data.response.text() β Retrieves plain text.response.blob() β Handles files or images.response.formData() β Works with HTML form submissions.Example for Blob:
fetch("example.png")
.then(res => res.blob())
.then(blob => console.log(blob));
Sometimes, you may want to cancel a request, for example, if a user navigates away before the data loads. You can use AbortController:
const controller = new AbortController();
const signal = controller.signal;
fetch("<https://api.example.com/data>", { signal })
.then(res => res.json())
.then(data => console.log(data))
.catch(err => {
if(err.name === "AbortError") console.log("Fetch aborted");
else console.error(err);
});
// Abort after 2 seconds
setTimeout(() => controller.abort(), 2000);
AbortController creates a signal to control the fetch.{ signal } allows you to cancel the request..abort() stops the request if needed, improving performance.XMLHttpRequest.AbortController.