Advertisement
didkoslawow

Untitled

Jun 30th, 2023
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. document.querySelectorAll('a').forEach(x => x.classList.remove('active'));
  2.  document.getElementById('login').classList.add('active');
  3.  document.getElementById('logout').style.display = 'none';
  4.  
  5.  window.addEventListener('DOMContentLoaded', () => {
  6.      document.querySelector('form').addEventListener('submit', onLogin);
  7.  });
  8.  
  9.  
  10.  async function onLogin(e) {
  11.      e.preventDefault();
  12.      const formData = new FormData(e.target);
  13.  
  14.      const email = formData.get('email');
  15.      const password = formData.get('password');
  16.  
  17.      try {
  18.          if (email == '') {
  19.              throw new Error('Email is required');
  20.          }
  21.          if (password == '') {
  22.              throw new Error('Password is required');
  23.          }
  24.  
  25.  
  26.          const response = await fetch('http://localhost:3030/users/login/', {
  27.              method: 'post',
  28.              headers: {
  29.                  'Content-Type': 'application/json',
  30.              },
  31.              body: JSON.stringify({ email, password }),
  32.          });
  33.  
  34.          if (response.ok != true) {
  35.              const error = await response.json();
  36.              throw new Error(error.message);
  37.          }
  38.  
  39.          const data = await response.json();
  40.          const userData = {
  41.              id: data._id,
  42.              email: data.email,
  43.              token: data.accessToken,
  44.          }
  45.  
  46.          sessionStorage.setItem('userData', JSON.stringify(userData));
  47.          window.location = 'index.html';
  48.  
  49.      } catch (error) {
  50.          alert(error.message)
  51.      }
  52.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement