2
0
Эх сурвалжийг харах

✨ feat(server): 重构服务器架构为 Hono 框架

- 引入 Hono 框架替代原生 HTTP 服务器实现
- 将原有请求处理函数转换为 Hono 中间件架构
- 实现基于 Hono 的服务器启动流程

🐛 fix(server): 修复请求处理上下文获取问题
  - 使用 c.env 获取原生请求响应对象,解决上下文访问问题

♻️ refactor(server): 优化条件语句块格式
  - 为 if 条件结果添加花括号,提高代码可读性
  - 统一条件返回语句格式
yourname 7 сар өмнө
parent
commit
5db237db14
1 өөрчлөгдсөн 32 нэмэгдсэн , 22 устгасан
  1. 32 22
      server.js

+ 32 - 22
server.js

@@ -1,7 +1,12 @@
 import fs from 'node:fs/promises';
-import http from 'node:http';
 import { URL } from 'node:url';
 import { Transform } from 'node:stream';
+import { serve } from '@hono/node-server';
+import { Hono } from 'hono';
+import { createServer as createNodeServer } from 'node:http';
+
+// 创建 Hono 应用
+const app = new Hono();
 
 // Constants
 const isProduction = process.env.NODE_ENV === 'production';
@@ -41,17 +46,18 @@ if (!isProduction) {
   });
 }
 
-// 处理请求的函数
-async function handleRequest(req, res) {
+// 将原有请求处理逻辑转换为 Hono 中间件
+app.use(async (c, next) => {
   try {
+    // 使用 c.env 获取原生请求响应对象(关键修复)
+    const req = c.env.incoming;
+    const res = c.env.outgoing;
     const url = new URL(req.url, `http://${req.headers.host}`);
     const path = url.pathname;
 
     // 检查是否匹配基础路径
     if (!path.startsWith(baseUrl.pathname)) {
-      res.writeHead(404, { 'Content-Type': 'text/plain' });
-      res.end('Not found');
-      return;
+      return c.text('Not found', 404);
     }
 
     // 处理基础路径
@@ -65,7 +71,9 @@ async function handleRequest(req, res) {
       });
       
       // 如果 Vite 中间件已经处理了请求,直接返回
-      if (handled) return;
+      if (handled) {
+        return;
+      }
     } 
     // 生产环境:使用 compression 和 sirv 中间件
     else if (isProduction) {
@@ -74,14 +82,18 @@ async function handleRequest(req, res) {
         compressionMiddleware(req, res, () => resolve(false));
       });
       
-      if (compressed) return;
+      if (compressed) {
+        return;
+      }
       
       // 再尝试 sirv 中间件处理静态文件
       const served = await new Promise((resolve) => {
         sirvMiddleware(req, res, () => resolve(false));
       });
       
-      if (served) return;
+      if (served) {
+        return;
+      }
     }
 
     // 处理所有其他请求的 SSR 逻辑
@@ -144,25 +156,23 @@ async function handleRequest(req, res) {
       clearTimeout(abortTimeout);
     });
 
+    // 告诉 Hono 我们已经手动处理了响应
+    c.res = new Response(null, { status: 200 });
   } catch (e) {
     if (!isProduction && vite) {
       vite.ssrFixStacktrace(e);
     }
     console.error(e.stack);
-    res.writeHead(500, { 'Content-Type': 'text/plain' });
-    res.end(e.stack);
+    return c.text(e.stack, 500);
   }
-}
-
-// 创建 HTTP 服务器
-const server = http.createServer(handleRequest);
-
-// 启动服务器
-server.listen(port, () => {
-  console.log(`Server started at http://localhost:${port}`);
 });
 
-// 处理服务器错误
-server.on('error', (err) => {
-  console.error('Server error:', err);
+// 使用 Hono 的 serve 启动服务器
+serve({
+  fetch: app.fetch,
+  createServer: createNodeServer,
+  port: port,
+}, () => {
+  console.log(`Server started at http://localhost:${port}`);
 });
+