// 使用相对路径,自动适配当前域名 const API_BASE = "/api"; // 检查是否已登录 window.onload = () => { const token = localStorage.getItem("auth_token"); if (token) { // 验证token是否有效 verifyToken(token); } }; // 验证token async function verifyToken(token) { try { const response = await fetch(`${API_BASE}/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token: token }) }); const result = await response.json(); if (result.code === 0) { // token有效,跳转到管理页面 window.location.href = "/web/index.html"; } else { // token无效,清除本地存储 localStorage.removeItem("auth_token"); } } catch (error) { // 网络错误,清除本地存储 localStorage.removeItem("auth_token"); } } // 处理登录 async function handleLogin(event) { event.preventDefault(); const tokenInput = document.getElementById("token"); const token = tokenInput.value.trim(); const loginBtn = document.getElementById("login-btn"); const loading = document.getElementById("loading"); const errorMsg = document.getElementById("error-message"); if (!token) { showError("请输入 Token"); return; } // 显示加载状态 loginBtn.disabled = true; loading.classList.add("show"); errorMsg.classList.remove("show"); try { const response = await fetch(`${API_BASE}/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token: token }) }); const result = await response.json(); if (result.code === 0) { // 登录成功,保存token localStorage.setItem("auth_token", token); // 跳转到管理页面 window.location.href = "/web/index.html"; } else { showError(result.msg || "登录失败"); } } catch (error) { showError("网络错误: " + error.message); } finally { loginBtn.disabled = false; loading.classList.remove("show"); } } // 显示错误信息 function showError(message) { const errorMsg = document.getElementById("error-message"); errorMsg.textContent = message; errorMsg.classList.add("show"); }