Files
JS/02_advanced/uebungen/u23_fetch-users/index.html
Philippe Torrel 199d580016
2026-07-08 11:55:05 +02:00

69 lines
2.1 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!doctype html>
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Übung 23: Fetch API Einfache Datenabfrage</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<main>
<div class="container py-5">
<div class="alert alert-primary">
<h2>Übung 23: Fetch API Einfache Datenabfrage</h2>
<p>
Erstelle eine Funktion <code>fetchUsers</code>, die mithilfe der Fetch API eine Liste von Benutzern von der
DummyJSON-API abruft. Verwende async/await und try/catch, um Netzwerkfehler abzufangen. Die abgerufenen
Daten sollen dann in der Konsole ausgegeben werden.
</p>
<p>
<strong>Hinweis:</strong> Verwende die URL
<a href="https://dummyjson.com/users">https://dummyjson.com/users</a> für den Fetch-Aufruf.
</p>
</div>
<div class="output alert alert-secondary my-3"></div>
</div>
</main>
<script>
'use strict';
const outputEl = document.querySelector('.output');
const fetchUsers = async () => {
try {
// Fetch-aufruf an die API
const response = await fetch('https://dummyjson.com/users');
// Prüfen ob die OK ist
if (!response.ok) {
throw new Error(`HTTP-Fehler: ${response.status}`);
}
// JSON-Daten parsen
const data = await response.json();
return data;
return data;
} catch (error) {
console.error(error.message);
}
};
// Funktionsaufruf
fetchUsers().then((data) => {
console.log(data);
console.log(data.users.length);
outputEl.innerHTML = '';
data.users.forEach((user) => {
const { firstName, lastName, email } = user;
console.log(`${firstName} ${lastName} (${email})`);
outputEl.innerHTML += `${firstName} ${lastName} (${email})<br />`;
});
});
</script>
</body>
</html>