修正前端端口
This commit is contained in:
@@ -1,46 +1,70 @@
|
||||
const { spawn } = require('child_process');
|
||||
const path = require('path');
|
||||
const express = require('express');
|
||||
|
||||
// 生产环境配置
|
||||
const PORT = process.env.PORT || 4001;
|
||||
const API_PORT = process.env.PORT || 4001;
|
||||
const FRONTEND_PORT = process.env.FRONTEND_PORT || 4002;
|
||||
const NODE_ENV = 'production';
|
||||
|
||||
// 设置环境变量
|
||||
process.env.NODE_ENV = NODE_ENV;
|
||||
process.env.PORT = PORT;
|
||||
process.env.PORT = API_PORT;
|
||||
|
||||
console.log(`启动生产环境服务器,端口: ${PORT}`);
|
||||
console.log(`启动生产环境服务器`);
|
||||
console.log(`后端API端口: ${API_PORT}`);
|
||||
console.log(`前端静态文件端口: ${FRONTEND_PORT}`);
|
||||
console.log(`工作目录: ${process.cwd()}`);
|
||||
|
||||
// 启动后端服务器
|
||||
const server = spawn('node', ['--import', 'tsx/esm', 'api/server.ts'], {
|
||||
// 启动前端静态文件服务
|
||||
const app = express();
|
||||
app.use(express.static(path.join(__dirname, 'dist')));
|
||||
app.get('*', (req, res) => {
|
||||
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
|
||||
});
|
||||
|
||||
const frontendServer = app.listen(FRONTEND_PORT, () => {
|
||||
console.log(`前端静态文件服务已启动,端口: ${FRONTEND_PORT}`);
|
||||
});
|
||||
|
||||
// 启动后端API服务器
|
||||
const apiServer = spawn('node', ['--import', 'tsx/esm', 'api/server.ts'], {
|
||||
stdio: 'inherit',
|
||||
env: {
|
||||
...process.env,
|
||||
NODE_ENV: NODE_ENV,
|
||||
PORT: PORT
|
||||
PORT: API_PORT
|
||||
}
|
||||
});
|
||||
|
||||
// 处理进程退出
|
||||
server.on('close', (code) => {
|
||||
console.log(`服务器进程退出,退出码: ${code}`);
|
||||
// 处理API服务器进程退出
|
||||
apiServer.on('close', (code) => {
|
||||
console.log(`API服务器进程退出,退出码: ${code}`);
|
||||
frontendServer.close();
|
||||
process.exit(code);
|
||||
});
|
||||
|
||||
// 处理错误
|
||||
server.on('error', (err) => {
|
||||
console.error('启动服务器时发生错误:', err);
|
||||
// 处理API服务器错误
|
||||
apiServer.on('error', (err) => {
|
||||
console.error('启动API服务器时发生错误:', err);
|
||||
frontendServer.close();
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
// 优雅关闭
|
||||
process.on('SIGINT', () => {
|
||||
console.log('\n收到 SIGINT 信号,正在关闭服务器...');
|
||||
server.kill('SIGINT');
|
||||
frontendServer.close();
|
||||
apiServer.kill('SIGINT');
|
||||
});
|
||||
|
||||
process.on('SIGTERM', () => {
|
||||
console.log('\n收到 SIGTERM 信号,正在关闭服务器...');
|
||||
server.kill('SIGTERM');
|
||||
frontendServer.close();
|
||||
apiServer.kill('SIGTERM');
|
||||
});
|
||||
|
||||
// 处理前端服务器错误
|
||||
frontendServer.on('error', (err) => {
|
||||
console.error('前端静态文件服务器错误:', err);
|
||||
});
|
||||
Reference in New Issue
Block a user