修改架构,移动端优先。
save
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
import 'dotenv/config'
|
||||
import path from 'node:path'
|
||||
import fs from 'node:fs'
|
||||
import express from 'express'
|
||||
import cors from 'cors'
|
||||
import authRouter from './routes/auth.js'
|
||||
import dataRouter from './routes/data.js'
|
||||
import articlesRouter from './routes/articles.js'
|
||||
|
||||
const PORT = Number(process.env.PORT) || 3001
|
||||
const DIST_DIR = path.join(process.cwd(), 'dist')
|
||||
const HAS_DIST = fs.existsSync(DIST_DIR)
|
||||
|
||||
const app = express()
|
||||
app.use(cors())
|
||||
app.use(express.json())
|
||||
|
||||
// 健康检查
|
||||
app.get('/api/health', (_req, res) => res.json({ ok: true, ts: Date.now() }))
|
||||
|
||||
// 业务路由
|
||||
app.use('/api/auth', authRouter)
|
||||
app.use('/api', dataRouter)
|
||||
app.use('/api', articlesRouter)
|
||||
|
||||
// 静态资源 (Vite build 产物)
|
||||
if (HAS_DIST) {
|
||||
app.use(express.static(DIST_DIR, { index: false, maxAge: '1h', etag: true }))
|
||||
|
||||
// SPA fallback: 非 /api/* 的请求一律返回 index.html, 由前端路由处理
|
||||
app.get(/^\/(?!api\/).*/, (_req, res, next) => {
|
||||
const indexHtml = path.join(DIST_DIR, 'index.html')
|
||||
if (!fs.existsSync(indexHtml)) return next()
|
||||
res.sendFile(indexHtml)
|
||||
})
|
||||
}
|
||||
|
||||
// 统一错误处理
|
||||
app.use((err, _req, res, _next) => {
|
||||
console.error('[api error]', err)
|
||||
res.status(500).json({ error: err.message || '服务器内部错误' })
|
||||
})
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`[iboard-api] listening on http://127.0.0.1:${PORT}`)
|
||||
console.log(`[iboard-api] static dist: ${HAS_DIST ? DIST_DIR : '(not built, API only)'}`)
|
||||
})
|
||||
Reference in New Issue
Block a user