82 lines
1.9 KiB
JavaScript
82 lines
1.9 KiB
JavaScript
import express from 'express';
|
|
import cors from 'cors';
|
|
import helmet from 'helmet';
|
|
import dotenv from 'dotenv';
|
|
import { fileURLToPath } from 'url';
|
|
import { dirname, join } from 'path';
|
|
|
|
// 加载环境变量
|
|
dotenv.config({ path: join(dirname(fileURLToPath(import.meta.url)), '.env') });
|
|
|
|
import authRoutes from './routes/auth.js';
|
|
import adminRoutes from './routes/admin.js';
|
|
import { apiLimiter } from './middleware/rateLimit.js';
|
|
import { initDatabase } from './database.js';
|
|
|
|
const app = express();
|
|
const PORT = process.env.PORT || 3001;
|
|
|
|
// ── 安全中间件 ──
|
|
app.use(helmet({
|
|
crossOriginResourcePolicy: { policy: 'cross-origin' }
|
|
}));
|
|
|
|
// CORS 配置
|
|
app.use(cors({
|
|
origin: true, // 开发环境允许所有来源
|
|
credentials: true
|
|
}));
|
|
|
|
// JSON 解析
|
|
app.use(express.json());
|
|
|
|
// ── API 路由 ──
|
|
app.use('/api/auth', authRoutes);
|
|
app.use('/api/admin', adminRoutes);
|
|
|
|
// API 速率限制
|
|
app.use('/api', apiLimiter);
|
|
|
|
// ── 健康检查 ──
|
|
app.get('/api/health', (req, res) => {
|
|
res.json({
|
|
status: 'ok',
|
|
timestamp: new Date().toISOString(),
|
|
version: '1.0.0'
|
|
});
|
|
});
|
|
|
|
// ── 错误处理 ──
|
|
app.use((err, req, res, next) => {
|
|
console.error('[Error]', err);
|
|
res.status(500).json({
|
|
error: '服务器内部错误',
|
|
message: process.env.NODE_ENV === 'development' ? err.message : undefined
|
|
});
|
|
});
|
|
|
|
// 404 处理
|
|
app.use((req, res) => {
|
|
res.status(404).json({ error: '接口不存在' });
|
|
});
|
|
|
|
// ── 启动服务 ──
|
|
async function start() {
|
|
try {
|
|
// 初始化数据库
|
|
await initDatabase();
|
|
console.log('[DB] 数据库初始化完成');
|
|
|
|
// 启动服务器
|
|
app.listen(PORT, () => {
|
|
console.log(`[Server] 认证服务已启动: http://localhost:${PORT}`);
|
|
console.log(`[Server] 环境: ${process.env.NODE_ENV || 'development'}`);
|
|
});
|
|
} catch (error) {
|
|
console.error('[Server] 启动失败:', error);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
start();
|