/** * 这是一个 API 服务端程序 */ import express, { type Request, type Response, type NextFunction, } from 'express' import cors from 'cors' import path from 'path' import dotenv from 'dotenv' import { fileURLToPath } from 'url' import authRoutes from './routes/auth.js' import aiRoutes from './routes/ai.js' // ESM 模式下的路径处理 const __filename = fileURLToPath(import.meta.url) const __dirname = path.dirname(__filename) // 加载环境变量 dotenv.config() const app: express.Application = express() app.use(cors()) app.use(express.json({ limit: '10mb' })) app.use(express.urlencoded({ extended: true, limit: '10mb' })) /** * API 路由配置 */ app.use('/api/auth', authRoutes) app.use('/api/ai', aiRoutes) /** * 静态文件服务 - 用于生产环境 */ const distPath = path.join(__dirname, '../dist') app.use(express.static(distPath)) /** * 健康检查接口 */ app.use( '/api/health', (req: Request, res: Response, next: NextFunction): void => { res.status(200).json({ success: true, message: '服务运行正常', }) }, ) /** * 错误处理中间件 */ app.use((error: Error, req: Request, res: Response, next: NextFunction) => { console.error('Server Error:', error) res.status(500).json({ success: false, error: '服务器内部错误', }) }) /** * 404 未找到处理 - 重定向到前端首页以支持 SPA 路由 */ app.use((req: Request, res: Response) => { if (req.path.startsWith('/api/')) { res.status(404).json({ success: false, error: '接口不存在', }) } else { res.sendFile(path.join(distPath, 'index.html')) } }) export default app