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