kinaiok commited on
Commit ·
43ef8b7
1
Parent(s): 134989b
feat: serve frontend static files from backend
Browse files
artifacts/api-server/src/app.ts
CHANGED
|
@@ -2,12 +2,17 @@ import express, { type Express } from "express";
|
|
| 2 |
import cors from "cors";
|
| 3 |
import cookieParser from "cookie-parser";
|
| 4 |
import pinoHttp from "pino-http";
|
|
|
|
|
|
|
| 5 |
import router from "./routes";
|
| 6 |
import openaiRouter from "./routes/openai";
|
| 7 |
import publicRouter from "./routes/public";
|
| 8 |
import accountsRouter from "./routes/accounts";
|
| 9 |
import { logger } from "./lib/logger";
|
| 10 |
|
|
|
|
|
|
|
|
|
|
| 11 |
const app: Express = express();
|
| 12 |
|
| 13 |
app.use(
|
|
@@ -41,4 +46,17 @@ app.use("/api", router);
|
|
| 41 |
app.use("/v1", openaiRouter);
|
| 42 |
app.use("/api/v1", openaiRouter);
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
export default app;
|
|
|
|
| 2 |
import cors from "cors";
|
| 3 |
import cookieParser from "cookie-parser";
|
| 4 |
import pinoHttp from "pino-http";
|
| 5 |
+
import path from "path";
|
| 6 |
+
import { fileURLToPath } from "url";
|
| 7 |
import router from "./routes";
|
| 8 |
import openaiRouter from "./routes/openai";
|
| 9 |
import publicRouter from "./routes/public";
|
| 10 |
import accountsRouter from "./routes/accounts";
|
| 11 |
import { logger } from "./lib/logger";
|
| 12 |
|
| 13 |
+
const __filename = fileURLToPath(import.meta.url);
|
| 14 |
+
const __dirname = path.dirname(__filename);
|
| 15 |
+
|
| 16 |
const app: Express = express();
|
| 17 |
|
| 18 |
app.use(
|
|
|
|
| 46 |
app.use("/v1", openaiRouter);
|
| 47 |
app.use("/api/v1", openaiRouter);
|
| 48 |
|
| 49 |
+
// 提供前端靜態檔案
|
| 50 |
+
const frontendDistPath = path.join(__dirname, "../../image-gen/dist");
|
| 51 |
+
app.use(express.static(frontendDistPath));
|
| 52 |
+
|
| 53 |
+
// SPA fallback - 所有非 API 路由都返回 index.html
|
| 54 |
+
app.get("*", (req, res) => {
|
| 55 |
+
if (!req.path.startsWith("/api") && !req.path.startsWith("/v1")) {
|
| 56 |
+
res.sendFile(path.join(frontendDistPath, "index.html"));
|
| 57 |
+
} else {
|
| 58 |
+
res.status(404).json({ error: "Not found" });
|
| 59 |
+
}
|
| 60 |
+
});
|
| 61 |
+
|
| 62 |
export default app;
|