首页 前端知识 Vue实现Ai 聊天(流式请求处理和碰到的问题)

Vue实现Ai 聊天(流式请求处理和碰到的问题)

2025-03-08 14:03:34 前端知识 前端哥 457 888 我要收藏

使用axios请求后,返回的数据是阻塞的,只能在最后拿到最终的结果,而不是流式

axios请求代码如下(无法实现流式效果)
axios.post('http://localhost:20000/opens/ai', {
responseType: 'stream'
}).then(response => {
response.data.on('data', (chunk) => {
console.log('数据读取:' + chunk)
})
response.data.on('end', () => {
console.log('数据读取完成')
})
})
复制

重点,使用fetch来替换axios

参考代码如下
async fetchData() {
try {
fetch('http://localhost:20000/opens/ai', {
responseType: 'stream'
}).then(async response => {
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
this.streamedData += chunk;
console.log('Received chunk:', chunk);
}
})
} catch (error) {
console.error('请求失败:', error);
}
},
复制

注意fetch是浏览器自带的api,不需要引入第三方依赖。直接使用

另外作者主页中有个完整的全栈项目,有兴趣可以看看(进主页查看或者点击下方链接哦)

https://blog.csdn.net/weixin_52911459/article/details/135256041

转载请注明出处或者链接地址:https://www.qianduange.cn//article/22874.html
标签
评论
还可以输入200
共0条数据,当前/页
发布的文章

Lua与Unity交互

2025-03-08 14:03:36

Pygame介绍与游戏开发

2025-03-08 14:03:36

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!