Browse Source

✨ feat(proxy): 添加plant2服务代理路由

- 实现/plant2/*路径的代理功能,转发请求到https://plant2.hbatg.com
- 处理URL路径和查询参数转换
- 添加请求错误处理和日志记录
- 修改前端XHR拦截逻辑,将原请求重定向到代理路由

✨ refactor(renderer): 更新API请求拦截逻辑

- 修改XHR拦截规则,将原域名请求重定向到/plant2代理路径
- 优化URL替换正则表达式,提高匹配准确性
yourname 1 month ago
parent
commit
b902192b8d
2 changed files with 34 additions and 2 deletions
  1. 32 0
      src/server/api.ts
  2. 2 2
      src/server/renderer.tsx

+ 32 - 0
src/server/api.ts

@@ -110,6 +110,38 @@ export const authRoutes = api.route('/api/v1/auth', authRoute)
 export const roleRoutes = api.route('/api/v1/roles', rolesRoute)
 export const fileApiRoutes = api.route('/api/v1/files', fileRoutes)
 
+// 代理路由 - 转发到plant2.hbatg.com
+app.all('/plant2/*', async (c) => {
+  const path = c.req.path.replace('/plant2', '')
+  const query = c.req.url.split('?')[1] || ''
+  const targetUrl = `https://plant2.hbatg.com${path}${query ? '?' + query : ''}`
+  console.debug('targetUrl', targetUrl)
+
+  try {
+    const response = await fetch(targetUrl, {
+      method: c.req.method,
+      headers: {
+        // ...Object.fromEntries(c.req.raw.headers),
+        // 'host': 'plant2.hbatg.com'
+      },
+      body: c.req.raw.body
+    })
+
+    const responseBody = await response.text()
+
+    console.debug('responseBody', responseBody)
+
+    // return new Response(responseBody, {
+    //   status: response.status,
+    //   headers: Object.fromEntries(response.headers)
+    // })
+    return c.text(responseBody, response.status as 200)
+  } catch (error) {
+    console.error('代理请求失败:', error)
+    return c.json({ error: '代理请求失败' }, 500)
+  }
+})
+
 export type AuthRoutes = typeof authRoutes
 export type UserRoutes = typeof userRoutes
 export type RoleRoutes = typeof roleRoutes

+ 2 - 2
src/server/renderer.tsx

@@ -112,8 +112,8 @@ export const Rooter = () => {
             XMLHttpRequest.prototype.open = function(method, url, ...args) {
               // 检查URL是否包含需要拦截的域名
               if (url && url.includes(INTERCEPT_DOMAIN)) {
-                // 将URL重定向到当前域
-                const newUrl = url.replace(new RegExp('https?://[^/]*' + INTERCEPT_DOMAIN), '');
+                // 将URL重定向到代理路由
+                const newUrl = url.replace(new RegExp('https?://[^/]*' + INTERCEPT_DOMAIN), '/plant2');
                 console.log('XHR拦截: 将请求从', url, '重定向到', newUrl);
                 return originalXHROpen.call(this, method, newUrl, ...args);
               }