You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js Express实时流式转发响应至前端的问题求助

Node.js Express 流式响应实时转发单个字符的解决方法

从你的控制台输出能看到,上游返回的流确实已经拆成单个字符的chunk了,但Express默认会缓冲响应内容,导致前端没法实时收到每一个字符。下面是具体的解决步骤:

1. 配置流式响应头

先告诉前端这是分块传输的流式内容,同时不要设置固定的Content-Length:

res.setHeader('Transfer-Encoding', 'chunked');
res.setHeader('Content-Type', 'text/plain; charset=utf-8');

2. 强制刷新响应缓冲区

Express默认会攒够一定量的内容才发送给前端,你需要在每次res.write之后调用res.flush(),强制把当前内容立刻发送出去:

response.body.on('data', (chunk) => {
    console.log(chunk.toString());
    res.write(chunk.toString());
    res.flush(); // 关键:立即推送内容到前端
});

3. 完整示例代码

try {
    const response = await getResponse();

    // 配置流式响应头
    res.setHeader('Transfer-Encoding', 'chunked');
    res.setHeader('Content-Type', 'text/plain; charset=utf-8');

    response.body.on('data', (chunk) => {
        console.log(chunk.toString());
        res.write(chunk.toString());
        res.flush();
    });

    response.body.on('end', () => {
        console.log('Streaming text finished.');
        res.end();
    });

    // 处理流错误
    response.body.on('error', (err) => {
        console.error('Stream error:', err);
        res.status(500).end();
    });
} catch (error) {
    console.error("Error:", error);
    res.status(500).end();
}

内容的提问来源于stack exchange,提问作者Arsene Wenger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 22:43:07