fix: 修复流式响应缓冲问题,实现真正的实时流传输

- 配置 compression 中间件排除 SSE 流式响应,避免压缩导致的缓冲
- 添加 X-Accel-Buffering: no 响应头,禁用 Nginx 等代理的缓冲
- 使用 res.flushHeaders() 立即发送响应头
- 禁用 Nagle 算法确保数据立即发送
- 在每次写入流数据后调用 flush() 确保实时传输

这些修复确保了流式请求能够正常显示打字机效果,数据从上游 Claude API 接收后能够立即转发给客户端。

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
shaw
2025-07-23 15:56:27 +08:00
parent 2f4730baba
commit 1e372dd365
3 changed files with 79 additions and 39 deletions

View File

@@ -64,8 +64,17 @@ class Application {
this.app.use(corsMiddleware);
}
// 📦 压缩
this.app.use(compression());
// 📦 压缩 - 排除流式响应SSE
this.app.use(compression({
filter: (req, res) => {
// 不压缩 Server-Sent Events
if (res.getHeader('Content-Type') === 'text/event-stream') {
return false;
}
// 使用默认的压缩判断
return compression.filter(req, res);
}
}));
// 🚦 全局速率限制(仅在生产环境启用)
if (process.env.NODE_ENV === 'production') {