【发布时间】:2020-03-16 14:55:11
【问题描述】:
我在 React 中有一个客户端应用程序,在 Node 中有一个服务器(使用 Express)。 在服务器端,我有一个类似以下的端点(不是真正的端点,只是我在做什么的一个想法):
function endpoint(req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain',
'Transfer-Encoding': 'chunked'
});
for(x < 1000){
res.write(some_string + '\n');
wait(a_couple_of_seconds); // just to make process slower for testing purposes
}
res.end();
}
这是完美的,我的意思是,当我调用这个端点时,我会收到包含所有 1.000 行的整个流。
问题是我无法设法按块获取这些数据(对于每个“写入”或一堆“写入”),以便在我收到它们后立即在前端显示..(想想在我从端点调用中获取行后立即显示行的表)
在前端,我使用 Axios 调用 API,代码如下:
async function getDataFromStream(_data): Promise<any> {
const { data, headers } = await Axios({
url: `http://the.api.url/endpoint`,
method: 'GET',
responseType: 'stream',
timeout: 0,
});
// this next line doesn't work. it says that 'on' is not a function
data.on('data', chunk => console.log('chunk', chunk));
// data has actually the whole response data (all the rows)
return Promise.resolve();
}
问题是 Axios 调用在调用服务器上的“res.end()”之后返回整个数据对象,但我需要在服务器开始发送带有行的块时立即获取数据(在每次 res.write 或服务器认为已准备好发送一些块时)。
我也尝试过不使用 await 并在 axios 调用的 'then()' 处获取 promise 的值,但这是相同的行为,'data' 值与所有 '一旦服务器执行 'res.end()'
那么,我在这里做错了什么?也许这对于 Axios 或 Node 是不可能的,我应该使用 websockets 之类的东西来解决它。 任何帮助都将不胜感激,因为我阅读了很多但还没有找到可行的解决方案。
【问题讨论】: