【问题标题】:Problem with async function not being called in javascriptjavascript中未调用异步函数的问题
【发布时间】:2022-01-20 17:14:44
【问题描述】:

我正在制作一个简单的登录功能,但在异步响应方面遇到了困难。似乎没有调用 html 文件中的函数。为什么? 它会将我发送到另一个页面,其中仅包含:{"status":"Not Found","data":"Incorrect Username and/or 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">
                <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>

问题似乎是上面的函数没有被调用。我真的很感谢你的帮助: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!' });
            }
        });
    }
});

【问题讨论】:

  • 您需要正文解析器但忘记使用它。
  • document.getElementById('login') 不存在
  • 你为什么不附加一个调试器并逐步调试它?
  • 我正在使用记事本++

标签: javascript html node.js


【解决方案1】:

这是一个更正的 sn-p。 @Quentin 已经指出 id "login" 丢失了。

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-25
    • 2020-04-20
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多