Pārlūkot izejas kodu

Add Cloudflare worker and API proxy functionality

- Create `worker.js` to handle SPA routing and static asset requests.
- Add `wrangler.toml` for project configuration and asset management.
- Implement API proxy in `[[path]].ts` to forward requests to the backend service with CORS support.
yb 3 nedēļas atpakaļ
vecāks
revīzija
cbefc4b94b
3 mainītis faili ar 68 papildinājumiem un 0 dzēšanām
  1. 37 0
      functions/api/[[path]].ts
  2. 19 0
      worker.js
  3. 12 0
      wrangler.toml

+ 37 - 0
functions/api/[[path]].ts

@@ -0,0 +1,37 @@
+// API 代理 - 将 /api/* 请求转发到后端服务
+const API_BASE = 'https://tg-live-game-api.ifoodme.com';
+
+export const onRequest: PagesFunction = async (context) => {
+  const { request } = context;
+  const url = new URL(request.url);
+
+  // 构建目标 URL: /api/auth/login -> https://tg-live-game-api.ifoodme.com/api/auth/login
+  const targetUrl = `${API_BASE}${url.pathname}${url.search}`;
+
+  // 复制请求头,移除 host
+  const headers = new Headers(request.headers);
+  headers.delete('host');
+  headers.set('origin', API_BASE);
+
+  // 转发请求
+  const response = await fetch(targetUrl, {
+    method: request.method,
+    headers,
+    body: request.method !== 'GET' && request.method !== 'HEAD'
+      ? request.body
+      : undefined,
+  });
+
+  // 复制响应头
+  const responseHeaders = new Headers(response.headers);
+
+  // 添加 CORS 头
+  responseHeaders.set('Access-Control-Allow-Origin', url.origin);
+  responseHeaders.set('Access-Control-Allow-Credentials', 'true');
+
+  return new Response(response.body, {
+    status: response.status,
+    statusText: response.statusText,
+    headers: responseHeaders,
+  });
+};

+ 19 - 0
worker.js

@@ -0,0 +1,19 @@
+// 静态资产由 Cloudflare 自动处理
+// 这个文件用于处理 SPA 路由 fallback
+
+export default {
+  async fetch(request, env) {
+    const url = new URL(request.url);
+
+    // 如果请求的是静态资源路径,让 Cloudflare 处理
+    if (url.pathname.startsWith('/assets/') ||
+        url.pathname === '/vite.svg' ||
+        url.pathname === '/favicon.ico') {
+      return env.ASSETS.fetch(request);
+    }
+
+    // SPA fallback: 所有其他路径返回 index.html
+    const indexRequest = new Request(new URL('/', request.url), request);
+    return env.ASSETS.fetch(indexRequest);
+  }
+};

+ 12 - 0
wrangler.toml

@@ -0,0 +1,12 @@
+name = "tg-live-game-web"
+main = "worker.js"
+compatibility_date = "2024-01-01"
+account_id = "5544eac7cfb260d4fec9467d49513cea"
+
+# 静态资产配置
+[assets]
+directory = "./dist"
+
+# 生产环境
+[env.production]
+name = "tg-live-game-web"