69 lines
2.1 KiB
HTML
69 lines
2.1 KiB
HTML
<!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>
|