1. Einführung
JavaScript ist eine der am weitesten verbreiteten Programmiersprachen in der Webentwicklung. Unter seinen vielen Funktionen hat die Fetch‑API als wichtige Fähigkeit zur Ermöglichung asynchroner Kommunikation Aufmerksamkeit erlangt.
In diesem Artikel erklären wir die Fetch‑API im Detail – von den Grundlagen bis zu fortgeschrittener Nutzung. Wenn Sie sie verstehen, können Sie das Abrufen von Daten und die Serverkommunikation in Webanwendungen reibungsloser implementieren.
Was ist asynchrone Kommunikation?
Asynchrone Kommunikation ist ein Verfahren zum Austausch von Daten mit einem Server, während andere Prozesse weiterlaufen, ohne zu blockieren, bis die Kommunikation abgeschlossen ist. Das verbessert die Reaktionsfähigkeit der Benutzeroberfläche und erleichtert die Datenverarbeitung ohne Frustration.
Beispielsweise kann ein Benutzer, der auf einer Webseite einen Button zum Abrufen von Daten klickt, andere Aufgaben fortsetzen, ohne auf die Serverantwort warten zu müssen, was die Benutzererfahrung erheblich verbessert.
Was ist die Fetch‑API?
Die Fetch‑API ist ein modernes Interface zum Durchführen asynchroner Kommunikation in JavaScript. Sie wurde als Alternative zum traditionellen XMLHttpRequest (XHR) eingeführt und bietet eine kompakte Syntax sowie flexible Konfiguration.
Mit dieser API können Sie leicht Logik schreiben, um Daten von einem Server abzurufen oder Daten an einen Server zu senden.
In den folgenden Abschnitten stellen wir alles Schritt für Schritt vor – von der grundlegenden Nutzung der Fetch‑API bis zu praktischen, realen Beispielen.
2. Was ist die Fetch‑API?
Die Fetch‑API ist das neueste standardisierte Interface zum Durchführen asynchroner Kommunikation in JavaScript. In diesem Abschnitt erklären wir ihre grundlegende Rolle und wie sie sich von traditionellen Ansätzen unterscheidet.
Überblick über die Fetch‑API
Die Fetch‑API ist dafür konzipiert, Ressourcen über ein Netzwerk abzurufen.
Damit wird es für Webanwendungen einfach, mit Servern zu kommunizieren.
Wesentliche Merkmale
- Promise‑basiert: Keine Notwendigkeit für Callback‑Funktionen, wodurch lesbarer Code entsteht.
- Kompakte Syntax: Im Vergleich zu XMLHttpRequest kann der Code deutlich reduziert werden.
- Hohe Flexibilität: Anfragen und Antworten können detailliert angepasst werden.
- Modernes Design: Arbeitet gut mit modernen JavaScript‑Features zusammen und ermöglicht wartbaren Code.
Unten finden Sie ein einfaches Beispiel für die Verwendung der Fetch‑API.
fetch('https://api.example.com/data')
.then(response => response.json()) // Convert to JSON
.then(data => console.log(data)) // Output the data
.catch(error => console.error('Error:', error)); // Error handling
Dieser Code ruft Daten von der angegebenen URL ab, konvertiert sie zu JSON und gibt sie in der Konsole aus. Bei einem Fehler wird eine Fehlermeldung ausgegeben.
Unterschiede zum traditionellen XMLHttpRequest
Die Fetch‑API ist ein neuer Ansatz, der das weit verbreitete XMLHttpRequest (XHR) ersetzt. Die folgende Tabelle vergleicht die beiden.
| Feature | Fetch API | XMLHttpRequest |
|---|---|---|
| Code simplicity | Concise, readable syntax | Often complex with many callbacks |
| Asynchronous handling | Supports Promises and offers high flexibility | Requires callback functions |
| Stream processing | Native support | Requires additional handling |
| Working with JSON | Easy to handle | Requires explicit parsing |
| Error handling | Flexible and can be centralized | Often becomes complex |
Wie Sie sehen, ist die Fetch‑API dank ihrer kompakten und modernen Gestaltung attraktiv. Insbesondere das Promise‑basierte Modell ermöglicht es, asynchrone Logik natürlicher zu schreiben.
Zusammenfassung
Die Fetch‑API ist ein leistungsstarkes und einfach zu nutzendes Werkzeug für asynchrone Kommunikation in JavaScript. Da sie einfacher zu implementieren ist als das traditionelle XHR, hat sie sich zu einer unverzichtbaren Fähigkeit für die moderne Webentwicklung entwickelt.
Im nächsten Abschnitt gehen wir konkrete Nutzungsmuster der Fetch‑API mit Codebeispielen durch. 
3. Grundlegende Verwendung der Fetch‑API
In diesem Abschnitt erklären wir die grundlegende Nutzung der Fetch‑API anhand konkreter Codebeispiele. Wir behandeln hauptsächlich die folgenden Punkte.
- Syntax der
fetch()‑Methode und ein Basisbeispiel - Wie man eine GET‑Anfrage implementiert
- Wie man Antwortdaten verarbeitet
Grundsyntax der fetch()‑Methode
Mit der Fetch‑API senden Sie Anfragen an einen Server über die fetch()‑Methode. Nachfolgend die Grundsyntax.
fetch(url, options)
.then(response => {
// Handle the response
})
.catch(error => {
// Handle errors
});
Argumente
- url : Die URL, an die die Anfrage gesendet wird.
- options (optional): Optionale Einstellungen, die Methode, Header, Body und mehr umfassen.
Rückgabewert
- Promise‑Objekt : Gibt das Ergebnis des asynchronen Prozesses zurück.
Wie man eine GET‑Anfrage implementiert
Die grundlegendste Verwendung der Fetch API ist eine GET‑Anfrage, die Daten von einem Server abruft.
Beispiel: JSON‑Daten mit Fetch abrufen
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) {
throw new Error('Network error');
}
return response.json(); // Retrieve data as JSON
})
.then(data => {
console.log(data); // Display the retrieved data
})
.catch(error => {
console.error('Error:', error); // Print an error log
});
Wie man Antwortdaten verarbeitet
Mit der Fetch API können Sie Antwortdaten in verschiedenen Formaten verarbeiten. Nachfolgend finden Sie gängige Beispiele.
- Textdaten abrufen
fetch('https://example.com/data.txt') .then(response => response.text()) // Retrieve data as text .then(data => console.log(data)) .catch(error => console.error('Error:', error));
- Binärdaten abrufen
fetch('https://example.com/image.jpg') .then(response => response.blob()) // Retrieve as binary data .then(blob => { const imgURL = URL.createObjectURL(blob); document.querySelector('img').src = imgURL; }) .catch(error => console.error('Error:', error));
- Header‑Informationen abrufen
fetch('https://example.com/api') .then(response => { console.log(response.headers.get('Content-Type')); // Get a header value }) .catch(error => console.error('Error:', error));
Zusammenfassung
Hier haben wir eine grundlegende GET‑Anfrage mit der Fetch API behandelt und gezeigt, wie man Antworten verarbeitet.
Die Fetch API ist ein flexibles Werkzeug, das das Abrufen vieler Datentypen wie Text, JSON und Binärdaten erleichtert. Sobald Sie diese Grundlagen verstanden haben, wird es einfacher, sie im nächsten Kapitel anzuwenden, einschließlich Fehlerbehandlung und POST‑Anfragen.
Im nächsten Abschnitt erklären wir die Fehlerbehandlung mit der Fetch API im Detail.
4. Fehlerbehandlung
In diesem Abschnitt erklären wir die Fehlerbehandlung bei der Verwendung der Fetch API. Beim Kommunizieren mit einem Server können verschiedene Probleme auftreten, wie Netzwerkfehler und Antwortfehler. Eine korrekte Handhabung kann die Benutzererfahrung verbessern.
Grundlagen der Fehlerbehandlung
Mit der Fetch API können Sie die catch()‑Methode verwenden, um Fälle wie Netzwerkfehler oder fehlerhafte Antworten zu behandeln.
Beispiel für grundlegende Fehlerbehandlung
fetch('https://example.com/data')
.then(response => {
if (!response.ok) { // Check the response status code
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('An error occurred:', error)); // Error handling
Fehlerbehandlung mit try…catch
Die Verwendung von Async/Await ermöglicht es Ihnen, saubereren und lesbareren Code zu schreiben. In diesem Fall behandeln Sie Fehler mit einer try...catch‑Anweisung.
Beispiel: Fehlerbehandlung mit Async/Await
async function fetchData() {
try {
const response = await fetch('https://example.com/data');
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('An error occurred:', error);
}
}
fetchData();
Implementierung von Timeouts
Die Fetch API enthält standardmäßig keine eingebaute Timeout‑Funktion. Durch die Implementierung von Timeouts können Sie jedoch langsam reagierende Antworten angemessen behandeln.
Beispiel: Implementierung eines Timeouts
function fetchWithTimeout(url, timeout = 5000) {
return Promise.race([
fetch(url),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Request timed out')), timeout)
),
]);
}
fetchWithTimeout('https://example.com/data', 5000)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP-Fehler! Status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Ein Fehler ist aufgetreten:', error));
Detecting network errors
A network error refers to cases where the server cannot be reached or the connection is interrupted. With the Fetch API, these errors can also be detected with catch().
Example: Handling a network error
fetch('https://invalid-url.com/data')
.then(response => response.json())
.catch(error => console.error('Netzwerkfehler:', error.message));
Summary
In this section, we introduced error handling with the Fetch API, from basics to more advanced patterns.
Key takeaways
- Check response status codes and implement error handling
- Simplify error handling with Async/Await
- Handle slow responses by implementing timeouts
Error handling is critical for improving the user experience. In the next section, we’ll explain POST requests for sending data to a server.

5. Sending POST requests
In this section, we explain how to send POST requests with the Fetch API to send data to a server. We’ll cover practical examples such as sending form data and JSON.
Basic syntax for POST requests
You can implement a POST request in the Fetch API by providing an options object as the second argument to the fetch() method.
Basic syntax
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Fehler:', error));
Example: Sending JSON data
Below is an example of sending user information in JSON format.
const userData = {
name: 'Taro Yamada',
email: 'yamada@example.com',
};
fetch('https://example.com/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData),
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP-Fehler! Status: ${response.status}`);
}
return response.json();
})
.then(data => console.log('Erfolg:', data))
.catch(error => console.error('Fehler:', error));
Example: Sending form data
To send form data, use the FormData object.
const formData = new FormData();
formData.append('username', 'yamada');
formData.append('file', fileInput.files[0]);
fetch('https://example.com/upload', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => console.log('Hochladen erfolgreich:', data))
.catch(error => console.error('Fehler:', error));
Example: Requests with authentication information
When sending data along with authentication information (for example, a token), add the auth data to the request headers.
fetch('https://example.com/api/protected', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
},
body: JSON.stringify({ message: 'Hello!' }),
})
.then(response => response.json())
.then(data => console.log('Erfolg:', data))
.catch(error => console.error('Fehler:', error));
Error handling for POST requests
For POST requests, you can add error handling like the following to deal with network issues or server-side problems.
async function postData(url, data) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error(`HTTP-Fehler! Status: ${response.status}`);
}
const result = await response.json();
console.log('Success:', result);
} catch (error) {
console.error('An error occurred:', error.message);
}
}
postData('https://example.com/api/messages', { text: 'Hello!' });
Summary
In this section, we explained the basics and practical usage of POST requests using the Fetch API.
Key takeaways
- How to send JSON data and form data
- How to implement requests with authentication information
- How to strengthen error handling
POST requests are essential for two-way communication with servers. In the next section, we’ll explain customization options for the Fetch API in detail.
6. Other option settings
In this section, we explain various option settings you can specify as the second argument to the Fetch API. By using these, you can easily customize requests and manage authentication information.
Basic option syntax
Fetch API options are specified as an object in the second argument.
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
},
body: JSON.stringify(data),
credentials: 'include',
mode: 'cors',
cache: 'no-cache',
redirect: 'follow',
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Details of each option
method(HTTP method)
- Specifies the HTTP method (for example: GET, POST, PUT, DELETE).
- The default is
GET.
headers(headers)
- Specifies request headers.
- Used to define the data format or add authentication information.
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_ACCESS_TOKEN', }
body(sending data)
- Used to send data to the server with POST or PUT methods.
credentials(managing credentials)
- Controls whether credentials (cookies or HTTP authentication data) are sent.
| Value | Description |
|---|---|
omit | Do not send credentials (default) |
same-origin | Send credentials only for same-origin requests |
include | Send credentials even for cross-origin requests |
mode(CORS policy)
- Controls cross-origin request behavior.
| Value | Description |
|---|---|
cors | Allow cross-origin requests (default) |
no-cors | Allow only simple requests (limited) |
same-origin | Allow requests only to the same origin |
cache(cache control)
- Controls how request caching is used.
| Value | Description |
|---|---|
default | Use the browser’s default cache settings |
no-store | Do not use cache; always make a new request |
reload | Ignore cache and make a new request |
redirect(redirect handling)
- Specifies how redirects are handled.
| Value | Description |
|---|---|
follow | Automatically follow redirects (default) |
error | Treat redirects as errors |
manual | Handle redirects manually (controllable in code) |
Advanced customization example
Below is an example that combines multiple options.
fetch('https://example.com/api/resource', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
},
body: JSON.stringify({ message: 'Hello!' }),
credentials: 'include',
mode: 'cors',
cache: 'no-cache',
redirect: 'follow',
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
Summary
In this section, we explained various Fetch API option settings in detail.
Key takeaways
- How to customize headers and credentials
- Fine-grained settings such as CORS and cache control
- Advanced patterns for redirects and error handling
In the next section, we’ll introduce concrete examples of how to use the Fetch API in practice.

7. Practical examples of using the Fetch API
In this section, we explain how you can use the Fetch API in real projects with concrete examples. Through practical scenarios, you’ll build real-world Fetch API skills.
Displaying a list of API data
A common use case in web applications is fetching data from an external API and displaying it as a list. In the example below, we fetch post data from the JSONPlaceholder API and display it as an HTML list.
Code example
const url = 'https://jsonplaceholder.typicode.com/posts';
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP-Fehler! Status: ${response.status}`);
}
return response.json();
})
.then(posts => {
const list = document.getElementById('post-list');
posts.forEach(post => {
const listItem = document.createElement('li');
listItem.textContent = `${post.id}: ${post.title}`;
list.appendChild(listItem);
});
})
.catch(error => console.error('Fehler:', error));
HTML example
<ul id="post-list"></ul>
Submitting a form and registering data
This is an example of registering data from a form input to a server.
Code example
const form = document.getElementById('user-form');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const formData = {
name: document.getElementById('name').value,
email: document.getElementById('email').value,
};
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});
if (!response.ok) {
throw new Error(`HTTP-Fehler! Status: ${response.status}`);
}
const result = await response.json();
console.log('Registrierung erfolgreich:', result);
alert('Der Benutzer wurde registriert!');
} catch (error) {
console.error('Fehler:', error);
alert('Ein Fehler ist aufgetreten.');
}
});
HTML example
<form id="user-form">
<input type="text" id="name" placeholder="Name" required />
<input type="email" id="email" placeholder="E-Mail-Adresse" required />
<button type="submit">Registrieren</button>
</form>
File upload
The Fetch API can also handle file uploads. Below is an example of uploading an image file to a server.
Code example
const fileInput = document.getElementById('file-input');
const uploadButton = document.getElementById('upload-button');
uploadButton.addEventListener('click', async () => {
const file = fileInput.files[0];
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch('https://example.com/upload', {
method: 'POST',
body: formData,
});
if (!response.ok) {
throw new Error(`HTTP-Fehler! Status: ${response.status}`);
}
const result = await response.json();
console.log('Upload erfolgreich:', result);
alert('Die Datei wurde hochgeladen!');
} catch (error) {
console.error('Fehler:', error);
alert('Upload fehlgeschlagen.');
}
});
HTML example
<input type="file" id="file-input" />
<button id="upload-button">Hochladen</button>
Summary
In this section, we introduced practical examples using the Fetch API.
Key takeaways
- Creating a dynamic list by displaying API data
- Implementing form submission and data registration
- Implementing file uploads and search functionality
By using these examples as references, you can build interactive web applications powered by the Fetch API. In the next section, we’ll summarize the entire article and introduce learning resources for your next steps.
8. Summary
In this article, we explained JavaScript’s Fetch API systematically—from the basics to practical use. The Fetch API is a powerful tool that enables asynchronous communication concisely and efficiently, making it essential for modern web application development.
Review of what you learned
- Overview and features of the Fetch API
- The Fetch API is Promise-based, allowing concise and flexible code.
- Compared to traditional XMLHttpRequest, the syntax is simpler and easier to maintain.
- Basic usage and error handling
- Basic syntax for fetching data with GET requests.
- By adding error handling and timeout processing, you can implement more robust code.
- Sending data with POST requests
- Beispiele für das Senden von JSON-Daten und Formulardaten.
- Erfahren, wie man Authentifizierungsinformationen und benutzerdefinierte Header hinzufügt.
- Optionseinstellungen effektiv nutzen
- Flexible Anpassungsmethoden wie Cache‑Control, CORS‑Einstellungen und Credential‑Management vorgestellt.
- Praktische Beispiele
- Praktische Anwendung durch Beispiele wie Listenanzeige, Formularübermittlung, Datei‑Uploads und Suchfunktion gelernt.
Vorteile und Hinweise zur Fetch API
Vorteile
- Der Code ist kompakt und sehr lesbar.
- Funktioniert gut mit Promises und Async/Await, wodurch er sich leicht mit moderner JavaScript‑Syntax kombinieren lässt.
- Unterstützt viele Datenformate wie JSON, Binärdaten und Streams.
Hinweise
- Standardmäßig gibt es keine Timeout‑Funktion, daher muss man sie ggf. selbst implementieren.
- Sie wird in älteren Browsern (z. B. Internet Explorer) nicht unterstützt, daher sollten bei Bedarf Polyfills oder Alternativen in Betracht gezogen werden.
Lernressourcen für die nächsten Schritte
Um Ihr Verständnis der Fetch API zu vertiefen, nutzen Sie die offizielle Dokumentation und die untenstehenden Ressourcen.
- MDN Web Docs (Fetch API) https://developer.mozilla.org/ja/docs/Web/API/Fetch_API
- JavaScript‑Dokumentation bei MDN https://developer.mozilla.org/ja/docs/Web/JavaScript
- Beispielprojekte und Code‑Sammlungen Es kann auch hilfreich sein, reale Projekte, die die Fetch API nutzen, auf GitHub oder CodePen zu erkunden.
Fazit
Die Fetch API ist ein leistungsstarkes Werkzeug, das es ermöglicht, die Serverkommunikation einfach mit modernen JavaScript‑Techniken zu implementieren. Durch die Anwendung des in diesem Artikel Gelernten können Sie interaktivere und funktionsreichere Webanwendungen erstellen.
Da sich die Webentwicklung ständig weiterentwickelt, werden API‑Integration und asynchrone Verarbeitung noch wichtiger. Beherrschen Sie die Fetch API und schärfen Sie Ihre praktischen Fähigkeiten!
Nächste Schritte
- Versuchen Sie, ein Projekt zu erstellen, das eine reale API nutzt.
- Verwenden Sie benutzerdefinierte Optionen, um eine fortgeschrittenere Anfragenverarbeitung zu implementieren.
- Fordern Sie sich heraus, Full‑Stack‑Anwendungen zu bauen, die ein serverseitiges Backend integrieren.
Damit endet der Artikel. Wir hoffen, dass das Erlernen der Fetch API Ihnen hilft, Ihre Fähigkeiten weiter zu verbessern!


