前端根據(jù)后端返回的文本流逐個展示文本內(nèi)容代碼示例
前端根據(jù)后端返回的文本流逐個展示文本內(nèi)容
1、前端調(diào)用方法
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(`服務(wù)響應(yīng)失敗,請稍后重試`); 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); // 每次接收到數(shù)據(jù)時,調(diào)用onSuccess } close(); return result; }
2、使用
const onSend = () => { if (!questionText.value.trim()) { message('不能發(fā)送空消息', { 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; } ); };
經(jīng)過以上兩步,即可實現(xiàn)文本流逐個顯示在界面上。
總結(jié)
到此這篇關(guān)于前端根據(jù)后端返回的文本流逐個展示文本內(nèi)容的文章就介紹到這了,更多相關(guān)根據(jù)后端文本流展示文本內(nèi)容內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用SyntaxHighlighter實現(xiàn)HTML高亮顯示代碼的方法
syntaxhighlighter是一個小開源項目,它可以在網(wǎng)頁中對各種程序源代碼語法進行加亮顯示。2010-02-02JS函數(shù)修改html的元素內(nèi)容,及修改屬性內(nèi)容的方法
下面小編就為大家?guī)硪黄狫S函數(shù)修改html的元素內(nèi)容,及修改屬性內(nèi)容的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-10-10layer.prompt使文本框為空的情況下也能點擊確定的方法
今天小編就為大家分享一篇layer.prompt使文本框為空的情況下也能點擊確定的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09javaScript在表單提交時獲取表單數(shù)據(jù)的示例代碼
本文介紹了五種在JavaScript中獲取表單數(shù)據(jù)的方法:使用FormData對象、手動提取表單數(shù)據(jù)、使用querySelector獲取單個字段數(shù)據(jù)、序列化為查詢字符串和配合AJAX提交表單數(shù)據(jù),每種方法都有示例代碼,幫助開發(fā)者更好地理解和應(yīng)用2025-02-02js中net::ERR_FILE_NOT_FOUND報錯的解決
本文主要介紹了js中net::ERR_FILE_NOT_FOUND報錯的解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07