HTML Fetch API
Modern way to make HTTP requests in JavaScript
🌐 What is the Fetch API?
The Fetch API provides a modern, promise-based way to make HTTP requests. It's the successor to XMLHttpRequest and much easier to use.
// Simple GET request
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
Try it:
Fetch API Features
Promise-based
Clean, modern async/await syntax
const response = await fetch(url);
const data = await response.json();
Flexible Options
Customize headers, methods, and body
fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
});
Response Handling
Easy response parsing and status checking
if (response.ok) {
const data = await response.json();
}
Error Handling
Built-in error handling with try/catch
try {
const response = await fetch(url);
} catch (error) {
console.error(error);
}
🔹 Basic Fetch Requests
Here are the most common types of HTTP requests using Fetch:
// GET request
async function getData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
return data;
} catch (error) {
console.error('Fetch error:', error);
}
}
// POST request
async function postData(newPost) {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newPost)
});
const data = await response.json();
return data;
} catch (error) {
console.error('Post error:', error);
}
}
Try Different Request Types:
🔹 Handling Different Response Types
Fetch can handle various response formats:
// JSON response
const jsonData = await response.json();
// Text response
const textData = await response.text();
// Blob response (for files/images)
const blobData = await response.blob();
// Form data response
const formData = await response.formData();
// Array buffer (for binary data)
const arrayBuffer = await response.arrayBuffer();
// Example: Fetch and display an image
async function fetchImage() {
try {
const response = await fetch('https://picsum.photos/200/300');
const blob = await response.blob();
const imageUrl = URL.createObjectURL(blob);
const img = document.createElement('img');
img.src = imageUrl;
document.body.appendChild(img);
} catch (error) {
console.error('Image fetch error:', error);
}
}
Try it:
🔹 Advanced Fetch Options
Customize your requests with various options:
// Advanced fetch configuration
const response = await fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token-here',
'X-Custom-Header': 'custom-value'
},
body: JSON.stringify({
name: 'John Doe',
email: '[email protected]'
}),
mode: 'cors', // cors, no-cors, same-origin
credentials: 'include', // include, same-origin, omit
cache: 'no-cache', // default, no-cache, reload, force-cache
redirect: 'follow', // follow, error, manual
referrerPolicy: 'no-referrer'
});
// Check response status
if (response.status === 200) {
console.log('Success!');
} else if (response.status === 404) {
console.log('Not found');
} else {
console.log('Other status:', response.status);
}