wordpress收费下载资源主题
wordpress付费下载资源插件

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

下面是模板兔精心调试+亲测的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);
});

0 个评论

定制开发
本站承接WordPress等系统建站仿站、二次开发、主题插件定制等开发服务
在线咨询
  • 请直接说明需求,勿问在否
    QQ:1-247-246-247

  • QQ一群:104228692(满)
  • QQ二群:64786792
在线咨询
本站承接WordPress建站仿站、二次开发、主题插件定制等PHP开发服务!

了解详情