quanyoumi/backend/server.js

54 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');
const app = express();
// 中间件
app.use(cors());
app.use(express.json());
// 静态文件服务 - 提供上传的文件
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// API 路由
app.use('/api', require('./routes/activity'));
app.use('/api', require('./routes/registration'));
app.use('/api/admin', require('./routes/admin'));
// 生产环境下提供前端静态文件
if (process.env.NODE_ENV === 'production') {
// 静态文件目录
app.use(express.static(path.join(__dirname, 'public')));
// 所有其他请求返回 index.html支持前端路由
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
}
const PORT = process.env.PORT || 3000;
// 启动服务器前运行数据库迁移
const MigrationManager = require('./migrations/index');
const runMigrations = async () => {
try {
const manager = new MigrationManager();
await manager.runMigrations();
} catch (error) {
console.error('数据库迁移失败,但服务器将继续启动');
}
};
runMigrations().then(() => {
app.listen(PORT, () => {
console.log(`服务器运行在 http://localhost:${PORT}`);
if (process.env.NODE_ENV === 'production') {
console.log('运行模式: 生产环境(前后端一体)');
} else {
console.log('运行模式: 开发环境仅后端API');
}
});
});