This commit is contained in:
58
public/dashboard.js
Normal file
58
public/dashboard.js
Normal file
@@ -0,0 +1,58 @@
|
||||
// dashboard.js
|
||||
import { authFetch } from "api.js";
|
||||
|
||||
// Element‑Referenzen
|
||||
const welcomeMessage = document.getElementById("welcomeMessage");
|
||||
const todosList = document.getElementById("todosList");
|
||||
const errorMessage = document.getElementById("errorMessage");
|
||||
const logoutBtn = document.getElementById("logoutBtn");
|
||||
|
||||
// Prüfe ob ein JWT vorhanden ist
|
||||
const token = localStorage.getItem("token");
|
||||
if (!token) {
|
||||
// Kein Token → zurück zur Login‑Seite
|
||||
window.location.href = "login.html";
|
||||
}
|
||||
|
||||
// Logout – Token löschen + weiterleiten
|
||||
logoutBtn.addEventListener("click", () => {
|
||||
localStorage.removeItem("token");
|
||||
window.location.href = "login.html";
|
||||
});
|
||||
|
||||
// Lade Todos vom Backend
|
||||
async function loadTodos() {
|
||||
try {
|
||||
const res = await authFetch("/todos"); // fetchWrapper sendet den JWT Automatisch
|
||||
if (!res.ok) {
|
||||
errorMessage.textContent = "Fehler beim Abrufen der Todos!";
|
||||
if (res.status === 401) {
|
||||
window.location.href = "login.html"; // bei ungültigem Token zum Login
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const todos = await res.json();
|
||||
|
||||
// Zeige Todos in der Liste an
|
||||
todosList.innerHTML = "";
|
||||
if (Array.isArray(todos) && todos.length > 0) {
|
||||
todos.forEach(todo => {
|
||||
const li = document.createElement("li");
|
||||
li.textContent = todo.task;
|
||||
todosList.appendChild(li);
|
||||
});
|
||||
} else {
|
||||
todosList.innerHTML = "<li>Keine Todos gefunden.</li>";
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Fetch Error:", err);
|
||||
errorMessage.textContent = "Serverfehler beim Laden!";
|
||||
}
|
||||
}
|
||||
|
||||
// Willkommenstext setzen
|
||||
welcomeMessage.textContent = "Willkommen zum Dashboard!";
|
||||
|
||||
// Rufe die Todos ab
|
||||
loadTodos();
|
||||
Reference in New Issue
Block a user