login.js 920 B

123456789101112131415161718192021222324252627282930313233343536
  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 res = await fetch("/api/auth/login", {
  15. method: "POST",
  16. headers: {
  17. "Content-Type": "application/json"
  18. },
  19. credentials: "include",
  20. body: JSON.stringify({ username, password })
  21. });
  22. const data = await res.json();
  23. if (data.success) {
  24. window.location.href = "/";
  25. } else {
  26. showMsg("用户名或密码错误");
  27. }
  28. }
  29. initLogin();