chore: 基本服务器版本完成

This commit is contained in:
2025-11-12 08:23:41 +08:00
parent 22016ac339
commit 58ad47d124
9 changed files with 2084 additions and 490 deletions

77
server.js Normal file
View File

@@ -0,0 +1,77 @@
import express from 'express';
import cors from 'cors';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = 3000;
const CONFIG_FILE_PATH = path.join(__dirname, 'data', 'config.json');
// 中间件
app.use(cors());
app.use(express.json());
// 静态文件服务Vue应用
app.use(express.static(path.join(__dirname, 'dist')));
// API: 获取配置数据
app.get('/api/config', (req, res) => {
try {
const configData = fs.readFileSync(CONFIG_FILE_PATH, 'utf8');
res.json(JSON.parse(configData));
} catch (error) {
console.error('读取配置文件失败:', error);
res.status(500).json({ error: '读取配置文件失败' });
}
});
// API: 保存配置数据
app.post('/api/config', (req, res) => {
try {
fs.writeFileSync(CONFIG_FILE_PATH, JSON.stringify(req.body, null, 2), 'utf8');
res.json({ success: true });
} catch (error) {
console.error('保存配置文件失败:', error);
res.status(500).json({ error: '保存配置文件失败' });
}
});
// 处理Vue Router历史模式 - 使用正则表达式代替通配符
app.get(/^((?!\/api).)*$/, (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
// 启动服务器并监听错误
const server = app.listen(PORT, () => {
console.log(`服务器运行在 http://localhost:${PORT}`);
console.log('服务器已成功启动,可以访问 http://localhost:3000');
console.log('API端点: GET/POST /api/config');
});
// 监听服务器错误
server.on('error', (error) => {
console.error('服务器错误:', error);
if (error.code === 'EADDRINUSE') {
console.error(`端口 ${PORT} 已被占用,请尝试其他端口。`);
}
});
// 监听SIGINT信号Ctrl+C
process.on('SIGINT', () => {
console.log('正在关闭服务器...');
server.close(() => {
console.log('服务器已关闭');
process.exit(0);
});
});
// 确保服务器持续运行
setInterval(() => {
// 保持服务器活动的空操作
}, 60000); // 每分钟执行一次