JavaScript Fetch API: A Practical Guide
The Fetch API provides a modern promise-based way to make HTTP requests from browser JavaScript.
GET Request
const response = await fetch('/api/products');
const products = await response.json();
Always Check the HTTP Status
A fetch promise normally rejects for network failures, not simply because the server returned a 404 or 500. Check response.ok when appropriate.
const response = await fetch('/api/products');
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
POST JSON
const response = await fetch('/api/products', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Keyboard', price: 1200 })
});
Error Handling
try {
const response = await fetch('/api/products');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Request failed:', error);
}
Practical Tips
- Check HTTP status codes.
- Validate JSON before using it when the response is not fully trusted.
- Use
AbortControllerfor requests that need cancellation. - Do not put secrets such as API keys in browser JavaScript.
Continue Learning
đ¤ AlgoLassi Assistant
Have a question about this tutorial?
Ask a question
Ask AlgoLassi and get an answer plus the tutorials worth studying next.
đŦ Comments
Sign in with Google to publish immediately, or comment anonymously and wait for approval.
Comments will appear here when available.