下面是模板兔精心调试+亲测的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 个评论