我正在尝试显示从 fastAPI 收到的 StreamingResponse。我通过发送 axios post 请求得到响应。我成功地逐块获取响应,但我似乎无法在每次块到达时对它们进行 console.log()
这是我的帖子请求:
async sendSelectedDocumentList(
projectId: number,
selectedDocuments: string[],
) {
return await axios.post(
`/api/projects/${projectId}/thematiques/answer`,
{
document_names: selectedDocuments,
},
{
params: { user_id: this.userId },
},
);
}
我最终成功地将我的 axios post 请求转换为使用 fertch API 的 post 请求。然后我在response.body上使用了getReader()方法:
async sendSelectedDocumentList(
projectId: number,
selectedDocuments: string[],
) {
const data = {
document_names: selectedDocuments,
};
try {
const token = localStorage.getItem('access_token');
const response = await fetch(
`/api/projects/${projectId}/thematiques/answer?user_id=${this.userId}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(data),
},
);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const reader = response.body?.getReader();
if (reader) {
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log('Chunk:', new TextDecoder().decode(value));
}
} else {
throw new Error('Response body is null or undefined');
}
} catch (error) {
console.error(error);
}
}