auth.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. "use strict";
  2. const emailInput = document.getElementById("login-email");
  3. const passwordInput = document.getElementById("login-password");
  4. const errorMessageParagraph = document.getElementById("login-error");
  5. const submitButtonLogin = document.getElementById("btn-login");
  6. const submitButtonRegister = document.getElementById("btn-register");
  7. window.addEventListener("load", function () {
  8. submitButtonLogin.addEventListener("click", async function () {
  9. await login();
  10. })
  11. submitButtonRegister.addEventListener("click", async function () {
  12. await register();
  13. })
  14. });
  15. async function sendAuthRequest(type) {
  16. console.log(emailInput.value);
  17. console.log(passwordInput.value);
  18. const response = await fetch(
  19. "/api/auth/" + type,
  20. {
  21. method: "POST",
  22. headers: {
  23. "Content-Type": "application/json", // Set the content type to JSON
  24. },
  25. body: JSON.stringify(
  26. {
  27. email: emailInput.value,
  28. password: passwordInput.value,
  29. }
  30. ),
  31. }
  32. )
  33. const response_json = await response.json();
  34. if (response.status === 200) {
  35. localStorage.setItem("token", response_json["token"]);
  36. window.location.replace("/html/appointments.html");
  37. } else {
  38. if (response_json["error"]) {
  39. errorMessageParagraph.innerText = response_json["error"];
  40. } else {
  41. errorMessageParagraph.innerText = response_json["message"];
  42. }
  43. }
  44. }
  45. async function login() {
  46. await sendAuthRequest("login");
  47. }
  48. async function register() {
  49. await sendAuthRequest("register");
  50. }