HTML Fetch API
π Introduction to the Fetch API
The Fetch API is a modern JavaScript interface for making network requests to retrieve resources like JSON, text, images, or any other data from servers. Itβs a cleaner, more powerful alternative to the older XMLHttpRequest and uses Promises for easier asynchronous code. π
>>βFetching data asynchronously makes the web faster and more interactive.β π
π Basic Fetch Syntax
Use fetch() to make a GET request and handle the response:
Simple Fetch Example
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('Fetch error:', error);
});βοΈ Fetch with Async/Await
Modern JavaScript lets you write cleaner asynchronous code using async and await:
Fetch 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();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}
fetchData();π€ Sending Data with POST Request
You can also send data to servers using POST or other HTTP methods by passing an options object:
POST Request Example
fetch('https://api.example.com/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'John', age: 30 })
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});π§ Useful Fetch Options
| Option | Description |
|---|---|
| method | HTTP method: GET, POST, PUT, DELETE, etc. |
| headers | Request headers as an object |
| body | Request payload (string or FormData) |
| mode | CORS mode: cors, no-cors, same-origin |
| credentials | Include cookies with requests: omit, same-origin, include |
π‘ Handling Different Response Types
Fetch responses can be parsed as:
- response.json() β Parse JSON data
- response.text() β Plain text
- response.blob() β Binary data (images, files)
- response.formData() β Form data
- response.arrayBuffer() β Low-level binary data
π§ Tips & Best Practices
- Always check response.ok to handle HTTP errors gracefully.
- Use try/catch or .catch() to handle network errors.
- Consider CORS restrictions when making cross-origin requests.
- Use HTTPS endpoints for secure data transfer.
π Learn More
>>βFetch API simplifies networking β build fast, reactive web apps!β β‘