👋 Hallo, Front-End-Entwickler!
Heute werden wir eines der wichtigsten Themen in der Welt von JavaScript und React analysieren - die Arbeit mit APIs. Wir lernen, wie man HTTP-Anfragen sendet, Fehler behandelt und beliebte Bibliotheken wie fetch, axios und TanStack Query verwendet.
📡 Was ist eine API?
API (Application Programming Interface) ist eine Schnittstelle, über die Programme Daten miteinander austauschen. Beispielsweise kann Ihre React-App Beiträge von einem Remote-Server über eine API abrufen.
🛠️ APIs werden häufig mit Frameworks erstellt:
JavaScript — Express.js
Python — Django / Flask
Go — Gin
Java — Spring Boot
C# — ASP.NET Core
🔄 Was ist API-Verarbeitung?
API-Verarbeitung ist der Prozess des Sendens von HTTP-Anfragen an den Server und des Verarbeitens der empfangenen Antwort. In JavaScript und React werden am häufigsten verwendet:
fetch— integrierte Browser-Methodeaxios— beliebte externe BibliothekTanStack Query(früher React Query) — Bibliothek zur einfachen Verwaltung asynchroner Daten in React
📬 Grundlegende HTTP-Methoden
Methode | Zweck |
|---|---|
| Datenabruf |
| Neue Daten werden gesendet |
| Vollständige Aktualisierung der Ressource |
| Teilweise Aktualisierung der Ressource |
| Daten vom Server löschen |
⚙️ Arbeiten mit der API über fetch
Einfache GET-Anfrage
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json())
.then(data => scrib.show(data))
.catch(err => scrib.show('Error:', err));POST-Anfrage mit Text
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
title: 'JS is cool!',
body: 'Scribbler allows you to combine HTML and JS',
userId: 1
})
})
.then(res => res.json())
.then(data => scrib.show(data))
.catch(err => scrib.show('Error:', err));Fehlerbehandlung durch try/catch
async function getData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) throw new Error('Network error');
const data = await response.json();
scrib.show(data);
} catch (err) {
scrib.show('Error:', err);
} finally {
scrib.show('Request completed');
}
}
getData();⚡ Verwendung von axios
axios bietet eine sauberere Syntax und eine komfortable Fehlerbehandlung.
GET-Anfrage
import axios from 'axios';
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(res => scrib.show(res.data))
.catch(err => scrib.show('Error:', err));POST-Anfrage
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'Axios rules!',
body: 'Error handling is much easier',
userId: 1
}, {
headers: { 'Content-Type': 'application/json' }
})
.then(res => scrib.show(res.data))
.catch(err => scrib.show('Error:', err));Erweiterte Fehlerbehandlung
axios.get('https://jsonpl.typicode.com/posts')
.catch(error => {
if (error.response) {
scrib.show('Server error:', error.response.status);
} else if (error.request) {
scrib.show('No response from the server');
} else {
scrib.show('Request error:', error.message);
}
});⚛️ API in React (useEffect + useState)
import { useEffect, useState } from 'react';
function Posts() {
const [posts, setPosts] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => {
if (!res.ok) throw new Error('Error retrieving data');
return res.json();
})
.then(setPosts)
.catch(err => setError(err.message));
}, []);
if (error) return <p>Ошибка: {error}</p>;
return (
<div>
<h2>Посты</h2>
<ul>{posts.map(p => <li key={p.id}>{p.title}</li>)}</ul>
</div>
);
}⚙️ TanStack Query (React Query)
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
const fetchPosts = async () => {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
return data;
};
function Posts() {
const { data: posts, error, isLoading } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts
});
if (isLoading) return <p>Загрузка...</p>;
if (error) return <p>Ошибка: {error.message}</p>;
return <ul>{posts.map(post => <li key={post.id}>{post.title}</li>)}</ul>;
}✅ Schlussfolgerungen
📌 API-Verarbeitung ist eine Schlüsselkompetenz in der Webentwicklung. Das Wichtigste:
Meistern Sie
fetchundaxiosHTTP-Methoden verstehen
Fehler behandeln können
Verwenden Sie
useEffectin ReactAutomatisieren Sie das Laden von Daten mit TanStack Query
