login.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // 使用相对路径,自动适配当前域名
  2. const API_BASE = "/api";
  3. // 检查是否已登录
  4. window.onload = () => {
  5. const token = localStorage.getItem("auth_token");
  6. if (token) {
  7. // 验证token是否有效
  8. verifyToken(token);
  9. }
  10. };
  11. // 验证token
  12. async function verifyToken(token) {
  13. try {
  14. const response = await fetch(`${API_BASE}/login`, {
  15. method: "POST",
  16. headers: {
  17. "Content-Type": "application/json"
  18. },
  19. body: JSON.stringify({ token: token })
  20. });
  21. const result = await response.json();
  22. if (result.code === 0) {
  23. // token有效,跳转到管理页面
  24. window.location.href = "/web/index.html";
  25. } else {
  26. // token无效,清除本地存储
  27. localStorage.removeItem("auth_token");
  28. }
  29. } catch (error) {
  30. // 网络错误,清除本地存储
  31. localStorage.removeItem("auth_token");
  32. }
  33. }
  34. // 处理登录
  35. async function handleLogin(event) {
  36. event.preventDefault();
  37. const tokenInput = document.getElementById("token");
  38. const token = tokenInput.value.trim();
  39. const loginBtn = document.getElementById("login-btn");
  40. const loading = document.getElementById("loading");
  41. const errorMsg = document.getElementById("error-message");
  42. if (!token) {
  43. showError("请输入 Token");
  44. return;
  45. }
  46. // 显示加载状态
  47. loginBtn.disabled = true;
  48. loading.classList.add("show");
  49. errorMsg.classList.remove("show");
  50. try {
  51. const response = await fetch(`${API_BASE}/login`, {
  52. method: "POST",
  53. headers: {
  54. "Content-Type": "application/json"
  55. },
  56. body: JSON.stringify({ token: token })
  57. });
  58. const result = await response.json();
  59. if (result.code === 0) {
  60. // 登录成功,保存token
  61. localStorage.setItem("auth_token", token);
  62. // 跳转到管理页面
  63. window.location.href = "/web/index.html";
  64. } else {
  65. showError(result.msg || "登录失败");
  66. }
  67. } catch (error) {
  68. showError("网络错误: " + error.message);
  69. } finally {
  70. loginBtn.disabled = false;
  71. loading.classList.remove("show");
  72. }
  73. }
  74. // 显示错误信息
  75. function showError(message) {
  76. const errorMsg = document.getElementById("error-message");
  77. errorMsg.textContent = message;
  78. errorMsg.classList.add("show");
  79. }