Berikut contoh kode JavaScript menggunakan library Axios untuk mengirimkan request ke server HTML. Kode ini mencakup contoh penggunaan GET dan POST request.
Contoh dengan axios
- Menggunakan
GET Request
// Tambahkan library Axios di proyek Anda terlebih dahulu dengan npm, yarn, atau gunakan CDN
// Contoh dengan CDN:
// <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
console.log('Response data:', response.data); // Data hasil fetch
})
.catch(error => {
console.error('Error:', error); // Menangkap error
});
- Menggunakan
POST Request
Jika Anda ingin mengirimkan data ke server.
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'My Post',
body: 'This is the body of the post.',
userId: 1
})
.then(response => {
console.log('Response data:', response.data); // Data respons dari server
})
.catch(error => {
console.error('Error:', error); // Menangkap error
});
- Penggunaan dengan Asynchronous/Await
Anda juga dapat menggunakan async/await untuk penulisan yang lebih bersih:
// Fungsi async untuk GET request
async function fetchData() {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
console.log('Response data:', response.data);
} catch (error) {
console.error('Error:', error);
}
}
// Fungsi async untuk POST request
async function sendData() {
try {
const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'New Post',
body: 'This is the body of the post.',
userId: 2
});
console.log('Response data:', response.data);
} catch (error) {
console.error('Error:', error);
}
}
// Panggil fungsi
fetchData();
sendData();
Penjelasan
- Axios adalah library populer untuk membuat HTTP request di browser atau Node.js.
GET digunakan untuk mengambil data dari server.
POST digunakan untuk mengirimkan data ke server.
- Hasil respon biasanya dicetak di
response.data.
- Gunakan try-catch untuk menangani error jika Anda menggunakan
async/await.
Untuk memasang Axios, Anda bisa menginstalnya dengan Node.js CLI:
npm install axios
Atau gunakan CDN di kode HTML Anda dengan tag <script> seperti ini:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Semoga membantu! 😊