Wie können wir helfen?

Kategorien
Inhalt

Einführung in Axios

Navigation:
< zurück

Was ist Axios?

Axios ist eine Promise-basierte HTTP-Client-Bibliothek. Sie kann verwendet werden, um HTTP-Anfragen zu senden und zu empfangen, was besonders nützlich ist, wenn man mit APIs arbeitet. Da Axios auf Promises basiert, ermöglicht es eine einfache und übersichtliche Handhabung von asynchronen Operationen.

Installation

  1. Im Browser:
    Axios kann über ein `<script>`-Tag eingebunden werden:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  1. In Node.js:
    Axios mit npm installieren:
npm install axios

Grundlegende Verwendung von Axios

Erstelle eine Datei namens `index.js` und füge die folgenden Beispiele hinzu.

  1. GET-Request
const axios = require('axios');

axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
  console.log('GET Response:', response.data);
})
.catch(error => {
  console.error('Error making GET request:', error);
});

Dieser Code sendet einen GET-Request an eine Beispiel-API und gibt die Antwort im Terminal aus.

  1. POST-Request
const axios = require('axios');

axios.post('http://jsonplaceholder.typicode.com/todos', {
  title: 'New Todo',
  completed: false
})
.then(response => {
  console.log('POST Response:', response.data);
})
.catch(error => {
  console.error('Error making POST request:', error);
});

Dieser Code sendet einen POST-Request an die Beispiel-API, um eine neue Aufgabe zu erstellen.

  1. PUT-Request
const axios = require('axios');

axios.put('https://jsonplaceholder.typicode.com/todos/1', {
  title: 'Updated Todo',
  completed: true
})
.then(response => {
  console.log('PUT Response:', response.data);
})
.catch(error => {
  console.error('Error making PUT request:', error);
});

Dieser Code sendet einen PUT-Request, um eine bestehende Aufgabe zu aktualisieren.

  1. DELETE-Request
const axios = require('axios');

axios.delete('https://jasonplaceholder.typicode.com/todos/1')
.then(response => {
  console.log('DELETE Response:', response.data);
})
.catch(error => {
  console.error('Error making DELETE request:', error);
});

Dieser Code sendet einen DELETE-Request, um eine Aufgabe zu löschen.

Fazit

Axios macht es einfach, mit APIs zu interagieren, und bietet viele nützliche Funktionen, die die Arbeit mit HTTP-Anfragen erleichtert. Diese Grundlagen sind die Basis, Axios in eigenen Projekten zu verwenden und komplexere Anfragen zu verwalten.