Files
backend-node/server.js
2026-02-06 14:29:29 +08:00

75 lines
2.1 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({ path: __dirname + '/.env' });
const express = require('express');
const cors = require('cors');
const path = require('path');
// 导入路由
const authRoutes = require('./routes/auth');
const serialRoutes = require('./routes/serials');
const companyRoutes = require('./routes/companies');
const app = express();
const PORT = process.env.PORT || 3000;
// 中间件
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));
// 设置响应编码
app.use((req, res, next) => {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
next();
});
// API路由必须在静态文件服务之前
app.use('/api/auth', authRoutes);
app.use('/api/serials', serialRoutes);
app.use('/api/companies', companyRoutes);
// 健康检查
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', message: '服务器运行正常' });
});
// 静态文件服务
const frontendPath = path.join(__dirname, '..', 'frontend');
const distPath = path.join(frontendPath, 'dist');
const publicPath = path.join(frontendPath, 'public');
if (process.env.NODE_ENV === 'production') {
app.use(express.static(distPath));
} else {
app.use(express.static(publicPath));
}
// 404处理
app.use((req, res) => {
if (req.path.startsWith('/api/')) {
res.status(404).json({ error: 'API接口不存在' });
} else {
// 对于非API请求返回index.html用于React Router
if (process.env.NODE_ENV === 'production') {
res.sendFile(path.join(distPath, 'index.html'));
} else {
res.sendFile(path.join(publicPath, 'index.html'));
}
}
});
// 错误处理中间件
app.use((error, req, res, next) => {
console.error('服务器错误:', error);
if (req.path.startsWith('/api/')) {
res.status(500).json({ error: '服务器内部错误' });
} else {
res.status(500).send('服务器内部错误');
}
});
// 启动服务器
app.listen(PORT, () => {
console.log(`服务器运行在 http://localhost:${PORT}`);
console.log(`API文档: http://localhost:${PORT}/api/health`);
console.log(`环境: ${process.env.NODE_ENV || 'development'}`);
});