Spaces:
Sleeping
Sleeping
File size: 1,679 Bytes
ad893f7 9cd53be ad893f7 9cd53be ad893f7 9cd53be ad893f7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | /**
* 这是一个 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
|