Logging In and out in handlebars

PHOTO EMBED

Thu Sep 22 2022 22:05:03 GMT+0000 (UTC)

Saved by @zaccamp #javascript #handlebars #html

// Javascript
async function signupFormHandler(event) {
  event.preventDefault();
  const username = document.querySelector('#username-signup').value.trim();
  const email = document.querySelector('#email-signup').value.trim();
  const password = document.querySelector('#password-signup').value.trim();
  if (username && email && password) {
    const response = await fetch('/api/users', {
      method: 'post',
      body: JSON.stringify({
        username,
        email,
        password,
      }),
      headers: { 'Content-Type': 'application/json' },
    });
    if (response.ok) {
      console.log(response);
    } else {
      alert(response.statusText);
    }
  }
}
async function loginFormHandler(event) {
  event.preventDefault();
  const email = document.querySelector('#email-signup').value.trim();
  const password = document.querySelector('#password-signup').value.trim();
  if (email && password) {
    const response = await fetch('/api/users/login', {
      method: 'post',
      body: JSON.stringify({
        email,
        password,
      }),
      headers: { 'Content-Type': 'application/json' },
    });
    if (response.ok) {
      document.location.replace('/')
    } else {
      alert(response.statusText);
    }
  }
}
document.querySelector('.signup-form').addEventListener('submit', signupFormHandler);
document.querySelector('.login-form').addEventListener('submit', loginFormHandler);


<!-- HTML -->

<form class='login-form'>
  <div>
    <label for='email-login'>email:</label>
    <input type='text' id='email-login' />
  </div>
  <div>
    <label for='password-login'>password:</label>
    <input type='text' id='password-login' />
  </div>
  <div>
    <button type='submit'>login</button>
  </div>
</form>
<form class='signup-form'>
  <div>
    <label for='username-signup'>username:</label>
    <input type='text' id='username-signup' />
  </div>
  <div>
    <label for='email-signup'>email:</label>
    <input type='text' id='email-signup' />
  </div>
  <div>
    <label for='password-signup'>password:</label>
    <input type='text' id='password-signup' />
  </div>
  <div>
    <button type='submit'>login</button>
  </div>
</form>
<script src="/javascript/login.js"></script>
content_copyCOPY