From 704a02f2173363f62b4d4e78b12269dd63c78b98 Mon Sep 17 00:00:00 2001 From: abearxiong Date: Mon, 5 Jan 2026 14:11:43 +0800 Subject: [PATCH] update --- next.config.ts | 3 ++- proxy.ts | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 proxy.ts diff --git a/next.config.ts b/next.config.ts index bb186c0..bd40853 100644 --- a/next.config.ts +++ b/next.config.ts @@ -6,9 +6,10 @@ console.log(`NODE_ENV: ${process.env.NODE_ENV}`); const basePath = isDev ? "" : `${pkgs.basename}`; const nextConfig: NextConfig = { /* config options here */ - output: 'export', + output: isDev ? undefined : 'export', distDir: 'dist', basePath: basePath, + trailingSlash: true, }; export default nextConfig; diff --git a/proxy.ts b/proxy.ts new file mode 100644 index 0000000..ea54403 --- /dev/null +++ b/proxy.ts @@ -0,0 +1,64 @@ +import { NextRequest, NextResponse } from 'next/server'; + +const API_URL = process.env.API_URL || 'http://localhost:51515'; +/** + * 通用代理函数 + * @param request 原始请求 + * @param targetHost 目标服务器地址(如 http://localhost:51515) + * @returns NextResponse 代理响应 + */ +async function proxyRequest(request: NextRequest, targetHost: string): Promise { + const { pathname } = request.nextUrl; + const targetUrl = new URL(pathname + request.nextUrl.search, targetHost); + + try { + console.log(`Proxying request to: ${targetUrl.toString()}`); + const response = await fetch(targetUrl.toString(), { + method: request.method, + headers: { + // 复制原始请求的所有头部 + ...Object.fromEntries(request.headers.entries()), + // 确保转发 cookie + cookie: request.headers.get('cookie') || '', + }, + body: request.method !== 'GET' && request.method !== 'HEAD' ? await request.text() : undefined, + // 包含 cookie 的请求 + credentials: 'include', + }); + + // 创建响应,保留原始响应的所有头部(包括 Set-Cookie) + const responseHeaders = new Headers(response.headers); + + return new NextResponse(response.body, { + status: response.status, + statusText: response.statusText, + headers: responseHeaders, + }); + } catch (error) { + console.error('Proxy error:', error); + return NextResponse.json( + { error: 'Proxy request failed' }, + { status: 502 } + ); + } +} + +export async function proxy(request: NextRequest) { + const { pathname } = request.nextUrl; + // 代理 /api 请求 + if (pathname.startsWith('/api')) { + return proxyRequest(request, API_URL); + } + // 代理 /root/home 或 /root/home/ 请求 (第二个路径段后可以为空或以 / 结尾) + if (pathname.match(/^\/root\/\w+(\/)?$/)) { + return proxyRequest(request, API_URL); + } + + return NextResponse.next(); +} + +export const config = { + matcher: ['/api/:path*', '/root/:segment/:path*'], +}; + +export default proxy; \ No newline at end of file