What is the Fetch API?
The Fetch API provides a modern way to make HTTP requests in JavaScript. It's built on Promises and replaces older methods like XMLHttpRequest.
💡 Key insight
fetch() returns a Promise that resolves to a Response object. You need to call .json() or .text() to get the actual data.
Basic GET Request
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
With Async/Await
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) throw new Error('Network response was not ok');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}
POST Request
const response = await fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'Alice', age: 25 })
});
Handling Different Response Types
response.json()— parse as JSONresponse.text()— parse as textresponse.blob()— parse as Blob (for images)response.formData()— parse as FormData
Common Mistakes
- Forgetting to check
response.okbefore parsing - Not handling errors with
.catch()ortry/catch - Using
fetch()withoutawaitor.then() - Forgetting to set
Content-Typeheader for POST requests
Quick Quiz
1. What does fetch() return?
2. How do you check if a fetch request was successful?
3. Which method parses the response as JSON?
4. What header must you set for a POST request with JSON data?
Summary
fetch()makes HTTP requests and returns a Promise- Always check
response.okfor success - Use
response.json()to parse JSON responses - Configure requests with method, headers, and body
- Always handle errors with
.catch()ortry/catch - Async/await makes fetch code more readable
