HTTP Requests di JavaScript dengan Fetch API
1
min read .
Updated on
Fetch API itu modern, clean, dan promise-based—solusi yang jauh lebih enak dibanding XMLHttpRequest
. Gini deh, contoh CRUD pakai DummyJSON API.
1. Ambil Semua Produk
fetch('https://dummyjson.com/products')
.then(res => res.json())
.then(console.log)
.catch(err => console.error('Error:', err));
2. Ambil Produk Berdasarkan ID
fetch('https://dummyjson.com/products/1')
.then(res => res.json())
.then(console.log)
.catch(err => console.error('Error:', err));
3. Cari Produk
fetch('https://dummyjson.com/products/search?q=phone')
.then(res => res.json())
.then(console.log)
.catch(err => console.error('Error:', err));
4. Tambah Produk Baru
fetch('https://dummyjson.com/products/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'BMW Pencil' })
})
.then(res => res.json())
.then(console.log)
.catch(err => console.error('Error:', err));
5. Update Produk
fetch('https://dummyjson.com/products/1', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'iPhone Galaxy +1' })
})
.then(res => res.json())
.then(console.log)
.catch(err => console.error('Error:', err));
6. Hapus Produk
fetch('https://dummyjson.com/products/1', { method: 'DELETE' })
.then(res => res.json())
.then(console.log)
.catch(err => console.error('Error:', err));
7. Tips & Best Practices
- Error Handling: selalu pakai
.catch()
atau try/catch. - Async/Await: lebih readable untuk kode kompleks:
async function fetchProducts() {
try {
const res = await fetch('https://dummyjson.com/products');
const data = await res.json();
console.log(data);
} catch (err) {
console.error('Error:', err);
}
}
fetchProducts();
- Keamanan: jangan lupa handle data sensitif dengan aman.
Kesimpulan
Fetch API bikin HTTP request mudah dan fleksibel di JavaScript. CRUD, searching, dan data manipulation jadi simpel tanpa ribet.