Files
backend-node/server.ts

66 lines
2.0 KiB
TypeScript

import 'dotenv/config';
import express, { Request, Response, NextFunction } from 'express';
import cors from 'cors';
import path from 'path';
import authRoutes from './routes/auth';
import serialRoutes from './routes/serials';
import companyRoutes from './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: Request, res: Response, next: NextFunction): void => {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
next();
});
app.use('/api/auth', authRoutes);
app.use('/api/serials', serialRoutes);
app.use('/api/companies', companyRoutes);
app.get('/api/health', (req: Request, res: Response): void => {
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));
}
app.use((req: Request, res: Response): void => {
if (req.path.startsWith('/api/')) {
res.status(404).json({ error: 'API接口不存在' });
} else {
if (process.env.NODE_ENV === 'production') {
res.sendFile(path.join(distPath, 'index.html'));
} else {
res.sendFile(path.join(publicPath, 'index.html'));
}
}
});
app.use((error: Error, req: Request, res: Response, next: NextFunction): void => {
console.error('服务器错误:', error);
if (req.path.startsWith('/api/')) {
res.status(500).json({ error: '服务器内部错误' });
} else {
res.status(500).send('服务器内部错误');
}
});
app.listen(PORT, (): void => {
console.log(`服务器运行在 http://localhost:${PORT}`);
console.log(`API文档: http://localhost:${PORT}/api/health`);
console.log(`环境: ${process.env.NODE_ENV || 'development'}`);
});