Sarıkaya Dev Logo

JavaScript ile Axios Kullanımı

Mahmut Sarıkaya 1 min read 0
JavaScript ile Axios Kullanımı

Axios Kütüphanesini Yükleme

CDN Kullanarak

HTML dosyanın <script> etiketi içine şunu ekleyebilirsin:





cdn

script · script

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

NPM veya Yarn ile Yükleme (Node.js Projeleri İçin)



terminal

sh · sh

npm install axios

veya

terminal

sh · sh

yarn add axios

2. GET ve POST İstekleri

GET İsteği (Veri Çekme)


GET

api.js · 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);
  });

POST İsteği (Veri Gönderme)



POST

api.js · 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);
  });

3. PUT ve DELETE İstekleri



PUT (Veri Güncelleme)

api.js · 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));

DELETE (Veri Silme)



DELETE

api.js · 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));

DELETE (Veri Silme)



Axios ile Başlık (Header) ve Token Kullanımı

api.js · 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));

Axios İçin Varsayılan Ayarlar Tanımlama

Eğer her istekte aynı URL veya başlığı kullanıyorsan, varsayılan bir yapı oluşturabilirsin

Axios ile Başlık (Header) ve Token Kullanımı

api.js · 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

Tags: #Axios Kütüphanesini Yükleme
Share:
M

Written by

Mahmut Sarıkaya

Software Developer

Comments

No comments yet. Be the first to share your thoughts!

Leave a Comment

4 + 7 =