forked from woleigedouer/cookie-butler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev-server.js
More file actions
133 lines (116 loc) · 4.25 KB
/
dev-server.js
File metadata and controls
133 lines (116 loc) · 4.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import { readFileSync } from 'fs';
// ES模块中获取__dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 3000;
// 中间件配置
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// CORS配置 - 仅在开发环境使用,生产环境由API路由自己处理
if (process.env.NODE_ENV !== 'production') {
app.use((req, res, next) => {
// 开发环境的CORS配置
const allowedOrigins = [
'http://localhost:3000',
'http://127.0.0.1:3000',
'http://localhost:8080', // 可能的其他开发端口
'http://127.0.0.1:8080'
];
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.header('Access-Control-Allow-Origin', origin);
} else {
// 开发环境默认允许localhost
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
}
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
res.header('Access-Control-Allow-Credentials', 'false');
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
});
console.log('🔧 开发环境CORS中间件已启用');
} else {
console.log('🔒 生产环境:CORS由API路由自行处理');
}
// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));
// 动态导入API路由处理器
async function loadApiHandler(modulePath) {
try {
const module = await import(modulePath);
return module.default;
} catch (error) {
console.error(`加载API模块失败: ${modulePath}`, error);
return null;
}
}
// API路由 - 二维码生成
app.post('/api/qrcode', async (req, res) => {
try {
const handler = await loadApiHandler('./api/qrcode.js');
if (handler) {
await handler(req, res);
} else {
res.status(500).json({ success: false, message: '无法加载二维码API' });
}
} catch (error) {
console.error('二维码API错误:', error);
res.status(500).json({ success: false, message: '服务器内部错误' });
}
});
// API路由 - 状态检查
app.post('/api/check-status', async (req, res) => {
try {
const handler = await loadApiHandler('./api/check-status.js');
if (handler) {
await handler(req, res);
} else {
res.status(500).json({ success: false, message: '无法加载状态检查API' });
}
} catch (error) {
console.error('状态检查API错误:', error);
res.status(500).json({ success: false, message: '服务器内部错误' });
}
});
// 处理所有其他路由,返回index.html(SPA支持)
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// 错误处理中间件
app.use((error, req, res, next) => {
console.error('服务器错误:', error);
res.status(500).json({
success: false,
message: '服务器内部错误',
error: process.env.NODE_ENV === 'development' ? error.message : undefined
});
});
// 启动服务器
app.listen(PORT, () => {
console.log(`🚀 Cookie Butler 开发服务器启动成功!`);
console.log(`📱 访问地址: http://localhost:${PORT}`);
console.log(`🔧 环境: ${process.env.NODE_ENV || 'development'}`);
console.log(`⏰ 启动时间: ${new Date().toLocaleString()}`);
console.log('');
console.log('💡 提示:');
console.log(' - 修改代码后需要重启服务器');
console.log(' - 推荐使用 "vercel dev" 获得热重载和完整功能');
console.log(' - 按 Ctrl+C 停止服务器');
});
// 优雅关闭
process.on('SIGINT', () => {
console.log('\n🛑 正在关闭服务器...');
process.exit(0);
});
process.on('SIGTERM', () => {
console.log('\n🛑 收到终止信号,正在关闭服务器...');
process.exit(0);
});