login.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. function initLogin() {
  2. const form = document.getElementById("loginForm");
  3. form.addEventListener("submit", loginHandler);
  4. }
  5. function showMsg(text, isError = true) {
  6. const msg = document.getElementById("msg");
  7. msg.innerText = text;
  8. msg.style.color = isError ? "red" : "green";
  9. }
  10. async function loginHandler(e) {
  11. e.preventDefault();
  12. const username = document.getElementById("username")?.value || "";
  13. const password = document.getElementById("password")?.value || "";
  14. const btn = document.getElementById("loginBtn");
  15. btn.disabled = true;
  16. btn.innerText = "登录中...";
  17. try {
  18. const res = await fetch("/api/auth/login", {
  19. method:"POST",
  20. headers:{
  21. "Content-Type":"application/json"
  22. },
  23. credentials:"include",
  24. body:JSON.stringify({username,password})
  25. });
  26. const data = await res.json();
  27. if (data.success) {
  28. window.location.href = "/";
  29. return;
  30. }
  31. showMsg("用户名或密码错误");
  32. } catch (err) {
  33. showMsg("登录请求失败,请检查网络");
  34. } finally {
  35. btn.disabled = false;
  36. btn.innerText = "登录";
  37. }
  38. }
  39. initLogin();