0

I am making a simple login function, but face difficulty with the async response. The function in the html file doesn't seem to be called. Why? It sends me to another page containing just: {"status":"Not Found","data":"Incorrect Username and/or Password!"} It should also open a dialog box

<body class="hero-image">

<div id="container">
    <div id="tabs">

       <p id="lt" class="tabs">Log in</p>
        <p id="rt" class="tabs" onclick="location.href = './register';">Register</p>

        <div id="clear"></div>
    </div>
    <div id="cont">
        <div id="loginBox" class="comm">
            <h3>Sign in</h3>
            <form action="/api/login" method="POST">
                <input id="username" type="text" autocomplete="off" name="username" placeholder="Username" required>
                <input id="password" type="password" autocomplete="off" name="password" placeholder="Password" required>
                <input type="submit" value="Submit Form">
            </form>
        </div>
    </div>
</div>
<script>
        const form = document.getElementById('login')
        form.addEventListener('submit', login)

        async function login(event) {
            alert('Success')
            event.preventDefault()
            const username = document.getElementById('username').value
            const password = document.getElementById('password').value
            
            
            
            const result = await fetch('/api/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username,
                    password
                })
            }).then((res) => res.json())

            if (result.status === 'ok') {
                // everything went fine
                console.log('Got the token: ', result.data)
                localStorage.setItem('token', result.data)
                alert('Success')
            } else {
                if (result.status === 'Not Found') {
                    alert("Incorrect Username and/or Password!");
                }
                else {
                    alert("Please enter Username and Password!");
                }
            }
        }
    </script>

The problem seems to be that the function above doesn't get called. I would really really appreciate your help :D

var mysql = require('mysql');
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var path = require('path')
const jwt = require('jsonwebtoken')

app.post('/api/login', async (req, res) => {
    var dialog = require('dialog');
    const { username, password } = req.body;
    if (!username) {
        return res.json({ status: 'Not Found', data: 'Invalid username/password' });
    }
    if (username && password) {
        connection.query('SELECT * FROM users WHERE username = ? AND password = ?', [username, password], function(error, results, fields) {
            if (results.length > 0) {
                return res.json({ status: 'ok', data: username });
            } else {
                return res.json({ status: 'Not Found', data: 'Incorrect Username and/or Password!' });
            }
        });
    }
});
4
  • 1
    You required body parser but forgot to use it. Commented Jan 20, 2022 at 9:05
  • 2
    document.getElementById('login') doesn’t exist Commented Jan 20, 2022 at 9:06
  • Why don't you just attch a debugger and step though it? Commented Jan 20, 2022 at 9:13
  • I'm using notepad++ Commented Jan 20, 2022 at 9:38

1 Answer 1

2

Here is a corrected snippet. @Quentin already pointed out that the id "login" was missing.

const form = document.getElementById('login')
form.addEventListener('submit', login)

async function login(event) {
  console.log('logging in ...')
  event.preventDefault()
  const username = document.getElementById('username').value
  const password = document.getElementById('password').value

  const url='https://jsonplaceholder.typicode.com/users/'; // '/api/login'
  const result = await fetch(url, { 
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      username,
      password
    })
  }).then((res) => res.json())

  if (result.status !== 'ok') {
    // everything went fine
    console.log('Got the token: ', result)
    // localStorage.setItem('token', result.id)
    alert('Success')
  } else {
    if (result.status === 'Not Found') {
      alert("Incorrect Username and/or Password!");
    } else {
      alert("Please enter Username and Password!");
    }
  }
}
<body class="hero-image">
  <div id="container">
    <div id="tabs">
      <p id="lt" class="tabs">Log in</p>
      <p id="rt" class="tabs" onclick="location.href = './register';">Register</p>

      <div id="clear"></div>
    </div>
    <div id="cont">
      <div id="loginBox" class="comm">
        <h3>Sign in</h3>
        <form action="/api/login" method="POST" id="login">
          <input id="username" type="text" autocomplete="off" name="username" placeholder="Username" required>
          <input id="password" type="password" autocomplete="off" name="password" placeholder="Password" required>
          <input type="submit" value="Submit Form">
        </form>
      </div>
    </div>
  </div>
</body>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.