请求响应已开始但未结束前持续获取响应的内容
const getContent = async (e: any) => {
e.preventDefault();
setLoading(true);
await fetch("/api/content", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
key:"hahaha",
}),
})
if (!response.ok) {
throw new Error(response.statusText);
}
// This data is a ReadableStream
const data = response.body;
if (!data) {
return;
}
const reader = data.getReader();
const decoder = new TextDecoder();
let done = false;
while (!done) {
const { value, done: doneReading } = await reader.read();
done = doneReading;
const chunkValue = decoder.decode(value);
setContent((prev) => prev + chunkValue);
}
setLoading(false);
};
getReader: https://developer.mozilla.org/zh-CN/docs/Web/API/ReadableStream/getReader
TextDecoder: https://developer.mozilla.org/zh-CN/docs/Web/API/TextDecoder