使用fetch
流式获取一般在用于数据量比较大的情况,一次性返回会导致前端页面加载时间过长或者请求超时等问题,这时候我们就不能等所有的结果都返回再显示出来,可以考虑使用流式的方式拿到部分数据并先展示,从而提升用户体验
fetch(url, {
method: 'POST', // 请求方法
headers: {
"Content-Type": "application/json", // 请求头
Authorization: token // 校验令牌,根据自己的服务器需求传
},
body: JSON.stringify({
// 请求体
prompt: [{
role: 'user', content: data}],
incremental: true
})
}).then(res => {
const reader = result.body.getReader() // 创建读取器
let content ="";
const textDecoder = new TextDecoder() // 创建解码器
while(true){
// 循环读取内容
/* 读取其中一部分内容,其中 done 是否读取完成, value 读取到的内容 */
const {
done, value} = await reader.read()
if(done){
break;
}
const str = textDecoder.decode(value) // 利用解码器把数据解析成字符串
console.log(str) // 这时候str就是服务器返回的内容
cotent +=str; // 将返回的内容合并
conosole.log('结果为':res);
}
})
注:
result.body是暴露响应体内容的可读的可读的字节数据流.