66 lines
2.0 KiB
JavaScript
66 lines
2.0 KiB
JavaScript
const express = require('express');
|
|
const path = require('path');
|
|
const compression = require('compression');
|
|
const helmet = require('helmet');
|
|
const { createProxyMiddleware } = require('http-proxy-middleware');
|
|
|
|
const app = express();
|
|
const PORT = process.env.PORT || 3000;
|
|
|
|
// 安全中间件
|
|
app.use(helmet({
|
|
contentSecurityPolicy: false, // 允许内联脚本和样式
|
|
}));
|
|
|
|
// 压缩中间件
|
|
app.use(compression());
|
|
|
|
// API 代理中间件 - 将 /api/* 请求代理到 10.100.5.86:8113
|
|
app.use('/api', createProxyMiddleware({
|
|
target: 'http://10.100.51.86:8113',
|
|
changeOrigin: true,
|
|
pathRewrite: {
|
|
'^/api': '/api', // 保持 /api 路径
|
|
},
|
|
onProxyReq: (proxyReq, req, res) => {
|
|
console.log(`🔄 代理请求: ${req.method} ${req.url} -> http://10.100.51.86:8113${req.url}`);
|
|
},
|
|
onProxyRes: (proxyRes, req, res) => {
|
|
console.log(`✅ 代理响应: ${req.method} ${req.url} - 状态码: ${proxyRes.statusCode}`);
|
|
},
|
|
onError: (err, req, res) => {
|
|
console.error(`❌ 代理错误: ${req.method} ${req.url}`, err.message);
|
|
res.status(500).json({ error: '代理请求失败', message: err.message });
|
|
}
|
|
}));
|
|
|
|
// 静态文件服务
|
|
app.use(express.static(path.join(__dirname, 'dist')));
|
|
|
|
// 处理 SPA 路由,所有未匹配的路由都返回 index.html
|
|
app.get('*', (req, res) => {
|
|
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
|
|
});
|
|
|
|
// 错误处理中间件
|
|
app.use((err, req, res, next) => {
|
|
console.error('服务器错误:', err.stack);
|
|
res.status(500).send('服务器内部错误');
|
|
});
|
|
|
|
app.listen(PORT, () => {
|
|
console.log(`🚀 VDI 管理平台服务器已启动`);
|
|
console.log(`📍 访问地址: http://localhost:${PORT}`);
|
|
console.log(`⏰ 启动时间: ${new Date().toLocaleString()}`);
|
|
});
|
|
|
|
// 优雅关闭
|
|
process.on('SIGTERM', () => {
|
|
console.log('收到 SIGTERM 信号,正在关闭服务器...');
|
|
process.exit(0);
|
|
});
|
|
|
|
process.on('SIGINT', () => {
|
|
console.log('收到 SIGINT 信号,正在关闭服务器...');
|
|
process.exit(0);
|
|
}); |