前端根据后端返回的文本流逐个展示文本内容
1、前端调用方法
js
async function fetchStream(url, data, onSuccess, close, error) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
if (!response.ok) {
onSuccess(`服务响应失败,请稍后重试`);
close();
throw new Error(`HTTP error! status: ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let result = '';
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
const decodedValue = decoder.decode(value, { stream: true });
result += decodedValue;
onSuccess && onSuccess(decodedValue); // 每次接收到数据时,调用onSuccess
}
close();
return result;
}
2、使用
js
const onSend = () => {
if (!questionText.value.trim()) {
message('不能发送空消息', { type: 'warning' });
return;
}
chatList.value.push({
index: chatIndex.value + 1,
type: 'user',
content: questionView.value
});
chatList.value.push({
index: chatIndex.value + 1,
type: 'assistant',
content: ''
});
const data = {
question: questionView.value,
modelId: props.modelId,
sessionId: sessionId.value
};
let streamContent = '';
const onStreamSuccess = (chunk) => {
streamContent += chunk;
chatList.value[chatList.value.length - 1].content = streamContent.replace(/\n+/g, ' ').replace(/ {2,}/g, ' ');
scrollToBottom();
};
fetchStream(
'/ai/aiAgent/stream',
data,
onStreamSuccess,
() => {
sendloading.value = false;
},
() => {
chatList.value[chatList.value.length - 1].content = '';
sendloading.value = false;
}
);
};
经过以上两步,即可实现文本流逐个显示在界面上。