需求:根据接口返回的数据进行类似打字机渲染的效果
使用的fetch 流式处理
fetch('BASE_URL/api/apps/' + this.app_Id + '/chat-messages', {
signal: this.controller.signal,
method: 'POST',
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token'),
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': '*',
},
mode: 'cors',
body: JSON.stringify({
query: this.chat_input,
chat_id: this.chat_Id,
stream: true,
app_config: getApp_config,
}),
})
.then((response) => {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
function processResult() {
reader
.read()
.then(({ done, value }) => {
if (done) {
that.chat_input = '';
that.isInputend = false;
return;
}
const chunk = decoder.decode(value, { stream: true });
buffer += chunk;
console.log(buffer, 'buffer========');
// 分割数据并解析JSON
const lines = buffer.split('\n');
console.log(lines, 'lines========');
lines.forEach((line) => {
if (line.startsWith('data: ')) {
const jsonStr = line.substring(6); // 去掉前缀
try {
const data = JSON.parse(jsonStr);
// console.log('Parsed data:', data);
if (data.event === 'message_end') {
that.chat_input = '';
that.isInputend = false;
that.chatList[
that.chatList.length - 1
].referenceList = data.referencesList;
reader.cancel(); // 取消reader,结束流
} else {
if (
that.chatList[that.chatList.length - 1]
.answer == that.$t('text80')
) {
that.chatList[
that.chatList.length - 1
].answer = '';
}
that.chatList[
that.chatList.length - 1
].answer += data.answer;
// that.chatList[that.chatList.length - 1].answer =
// '服务器异常,请重试';
}
} catch (error) {
// console.error('Error parsing JSON:', error);
}
}
});
buffer = lines[lines.length - 1]; // 保留最后一个不完整的行
processResult(); // 继续处理下一个chunk
})
.catch((error) => {
console.error('Error reading the stream:', error);
});
}
processResult();
})