You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过if else语句调用MySQL账号密码实现登录验证与次数限制

实现基于MySQL的登录验证逻辑修改

要实现从MySQL数据库验证用户名密码,前端无法直接连接MySQL,必须通过后端接口完成数据库查询。以下是完整的修改方案:

一、前端代码修改

将原有的硬编码判断替换为异步请求后端接口的逻辑,修改后的代码如下:

var attempt = 3;

async function userLogin() {
    var username = document.getElementById("username").value.trim();
    var password = document.getElementById("password1").value.trim();
    
    if (username === "" || password === "") {
        alert("Please complete the required field!");
        return;
    }

    try {
        // 发送请求到后端登录接口
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ username, password })
        });

        const result = await response.json();

        if (result.success) {
            alert("Login successfully");
            // 可在此添加登录成功后的跳转、状态存储等逻辑
        } else {
            // 验证失败,执行次数扣减逻辑
            attempt--;
            document.getElementById("msg").innerHTML = "<center class='text-danger'>Invalid username or password</center>";
            alert(`You have left ${attempt} login attempt(s)`);
            
            if (attempt === 0) {
                document.getElementById("username").disabled = true;
                document.getElementById("password1").disabled = true;
                document.getElementById("login").disabled = true;
                document.getElementById("reset").style.display = "inline";
            }
        }
    } catch (error) {
        alert("Login failed due to server error");
        console.error(error);
    }
}

前端修改说明:

  • 新增async/await处理异步接口请求
  • 对用户名、密码做trim()处理,避免空格干扰验证
  • 移除原有的硬编码判断,改为根据后端返回的验证结果执行对应逻辑
  • 增加异常捕获,处理服务器错误情况

二、后端接口实现(Node.js+Express+MySQL示例)

前端请求需要对应的后端接口来完成数据库查询,以下是基于Node.js的实现方案:

1. 安装依赖

执行命令安装所需包:

npm install express mysql2 bcrypt

2. 后端代码

const express = require('express');
const mysql = require('mysql2/promise');
const bcrypt = require('bcrypt');
const app = express();

// 解析JSON格式的请求体
app.use(express.json());

// MySQL数据库连接配置,请替换为你的实际信息
const dbConfig = {
    host: 'localhost',
    user: '你的数据库用户名',
    password: '你的数据库密码',
    database: '你的数据库名'
};

// 登录验证接口
app.post('/api/login', async (req, res) => {
    const { username, password } = req.body;

    try {
        // 建立数据库连接
        const connection = await mysql.createConnection(dbConfig);
        
        // 查询用户表(假设表名为users,存储哈希后的密码)
        const [rows] = await connection.execute(
            'SELECT hashed_password FROM users WHERE username = ?',
            [username]
        );
        await connection.end();

        if (rows.length === 0) {
            // 用户名不存在
            return res.json({ success: false });
        }

        // 验证密码(数据库存储的是哈希值,需用bcrypt对比)
        const isPasswordValid = await bcrypt.compare(password, rows[0].hashed_password);
        
        res.json({ success: isPasswordValid });
    } catch (error) {
        console.error('数据库查询错误:', error);
        res.status(500).json({ success: false });
    }
});

// 启动服务器
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
});

后端关键说明:

  • 禁止明文存储密码:必须用bcrypt对密码进行哈希处理后再存入数据库,注册用户时的哈希示例:
    const hashedPassword = await bcrypt.hash('用户输入的明文密码', 10);
    // 将username和hashedPassword插入users表
    
  • 用户表结构示例(需提前创建):
    CREATE TABLE users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(50) UNIQUE NOT NULL,
        hashed_password VARCHAR(255) NOT NULL
    );
    
  • 需替换dbConfig中的数据库连接信息为你的实际配置

内容的提问来源于stack exchange,提问作者Christlyn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 13:26:01