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

如何将MySQL数据库接入JavaScript实现账号密码登录验证?

实现基于MySQL的登录鉴权(含3次错误尝试限制)

一、后端实现(Node.js + Express + MySQL)

前端无法直接连接MySQL,必须通过服务端中转鉴权逻辑,以下是最简服务端实现:

1. 依赖安装

npm install express mysql2 body-parser cors

2. 后端核心代码(server.js)

const express = require('express');
const mysql = require('mysql2');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 3000;

// MySQL连接配置
const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'your_mysql_password',
  database: 'your_database_name'
});

// 连接数据库
db.connect(err => {
  if (err) throw err;
  console.log('已连接MySQL数据库');
});

// 中间件配置
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 登录验证接口
app.post('/api/login', (req, res) => {
  const { username, password } = req.body;
  
  // 查询数据库匹配账号密码
  const query = 'SELECT * FROM users WHERE username = ?';
  db.query(query, [username], (err, results) => {
    if (err) return res.status(500).json({ success: false, msg: '服务器异常' });
    
    if (results.length === 0) {
      return res.json({ success: false, msg: '用户名不存在' });
    }
    
    // 生产环境务必用bcrypt等工具校验加密密码,此处为简化示例用明文对比
    if (results[0].password === password) {
      res.json({ success: true, msg: '登录成功' });
    } else {
      res.json({ success: false, msg: '密码错误' });
    }
  });
});

app.listen(port, () => {
  console.log(`服务运行在 http://localhost:${port}`);
});

3. 数据库表结构

先创建存储用户信息的users表:

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(50) NOT NULL UNIQUE,
  password VARCHAR(255) NOT NULL -- 提示:生产环境存哈希值,不要明文
);

二、前端实现(带错误次数限制)

1. 登录页面HTML

<div class="login-container">
  <input type="text" id="username" placeholder="请输入用户名">
  <input type="password" id="password" placeholder="请输入密码">
  <button id="loginBtn">登录</button>
  <p id="tipText" style="color:red;"></p>
</div>

2. 前端JS逻辑

let attemptTimes = 0;
const MAX_ATTEMPTS = 3;

const loginBtn = document.getElementById('loginBtn');
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
const tipText = document.getElementById('tipText');

loginBtn.addEventListener('click', async () => {
  const username = usernameInput.value.trim();
  const password = passwordInput.value.trim();

  // 空值校验
  if (!username || !password) {
    tipText.textContent = '用户名和密码不能为空';
    return;
  }

  // 检查尝试次数是否耗尽
  if (attemptTimes >= MAX_ATTEMPTS) {
    tipText.textContent = '尝试次数过多,已锁定登录';
    return;
  }

  try {
    // 调用后端接口
    const res = await fetch('http://localhost:3000/api/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, password })
    });

    const data = await res.json();

    if (data.success) {
      alert('登录成功');
      window.location.href = '/home.html'; // 替换为你的首页路径
    } else {
      attemptTimes++;
      const remaining = MAX_ATTEMPTS - attemptTimes;
      tipText.textContent = `${data.msg},剩余${remaining}次尝试机会`;

      // 耗尽次数后禁用控件
      if (attemptTimes >= MAX_ATTEMPTS) {
        loginBtn.disabled = true;
        usernameInput.disabled = true;
        passwordInput.disabled = true;
      }
    }
  } catch (err) {
    tipText.textContent = '网络异常,请稍后重试';
  }
});

三、必看优化提示

  • 密码加密:生产环境绝对不能存明文密码,用bcrypt哈希后存储,后端验证时用bcrypt.compare()对比输入密码和数据库哈希值。
  • 跨域处理:示例中用了cors中间件解决跨域问题,上线时可配置更严格的跨域规则。
  • 安全加固:可添加IP锁定、登录失败延迟、验证码等机制,防止暴力破解。

内容的提问来源于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 07:15:56