Demonstrates how to perform a simple GET request to fetch data from a specified URL.
fetch('/api/data/users')
.then(response => response.json())
.then(data => console.log('Users:', data))
.catch(error => console.error('Error fetching users:', error));
This example shows the most common use case for retrieving information.
Illustrates sending data to the server using a POST request, often for creating new resources.
const newUser = { name: 'Alice', email: 'alice@example.com' };
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newUser)
})
.then(response => response.json())
.then(data => console.log('User created:', data))
.catch(error => console.error('Error creating user:', error));
Learn how to structure your requests for data submission.
Shows best practices for detecting and handling common API errors, like 404 or 500 status codes.
fetch('/api/nonexistent-resource')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log('Data:', data))
.catch(error => console.error('An error occurred:', error));
Essential for robust application development.
Demonstrates how to include authentication tokens (e.g., Bearer tokens) in your API requests.
const token = localStorage.getItem('authToken');
fetch('/api/protected/profile', {
headers: { 'Authorization': `Bearer ${token}` }
})
.then(response => response.json())
.then(data => console.log('Profile:', data))
.catch(error => console.error('Authentication error:', error));
Secure your API interactions effectively.
Examples for updating existing resources on the server using PUT or PATCH methods.
const updatedData = { status: 'completed' };
fetch('/api/tasks/123', {
method: 'PUT', // or 'PATCH'
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updatedData)
})
.then(response => response.json())
.then(data => console.log('Task updated:', data))
.catch(error => console.error('Error updating task:', error));
Learn to modify server-side data.
Shows how to remove resources from the server using a DELETE request.
fetch('/api/items/456', {
method: 'DELETE'
})
.then(response => {
if (response.ok) {
console.log('Item deleted successfully.');
} else {
throw new Error('Failed to delete item.');
}
})
.catch(error => console.error('Error deleting item:', error));
Manage your resources efficiently.