简述js接收读取GPT的stream流的两种方法:EventSource与Fetch

本文介绍了如何使用EventSource和Fetch两种方法在JavaScript中接收和处理stream流,特别是针对GPT等AI接口的数据输出。EventSource示例展示了如何监听onmessage事件来处理数据,而Fetch则通过getReader()和TextDecoder进行流解析。这两种方法都允许在页面上实时更新内容,当收到[DONE]信号时执行完成的页面逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面是模板兔精心调试+亲测的js接收读取stream流的两种方法:EventSource与Fetch,供大家参考。可用于对接GPT等一些AI接口,从而在页面像打字一样输出内容。

EventSource:

var es = new EventSource(result.url, { withCredentials: true });
es.onerror = function (event) {
    //执行错误的页面逻辑
    es.close();
}
es.onmessage = function (event) {
    //console.log(event.data);

    if (event.data == "[DONE]") {
        //执行完成的页面逻辑
        es.close();
    }else{

    }
}

Fetch:

fetch(result.url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ test: 'test' }),
}).then(response => {
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let buffer = '';

function processStreamResult(result2) {
const chunk = decoder.decode(result2.value, { stream: !result2.done });
buffer += chunk;
//逐条解析后端返回数据
const lines = buffer.split('\n');
buffer = lines.pop();

lines.forEach(line => {
if (line.trim().length > 0) { 
//console.log(line);

if(line == 'data: [DONE]'){
    //执行完成的页面逻辑
}else{

} 

}
});

if (!result2.done) {
    return reader.read().then(processStreamResult);
}
}

return reader.read().then(processStreamResult);
})
.catch(error => {
    //console.error('Error:', error);
});

原文:https://www.mobantu.com/9934.html

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值