Axios Kütüphanesini Yükleme
HTML dosyanın <script>
etiketi içine şunu ekleyebilirsin:
script
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
sh
npm install axios
veya
sh
yarn add axios
api.js
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log(response.data); // API’den gelen veriyi göster
})
.catch(error => {
console.error('Hata:', error);
});
api.js
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'Yeni Post',
body: 'Bu bir deneme gönderisidir.',
userId: 1
})
.then(response => {
console.log('Başarıyla gönderildi:', response.data);
})
.catch(error => {
console.error('Hata:', error);
});
api.js
axios.put('https://jsonplaceholder.typicode.com/posts/1', {
title: 'Güncellenmiş Başlık',
body: 'Bu yazının içeriği güncellendi.',
userId: 1
})
.then(response => console.log(response.data))
.catch(error => console.error('Hata:', error));
api.js
axios.delete('https://jsonplaceholder.typicode.com/posts/1')
.then(response => console.log('Silme başarılı', response.data))
.catch(error => console.error('Hata:', error));
api.js
axios.all([
axios.get('https://jsonplaceholder.typicode.com/posts/1'),
axios.get('https://jsonplaceholder.typicode.com/posts/2')
])
.then(axios.spread((post1, post2) => {
console.log('Post 1:', post1.data);
console.log('Post 2:', post2.data);
}))
.catch(error => console.error('Hata:', error));
Eğer her istekte aynı URL veya başlığı kullanıyorsan, varsayılan bir yapı oluşturabilirsin
api.js
const api = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 1000,
headers: { 'X-Custom-Header': 'myApp' }
});
// Artık `api.get()` ile aynı ayarları kullanarak çağrı yapabilirsin.
api.get('/posts')
.then(response => console.log(response.data))
.catch(error => console.error('Hata:', error));
Axios, HTTP isteklerini yönetmek için güçlü ve esnek bir kütüphanedir.
✅ Kolay Kullanım
✅ Daha İyi Hata Yönetimi
✅ İstekleri Otomatik JSON Formatında Yönetme