my-project-vue/server/server.js
2024-07-11 16:59:46 +08:00

72 lines
2.0 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 = 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;
const checkSql = 'SELECT * FROM users WHERE username = ?';
db.query(checkSql, [username], (err, results) => {
if (err) {
return res.json({ success: false, message: '注册失败' });
}
if (results.length > 0) {
return res.json({ success: false, message: '用户名已存在' });
}
const insertSql = 'INSERT INTO users (username, password) VALUES (?, ?)';
db.query(insertSql, [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://0.0.0.0:${port} 上运行`);
});