JavaScript Fetch API
Modern HTTP requests: GET, POST, headers, response handling, and error management.
Basic GET Request
// Simple GET
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
POST Request
// POST with JSON
fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "John",
email: "[email protected]"
})
})
.then(res => res.json())
.then(data => console.log(data));
Custom Headers
// With authentication
fetch(url, {
headers: {
"Authorization": "Bearer token123",
"Content-Type": "application/json"
}
});
Response Handling
// Check response status
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error("HTTP error");
}
return response.json();
})
.then(data => processData(data));
Async/Await
// Modern syntax
async function fetchData() {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
Request Methods
// PUT request
fetch(url, { method: "PUT", body: data });
// DELETE request
fetch(url, { method: "DELETE" });
// PATCH request
fetch(url, { method: "PATCH", body: data });
Response Types
// Different formats
response.json() // JSON data
response.text() // Plain text
response.blob() // Binary data
response.arrayBuffer() // Array buffer
Abort Request
// Cancel request
const controller = new AbortController();
fetch(url, {
signal: controller.signal
});
// Cancel after 5 seconds
setTimeout(() => controller.abort(), 5000);