遥舟客 - Vue3
type: channel
link: https://www.renlmingj.cn/index.php/tag/Vue3/
items: Vue3+ts处理ai后端返回流式数据

Vue3+ts处理ai后端返回流式数据
type: item
date: 2025-03-12T17:28:25+08:00
description: 一、使用 fetch 请求二、封装 ts 公共文件const tokeninfo = JSON.parse(localStorage.getItem('token') || '{}'); const token = tokeninfo.access_token; export async function fetchProxy(url: string, options: any = {}) { const response = await fetch(`/api${url}`, { // 手动添加代理前缀[6](@ref) ...options, headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' } }) if (!response.ok) throw new Error(response.statusText) return response }三、页面中使用// 导入接口 import { fetchProxy } from '../utils/fetch'; const handleSearchUpdate = async (val: any) => { const body = { tagId: agentList.value, content: val } const resp: any = await fetchProxy('/xxx', { method: 'POST', body: JSON.stringify(body), }) const reader = resp.body.getReader(); let newData = ''; const textDecoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) { break; } const chunk = textDecoder.decode(value); chunk.split('\n\n').forEach(rawData => { if (!rawData.startsWith('data:')) return; try { const jsonStr = rawData.replace('data:', '').trim(); const data = JSON.parse(jsonStr); // 数据根据真实数据处理 newData += data.choices[0].delta.content; // 滚动到底部 scrollToBottom(); } catch (e) { console.warn(e, '无效数据块:', rawData); } }); } }注：后端接口返回的 content-type 类型必须是 text/event-stream，否则不生效！！！