Fetch API
What is the Fetch API?
The Fetch API is a modern, Promise-based interface for making HTTP requests in the browser. It was introduced in ES6 (2015) as a cleaner, more powerful replacement for XMLHttpRequest. Fetch uses Request, Response, and Headers objects to represent the parts of an HTTP transaction.
// ---- GET request ----
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log('Status:', response.status); // 200
console.log('OK?', response.ok); // true
console.log('Type:', response.type); // "cors" or "basic"
return response.json(); // returns a Promise
})
.then(post => console.log(post.title))
.catch(err => console.error('Fetch failed:', err));
// ---- POST request ----
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'Hello World',
body: 'This is the post body',
userId: 1
})
})
.then(res => res.json())
.then(data => console.log('Created post with id:', data.id));
Response Methods
The Response object returned by fetch() provides several methods to read the body. Each method returns a Promise and can only be called once per response.
response.json()— parses the body as JSON and returns a JavaScript object.response.text()— returns the body as a plain string.response.blob()— returns the body as aBlob(for binary data like images).response.arrayBuffer()— returns the body as anArrayBuffer.response.formData()— returns the body as aFormDataobject.response.ok—trueif status is 200–299.response.status— the HTTP status code.
// response.json()
fetch('/api/users')
.then(res => res.json())
.then(users => console.log(users));
// response.text() — useful for HTML fragments or plain text
fetch('/api/message')
.then(res => res.text())
.then(text => document.getElementById('msg').textContent = text);
// response.blob() — download and display an image
fetch('/images/avatar.png')
.then(res => res.blob())
.then(blob => {
const url = URL.createObjectURL(blob);
document.getElementById('avatar').src = url;
});
// Checking response.ok before processing
fetch('/api/data')
.then(res => {
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
}
return res.json();
})
.then(data => console.log(data))
.catch(err => console.error(err.message));
Headers Object
The Headers class provides a convenient interface for working with HTTP headers in both requests and responses.
// Build headers with the Headers constructor
const myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
myHeaders.append('Authorization', 'Bearer my-token-here');
myHeaders.append('X-Custom-Header', 'my-value');
fetch('/api/secure', {
method: 'POST',
headers: myHeaders,
body: JSON.stringify({ data: 'payload' })
});
// Read response headers
fetch('/api/info').then(res => {
console.log(res.headers.get('Content-Type'));
console.log(res.headers.get('X-Rate-Limit'));
// Iterate all response headers
res.headers.forEach((value, name) => {
console.log(`${name}: ${value}`);
});
});
// AbortController lets you cancel a fetch request
const controller = new AbortController();
const signal = controller.signal;
// Cancel after 5 seconds
const timeoutId = setTimeout(() => controller.abort(), 5000);
fetch('/api/slow-data', { signal })
.then(res => res.json())
.then(data => {
clearTimeout(timeoutId); // clear timeout if request succeeds
console.log('Data:', data);
})
.catch(err => {
if (err.name === 'AbortError') {
console.warn('Request was cancelled (timeout or manual abort)');
} else {
console.error('Fetch error:', err);
}
});
// Cancel manually (e.g., user clicks a cancel button)
document.getElementById('cancel-btn').addEventListener('click', () => {
controller.abort();
console.log('Request cancelled by user');
});
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.