欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > Vue实现Ai 聊天(流式请求处理和碰到的问题)

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

2024/10/28 12:12:45 来源:https://blog.csdn.net/weixin_52911459/article/details/143205069  浏览:    关键词:Vue实现Ai 聊天(流式请求处理和碰到的问题)

使用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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com