|
|
@@ -83,52 +83,6 @@ if (!isProduction) {
|
|
|
console.log('Vite 开发服务器初始化完成');
|
|
|
}
|
|
|
|
|
|
-// 生产环境:启动时加载 API 路由
|
|
|
-if (isProduction) {
|
|
|
- console.log('生产环境: 加载编译后的 API 路由...');
|
|
|
- const api = (await import('./dist/api/api.js')).default;
|
|
|
- app.route('/', api);
|
|
|
- console.log('API 路由加载完成');
|
|
|
-}
|
|
|
-// 开发环境:不在此处加载 API 路由,改为在中间件中动态加载
|
|
|
-
|
|
|
-// 添加动态 API 路由中间件
|
|
|
-app.use(async (c, next) => {
|
|
|
- try {
|
|
|
- // 开发环境:每次请求动态加载 API 路由
|
|
|
- if (!isProduction && vite) {
|
|
|
- // 动态加载最新 API 模块
|
|
|
- const apiModule = await vite.ssrLoadModule('./src/server/api.ts');
|
|
|
-
|
|
|
- // 创建临时子应用并挂载路由
|
|
|
- const apiApp = new Hono();
|
|
|
- apiApp.route('/', apiModule.default);
|
|
|
-
|
|
|
- // 检查是否为 API 请求
|
|
|
- if (
|
|
|
- c.req.path.startsWith('/api')
|
|
|
- || c.req.path.startsWith('/ui')
|
|
|
- || c.req.path.startsWith('/doc')
|
|
|
- ) {
|
|
|
- // 直接由子应用处理 API 请求
|
|
|
- return apiApp.fetch(c.req.raw, {
|
|
|
- ...c.env,
|
|
|
- // 传递原始请求对象
|
|
|
- incoming: c.env.incoming,
|
|
|
- outgoing: c.env.outgoing
|
|
|
- });
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- await next();
|
|
|
- } catch (e) {
|
|
|
- if (!isProduction && vite) {
|
|
|
- vite.ssrFixStacktrace(e);
|
|
|
- }
|
|
|
- console.error('API 路由加载错误:', e.stack);
|
|
|
- return c.text('API 服务器错误', 500);
|
|
|
- }
|
|
|
-});
|
|
|
|
|
|
// 请求处理中间件 - 通用逻辑
|
|
|
app.use(async (c, next) => {
|
|
|
@@ -187,6 +141,53 @@ app.use(async (c, next) => {
|
|
|
}
|
|
|
});
|
|
|
|
|
|
+// 生产环境:启动时加载 API 路由
|
|
|
+if (isProduction) {
|
|
|
+ console.log('生产环境: 加载编译后的 API 路由...');
|
|
|
+ const api = (await import('./dist/api/api.js')).default;
|
|
|
+ app.route('/', api);
|
|
|
+ console.log('API 路由加载完成');
|
|
|
+}
|
|
|
+// 开发环境:不在此处加载 API 路由,改为在中间件中动态加载
|
|
|
+
|
|
|
+// 添加动态 API 路由中间件
|
|
|
+app.use(async (c, next) => {
|
|
|
+ try {
|
|
|
+ // 开发环境:每次请求动态加载 API 路由
|
|
|
+ if (!isProduction && vite) {
|
|
|
+ // 动态加载最新 API 模块
|
|
|
+ const apiModule = await vite.ssrLoadModule('./src/server/api.ts');
|
|
|
+
|
|
|
+ // 创建临时子应用并挂载路由
|
|
|
+ const apiApp = new Hono();
|
|
|
+ apiApp.route('/', apiModule.default);
|
|
|
+
|
|
|
+ // 检查是否为 API 请求
|
|
|
+ if (
|
|
|
+ c.req.path.startsWith('/api')
|
|
|
+ || c.req.path.startsWith('/ui')
|
|
|
+ || c.req.path.startsWith('/doc')
|
|
|
+ ) {
|
|
|
+ // 直接由子应用处理 API 请求
|
|
|
+ return apiApp.fetch(c.req.raw, {
|
|
|
+ ...c.env,
|
|
|
+ // 传递原始请求对象
|
|
|
+ incoming: c.env.incoming,
|
|
|
+ outgoing: c.env.outgoing
|
|
|
+ });
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ await next();
|
|
|
+ } catch (e) {
|
|
|
+ if (!isProduction && vite) {
|
|
|
+ vite.ssrFixStacktrace(e);
|
|
|
+ }
|
|
|
+ console.error('API 路由加载错误:', e.stack);
|
|
|
+ return c.text('API 服务器错误', 500);
|
|
|
+ }
|
|
|
+});
|
|
|
+
|
|
|
// 请求处理中间件 - SSR 渲染逻辑
|
|
|
app.use(async (c) => {
|
|
|
try {
|