Skip to content

Kapitel 36: axios Grundlagen

📙 Lernziel: axios installieren und API-Aufrufe meistern!


36.1 Was ist axios?

axios ist eine beliebte Bibliothek für HTTP-Anfragen.

Vorteile:

  • ✅ Einfach zu verwenden
  • ✅ Promise-basiert (async/await)
  • ✅ Automatische JSON-Umwandlung
  • ✅ Interceptors (Request/Response)

Vergleich:

Merkmalfetch APIaxios
Bundle-Größe0 (Browser eingebaut)~13KB
FehlerbehandlungManuell (response.ok)Automatisch
Request/Response Interceptors❌ Nein✅ Ja
Abbrechen (Cancel)✅ Ja (AbortController)✅ Ja

36.2 axios installieren

Installation:

bash
# Mit pnpm (empfohlen)
pnpm add axios

# Mit npm
npm install axios

# Mit yarn
yarn add axios

Überprüfung (package.json):

json
{
  "dependencies": {
    "vue": "^3.4.0",
    "axios": "^1.6.0"
  }
}

36.3 Erstes API-Aufruf (GET)

Beispiel:

vue
<!-- views/PostsView.vue -->
<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const posts = ref([])
const isLoading = ref(false)
const error = ref(null)

const fetchPosts = async () => {
  isLoading.value = true
  error.value = null
  
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts?_limit=5')
    posts.value = response.data
  } catch (err) {
    error.value = err.message
    console.error('Fehler:', err)
  } finally {
    isLoading.value = false
  }
}

// Beim Mounten ausführen
onMounted(fetchPosts)
</script>

<template>
  <div class="posts-view">
    <h2>Posts</h2>
    
    <div v-if="isLoading">Lädt...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <ul v-else>
      <li v-for="post in posts" :key="post.id">
        <h3>{{ post.title }}</h3>
        <p>{{ post.body }}</p>
      </li>
    </ul>
    
    <button @click="fetchPosts()">Neu laden</button>
  </div>
</template>

<style scoped>
.posts-view {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.error {
  color: red;
  padding: 10px;
  background: #ffebeb;
  border-radius: 4px;
}

button {
  padding: 10px 20px;
  background: #42b883;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-top: 20px;
}
</style>

Wichtig:

  • response.data enthält die Antwort-Daten
  • ✅ Immer try-catch für Fehlerbehandlung nutzen
  • isLoading für Ladezustand

36.4 Verschiedene HTTP-Methoden

Beispiele:

vue
<script setup>
import { ref } from 'vue'
import axios from 'axios'

const post = ref({ title: '', body: '' })
const response = ref(null)

// GET (Daten abrufen)
const fetchPost = async (id) => {
  try {
    const res = await axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`)
    post.value = res.data
  } catch (error) {
    console.error('Fehler:', error)
  }
}

// POST (Daten erstellen)
const createPost = async () => {
  try {
    const res = await axios.post('https://jsonplaceholder.typicode.com/posts', post.value)
    response.value = res.data
    alert('Post erstellt!')
  } catch (error) {
    console.error('Fehler:', error)
  }
}

// PUT (Daten aktualisieren)
const updatePost = async (id) => {
  try {
    const res = await axios.put(`https://jsonplaceholder.typicode.com/posts/${id}`, post.value)
    response.value = res.data
    alert('Post aktualisiert!')
  } catch (error) {
    console.error('Fehler:', error)
  }
}

// DELETE (Daten löschen)
const deletePost = async (id) => {
  try {
    await axios.delete(`https://jsonplaceholder.typicode.com/posts/${id}`)
    alert('Post gelöscht!')
  } catch (error) {
    console.error('Fehler:', error)
  }
}
</script>

<template>
  <div>
    <h2>Post erstellen</h2>
    <form @submit.prevent="createPost()">
      <div>
        <label>Titel:</label>
        <input v-model="post.title" required />
      </div>
      <div>
        <label>Inhalt:</label>
        <textarea v-model="post.body" required></textarea>
      </div>
      <button type="submit">Speichern</button>
    </form>
    
    <div v-if="response">
      <h3>Antwort:</h3>
      <pre>{{ JSON.stringify(response, null, 2) }}</pre>
    </div>
  </div>
</template>

Kurzformen:

javascript
axios.get(url, config)
axios.post(url, data, config)
axios.put(url, data, config)
axios.patch(url, data, config)
axios.delete(url, config)

36.5 axios() Konfiguration

Vollständige Konfiguration:

javascript
import axios from 'axios'

const response = await axios({
  method: 'post',
  url: 'https://jsonplaceholder.typicode.com/posts',
  data: {
    title: 'Neuer Post',
    body: 'Inhalt...'
  },
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token123'
  },
  params: {
    _limit: 5
  },
  timeout: 5000,  // 5 Sekunden
  responseType: 'json'  // 'blob', 'arraybuffer', etc.
})

console.log(response.data)
console.log(response.status)
console.log(response.headers)

36.6 Übung: User-Liste mit axios

Aufgabe: Erstelle eine User-Liste, die Daten von API lädt.

Lösung:

vue
<!-- views/UsersView.vue -->
<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const users = ref([])
const isLoading = ref(false)
const error = ref(null)

const fetchUsers = async () => {
  isLoading.value = true
  error.value = null
  
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/users')
    users.value = response.data
  } catch (err) {
    error.value = err.message
  } finally {
    isLoading.value = false
  }
}

onMounted(fetchUsers)
</script>

<template>
  <div class="users-view">
    <h2>Benutzer</h2>
    
    <div v-if="isLoading" class="loading">Lädt...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else>
      <ul class="user-list">
        <li v-for="user in users" :key="user.id" class="user-card">
          <h3>{{ user.name }}</h3>
          <p>Email: {{ user.email }}</p>
          <p>Stadt: {{ user.address.city }}</p>
          <p>Telefon: {{ user.phone }}</p>
        </li>
      </ul>
    </div>
    
    <button @click="fetchUsers()" :disabled="isLoading">
      {{ isLoading ? 'Lädt...' : 'Neu laden' }}
    </button>
  </div>
</template>

<style scoped>
.users-view {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.loading {
  text-align: center;
  padding: 50px;
  font-size: 1.2em;
}

.error {
  color: red;
  padding: 10px;
  background: #ffebeb;
  border-radius: 4px;
  margin: 10px 0;
}

.user-list {
  list-style: none;
  padding: 0;
}

.user-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  margin: 10px 0;
}

.user-card h3 {
  color: #42b883;
  margin-top: 0;
}

button {
  padding: 10px 20px;
  background: #42b883;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

button:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style>

✅ Zusammenfassung

In diesem Kapitel hast du gelernt:

  • ✅ Was axios ist
  • ✅ axios installieren
  • ✅ Erstes API-Aufruf (GET)
  • ✅ Verschiedene HTTP-Methoden (GET, POST, PUT, DELETE)
  • axios() Konfiguration
  • ✅ Praxis: User-Liste mit axios

🎯 Nächster Schritt: In Kapitel 37 lernst du axios Instance & Interceptors!


← Zurück zu Kapitel 35: DatenpersistenzWeiter zu Kapitel 37: axios Instance & Interceptors →

Frei für alle Anfänger