Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Vue

HTTP Requests di JavaScript dengan Axios

1 min read .
HTTP Requests di JavaScript dengan Axios

Kalau urusan HTTP request di JavaScript, Axios itu lifesaver. Sintaksnya simpel, promise-based, dan lebih bersih dibanding fetch. Gini deh, saya kasih contoh CRUD pakai DummyJSON API.

1. Instalasi

npm install axios

Atau pakai CDN:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

2. Ambil Semua Produk

axios.get('https://dummyjson.com/products')
  .then(res => console.log(res.data))
  .catch(err => console.error('Error:', err));

3. Ambil Produk Berdasarkan ID

axios.get('https://dummyjson.com/products/1')
  .then(res => console.log(res.data))
  .catch(err => console.error('Error:', err));

4. Cari Produk

axios.get('https://dummyjson.com/products/search?q=phone')
  .then(res => console.log(res.data))
  .catch(err => console.error('Error:', err));

5. Tambah Produk Baru

axios.post('https://dummyjson.com/products/add', { title: 'BMW Pencil' })
  .then(res => console.log(res.data))
  .catch(err => console.error('Error:', err));

6. Update Produk

axios.put('https://dummyjson.com/products/1', { title: 'iPhone Galaxy +1' })
  .then(res => console.log(res.data))
  .catch(err => console.error('Error:', err));

7. Hapus Produk

axios.delete('https://dummyjson.com/products/1')
  .then(res => console.log(res.data))
  .catch(err => console.error('Error:', err));

8. Modul Axios

Biar rapi, bisa bikin modul:

// api.js
import axios from 'axios';

const apiClient = axios.create({
  baseURL: 'https://dummyjson.com/',
  headers: { 'Content-Type': 'application/json' }
});

export default {
  getProducts: () => apiClient.get('products'),
  getProduct: id => apiClient.get(`products/${id}`),
  searchProducts: q => apiClient.get('products/search', { params: { q } }),
  addProduct: p => apiClient.post('products/add', p),
  updateProduct: (id, p) => apiClient.put(`products/${id}`, p),
  deleteProduct: id => apiClient.delete(`products/${id}`)
};

Import dan pakai di kode utama:

import api from './api.js';

api.getProducts().then(res => console.log(res.data));

9. Tips dan Best Practices

  • Error Handling: selalu pakai .catch().
  • Interceptors: buat token atau transform global request/response.
  • Timeout: cegah server nge-hang.
const apiClient = axios.create({ baseURL: 'https://dummyjson.com/', timeout: 5000 });

Kesimpulan

Axios bikin HTTP request di JavaScript jadi mudah, cepat, dan rapi. CRUD, interceptors, timeout, semua bisa di-handle dengan clean syntax. Pada akhirnya, kerjaan coding jadi lebih lancar tanpa ribet.

Lihat Juga

HTTP Requests di JavaScript dengan Fetch API
HTTP Requests di JavaScript dengan Fetch API
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 Copy fetch('https://dummyjson.com/products') .then(res => res.json()) .then(console.log) .catch(err => console.error('Error:', err)); 2. Ambil Produk Berdasarkan ID Copy fetch('https://dummyjson.com/products/1') .then(res => res.json()) .then(console.log) .catch(err => console.error('Error:', err)); 3. Cari Produk Copy 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 Copy 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 Copy 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 Copy 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: Copy 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.
chevron-up