浏览器不能直连上游(会泄露密钥),常见做法是后端接收流再以 SSE 转发。这一步最容易踩的是缓冲与编码。
data: {"delta":"你"}
data: {"delta":"好"}
data: [DONE]
每个事件以 data: 开头,两个换行结束;响应头必须是 text/event-stream。
export async function POST(req) {
const upstream = await fetch("https://hardysapi.com/v1/chat/completions", {
method: "POST",
headers: { "Content-Type": "application/json",
Authorization: `Bearer ${process.env.KEY}` },
body: JSON.stringify({ model: "gpt-5.5", stream: true, messages }),
});
return new Response(upstream.body, {
headers: { "Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no" },
});
}
proxy_buffering off; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_read_timeout 300s;
TextDecoder 流式解码,不要对每个 chunk 单独 decode;: ping;反向代理或框架开启了响应缓冲,需要 proxy_buffering off 并设置 X-Accel-Buffering: no。
建议加,每 15–30 秒发一个注释行 : ping,避免中间设备因空闲断开连接。