63 lines
1.7 KiB
JavaScript
63 lines
1.7 KiB
JavaScript
|
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 = 3000;
|
||
|
|
||
|
app.use(bodyParser.json());
|
||
|
app.use(cors());
|
||
|
|
||
|
// 创建 MySQL 连接
|
||
|
const db = mysql.createConnection({
|
||
|
host: '1.14.200.189',
|
||
|
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;
|
||
|
const sql = 'INSERT INTO users (username, password) VALUES (?, ?)';
|
||
|
db.query(sql, [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;
|
||
|
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, '../dist')));
|
||
|
|
||
|
// 所有其他请求返回 index.html
|
||
|
app.get('*', (req, res) => {
|
||
|
res.sendFile(path.join(__dirname, '../dist', 'index.html'));
|
||
|
});
|
||
|
|
||
|
app.listen(port, () => {
|
||
|
console.log(`服务器在 http://localhost:${port} 上运行`);
|
||
|
});
|