fetch('https://example.com/api/products')
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error('Error:', error));
// Create a new product
fetch('https://example.com/api/products', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newProductData),
})
.then((response) => response.json())
.then((data) => console.log('Created:', data))
.catch((error) => console.error('Error:', error));
// Read (Retrieve) products
fetch('https://example.com/api/products')
.then((response) => response.json())
.then((data) => console.log('Products:', data))
.catch((error) => console.error('Error:', error));
// Update a product
fetch(`https://example.com/api/products/${productId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updatedProductData),
})
.then((response) => response.json())
.then((data) => console.log('Updated:', data))
.catch((error) => console.error('Error:', error));
// Delete a product
fetch(`https://example.com/api/products/${productId}`, {
method: 'DELETE',
})
.then((response) => {
if (response.status === 204) {
console.log('Deleted successfully.');
} else {
console.error('Deletion failed.');
}
})
.catch((error) => console.error('Error:', error));