Fetch API is a modern interface for making HTTP requests in JavaScript. It provides a more powerful and flexible feature set than XMLHttpRequest. This cheatsheet covers common use cases and features of the Fetch API.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
key: 'value'
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
fetch('https://api.example.com/data', {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
})
.then(response => response.json())
.then(data => console.log(data));
fetch('https://api.example.com/data')
.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('Error:', error));
fetch('https://api.example.com/data')
.then(response => {
console.log(response.status); // e.g. 200
console.log(response.statusText); // e.g. "OK"
console.log(response.headers.get('Content-Type'));
return response.text();
// Other methods: .json(), .blob(), .formData(), .arrayBuffer()
})
.then(data => console.log(data));
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
key: 'value'
})
})
.then(response => response.json())
.then(data => console.log(data));
const formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
fetch('https://api.example.com/data', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data));
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('HTTP error ' + response.status);
}
return response.json();
})
.then(data => {
// Process your data here
})
.catch(error => {
console.log('There was a problem with the fetch operation: ' + error.message);
});
const controller = new AbortController();
const signal = controller.signal;
fetch('https://api.example.com/data', {
signal: signal
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => {
if (err.name === 'AbortError') {
console.log('Fetch aborted');
} else {
console.error('Uh oh, an error!', err);
}
});
// Abort the request in 5 seconds
setTimeout(() => controller.abort(), 5000);
fetch('https://api.example.com/data', {
credentials: 'include'
})
.then(response => response.json())
.then(data => console.log(data));
fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer YOUR_TOKEN_HERE',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data));
fetch('https://api.example.com/stream')
.then(response => {
const reader = response.body.getReader();
return new ReadableStream({
start(controller) {
return pump();
function pump() {
return reader.read().then(({ done, value }) => {
if (done) {
controller.close();
return;
}
controller.enqueue(value);
return pump();
});
}
}
})
})
.then(stream => new Response(stream))
.then(response => response.blob())
.then(blob => URL.createObjectURL(blob))
.then(url => console.log(url))
.catch(err => console.error(err));
2024 © All rights reserved - buraxta.com