4 min read
•Question 42 of 50mediumHow does the Fetch API work?
Understanding modern HTTP requests in JavaScript.
What You'll Learn
- Basic fetch usage
- Request options
- Error handling
Basic GET Request
code.jsJavaScript
// Simple fetch
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// With async/await
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}POST Request
code.jsJavaScript
async function postData(url, data) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
return response.json();
}
postData('/api/users', { name: 'John' });Request Options
code.jsJavaScript
fetch(url, {
method: 'POST', // GET, POST, PUT, DELETE
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token'
},
body: JSON.stringify(data),
mode: 'cors', // cors, no-cors, same-origin
credentials: 'include' // include, same-origin, omit
});Error Handling
code.jsJavaScript
async function fetchWithError(url) {
const response = await fetch(url);
// Fetch doesn't throw on HTTP errors
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
}AbortController
code.jsJavaScript
const controller = new AbortController();
fetch(url, { signal: controller.signal })
.catch(err => {
if (err.name === 'AbortError') {
console.log('Request cancelled');
}
});
// Cancel request
controller.abort();