禁止使用模板插件做违法内容(涉黄等),否则将受到法律的制裁。

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 个评论

 
联系
目前暂停一切业务,客服消息可能不会及时回复,谢谢理解。
在线咨询
    在线咨询
    禁止使用模板插件做违法内容(涉黄等),否则将受到法律的制裁。