需求:根据接口返回的数据进行类似打字机渲染的效果

使用的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();
            })

接口返回的数据格式
在这里插入图片描述

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐