Initial commit

This commit is contained in:
2026-02-06 14:29:29 +08:00
commit e98dbcb0f4
11 changed files with 2574 additions and 0 deletions

75
server.js Normal file
View File

@@ -0,0 +1,75 @@
require('dotenv').config({ path: __dirname + '/.env' });
const express = require('express');
const cors = require('cors');
const path = require('path');
// 导入路由
const authRoutes = require('./routes/auth');
const serialRoutes = require('./routes/serials');
const companyRoutes = require('./routes/companies');
const app = express();
const PORT = process.env.PORT || 3000;
// 中间件
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));
// 设置响应编码
app.use((req, res, next) => {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
next();
});
// API路由必须在静态文件服务之前
app.use('/api/auth', authRoutes);
app.use('/api/serials', serialRoutes);
app.use('/api/companies', companyRoutes);
// 健康检查
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', message: '服务器运行正常' });
});
// 静态文件服务
const frontendPath = path.join(__dirname, '..', 'frontend');
const distPath = path.join(frontendPath, 'dist');
const publicPath = path.join(frontendPath, 'public');
if (process.env.NODE_ENV === 'production') {
app.use(express.static(distPath));
} else {
app.use(express.static(publicPath));
}
// 404处理
app.use((req, res) => {
if (req.path.startsWith('/api/')) {
res.status(404).json({ error: 'API接口不存在' });
} else {
// 对于非API请求返回index.html用于React Router
if (process.env.NODE_ENV === 'production') {
res.sendFile(path.join(distPath, 'index.html'));
} else {
res.sendFile(path.join(publicPath, 'index.html'));
}
}
});
// 错误处理中间件
app.use((error, req, res, next) => {
console.error('服务器错误:', error);
if (req.path.startsWith('/api/')) {
res.status(500).json({ error: '服务器内部错误' });
} else {
res.status(500).send('服务器内部错误');
}
});
// 启动服务器
app.listen(PORT, () => {
console.log(`服务器运行在 http://localhost:${PORT}`);
console.log(`API文档: http://localhost:${PORT}/api/health`);
console.log(`环境: ${process.env.NODE_ENV || 'development'}`);
});