function initLogin() { const form = document.getElementById("loginForm"); form.addEventListener("submit", loginHandler); } function showMsg(text, isError = true) { const msg = document.getElementById("msg"); msg.innerText = text; msg.style.color = isError ? "red" : "green"; } async function loginHandler(e) { e.preventDefault(); const username = document.getElementById("username")?.value || ""; const password = document.getElementById("password")?.value || ""; const btn = document.getElementById("loginBtn"); btn.disabled = true; btn.innerText = "登录中..."; try { const res = await fetch("/api/auth/login", { method:"POST", headers:{ "Content-Type":"application/json" }, credentials:"include", body:JSON.stringify({username,password}) }); const data = await res.json(); if (data.success) { window.location.href = "/"; return; } showMsg("用户名或密码错误"); } catch (err) { showMsg("登录请求失败,请检查网络"); } finally { btn.disabled = false; btn.innerText = "登录"; } } initLogin();