const express = require('express'); const mysql = require('mysql'); const bodyParser = require('body-parser'); const cors = require('cors'); const path = require('path'); const app = express(); const port = 4040; app.use(bodyParser.json()); app.use(cors()); // 创建 MySQL 连接 const db = mysql.createConnection({ host: '172.17.0.1', user: 'login_test', password: 'tTiwnNbzMeLFxbLj', database: 'login_test' }); db.connect(err => { if (err) { console.error('无法连接到数据库:', err); return; } console.log('已连接到数据库'); }); // 处理注册请求 app.post('/api/register', (req, res) => { const { username, password } = req.body; // 检查用户名和密码是否为空 if (!username || !password) { return res.json({ success: false, message: '用户名和密码不能为空' }); } const checkUserSql = 'SELECT * FROM users WHERE username = ?'; const registerSql = 'INSERT INTO users (username, password) VALUES (?, ?)'; db.query(checkUserSql, [username], (err, results) => { if (err) { return res.json({ success: false, message: '数据库查询失败' }); } if (results.length > 0) { return res.json({ success: false, message: '用户名已存在' }); } db.query(registerSql, [username, password], (err, result) => { if (err) { return res.json({ success: false, message: '注册失败' }); } res.json({ success: true, message: '注册成功' }); }); }); }); // 处理登录请求 app.post('/api/login', (req, res) => { const { username, password } = req.body; // 检查用户名和密码是否为空 if (!username || !password) { return res.json({ success: false, message: '用户名和密码不能为空' }); } const sql = 'SELECT * FROM users WHERE username = ? AND password = ?'; db.query(sql, [username, password], (err, results) => { if (err || results.length === 0) { return res.json({ success: false, message: '登录失败' }); } res.json({ success: true, message: '登录成功' }); }); }); // 提供静态文件服务 app.use(express.static(path.join(__dirname, 'public'))); // 所有其他请求返回 index.html app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); app.listen(port, () => { console.log(`服务器在 http://localhost:${port} 上运行`); });