login.js 1.4 KB

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