route.ts
3.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { NextRequest } from "next/server";
// 统一的同源 /api 流式代理(catch-all)。
// 取代 next.config 的 rewrites:rewrites 会把请求体与响应整体缓冲,
// → 大文件上传被卡(约 10MB),SSE 流式接口也变成「跑完一次性下发」。
// 这里对**请求体**与**响应体**都做流式透传,永不缓冲,所有接口(GET/POST/上传/下载/SSE)走同一条通道。
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
// 取消该路由的时长限制,兼容长连接 SSE 与大文件上传
export const maxDuration = 300;
const BACKEND = process.env.BACKEND_INTERNAL_URL || "http://backend:8104";
// 逐跳头(hop-by-hop)与会让上游困惑的头,转发前剔除
const STRIP_REQUEST_HEADERS = new Set([
"host",
"connection",
"content-length",
"transfer-encoding",
"keep-alive",
"upgrade",
"expect",
]);
async function proxy(req: NextRequest) {
// 直接用原始 pathname 还原后端路径,避免对已编码的路径段二次编码
const rest = req.nextUrl.pathname.replace(/^\/api/, "");
const target = `${BACKEND}${rest}${req.nextUrl.search}`;
const headers = new Headers();
req.headers.forEach((value, key) => {
if (!STRIP_REQUEST_HEADERS.has(key.toLowerCase())) headers.set(key, value);
});
const method = req.method.toUpperCase();
const hasBody = method !== "GET" && method !== "HEAD";
try {
const upstream = await fetch(target, {
method,
headers,
// 请求体流式透传:绝不读 formData/arrayBuffer/text,否则会整体缓冲并触发大小上限
body: hasBody ? req.body : undefined,
redirect: "manual",
// undici 流式请求体必须声明 duplex
...(hasBody ? { duplex: "half" } : {}),
} as RequestInit & { duplex?: "half" });
// 响应头透传(含 content-type、下载用的 content-disposition),剔除逐跳头
const respHeaders = new Headers();
upstream.headers.forEach((value, key) => {
const k = key.toLowerCase();
if (k === "content-length" || k === "transfer-encoding" || k === "connection") return;
respHeaders.set(key, value);
});
// 保障 SSE 等流式响应实时下发
respHeaders.set("cache-control", "no-cache, no-transform");
respHeaders.set("x-accel-buffering", "no");
// 响应体流式透传:直接把上游 ReadableStream 交给浏览器,绝不 await text()
return new Response(upstream.body, {
status: upstream.status,
statusText: upstream.statusText,
headers: respHeaders,
});
} catch (e) {
const msg = e instanceof Error ? `${e.name}: ${e.message}` : String(e);
console.error(`[api-proxy] ${method} ${target} FAILED ->`, e);
return new Response(JSON.stringify({ detail: `代理转发失败: ${msg}` }), {
status: 502,
headers: { "content-type": "application/json" },
});
}
}
export const GET = proxy;
export const POST = proxy;
export const PUT = proxy;
export const PATCH = proxy;
export const DELETE = proxy;
export const HEAD = proxy;
export const OPTIONS = proxy;