Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get form response to show on page #34

Open
i2xzy opened this issue Apr 9, 2018 · 0 comments
Open

Get form response to show on page #34

i2xzy opened this issue Apr 9, 2018 · 0 comments

Comments

@i2xzy
Copy link

i2xzy commented Apr 9, 2018

Based off ws-cookies from Week 7 Day 1

changes to index.html:

    <form action="/auth_check" method="GET" class="js-auth">
      <button type="submit">Am I authenticated?</button>
    </form>
  </main>
  <script src='./index.js'></script>

index.js:

var auth = document.querySelector('.js-auth');

auth.addEventListener('submit', function(e) {
  e.preventDefault();
  var xhr = new XMLHttpRequest();

  xhr.addEventListener('load', function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log('fetch is working');
      var response = JSON.parse(xhr.responseText);
      var message = document.createElement('span');
      response
        ? (message.textContent = 'Logged In')
        : (message.textContent = 'Unauthorised');
      auth.appendChild(message);
    } else {
      console.log('fetch error');
    }
  });
  xhr.open('GET', '/auth_check', true);
  xhr.send();
});

changes to router.js:

case 'GET /auth_check':
      if (req.headers.cookie === 'logged_in=true') {
        res.writeHead(200, {
          'Content-Type': 'application/javascript'
        });
        res.end('true');
      } else {
        res.writeHead(200, {
          'Content-Type': 'application/javascript'
        });
        res.end('false');
      }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant