Javascript 使用fetch在请求结束之前获取HTTP结果
我正在尝试使用无人机1.0服务器的Javascript 使用fetch在请求结束之前获取HTTP结果,javascript,axios,fetch,Javascript,Axios,Fetch,我正在尝试使用无人机1.0服务器的/api/stream端点。此端点保持HTTP连接打开,并仅流式传输新的即将发生的事件以通知使用者事件 我尝试使用javascript获取API处理这段代码 await fetch("https://drone.company.com/api/stream/", { headers }) .then(function(response) { return response.text(); }) .then(fun
/api/stream
端点。此端点保持HTTP连接打开,并仅流式传输新的即将发生的事件以通知使用者事件
我尝试使用javascript获取API处理这段代码
await fetch("https://drone.company.com/api/stream/", {
headers
})
.then(function(response) {
return response.text();
})
.then(function(data) {
console.log(data);
});
这段代码运行良好,但是请求结束后总是调用then
回调
有没有一种方法可以让我在处理请求时获取接收到的正文流?您可以从
response.getReader()
中读取
let response = await fetch("https://drone.company.com/api/stream/", {
headers
});
const reader = response.body.getReader();
while(true) {
const {done, value} = await reader.read();
if (done) {
break;
}
const text = new TextDecoder("utf-8").decode(value);
console.log(`Received ${text}`)
}
我们需要使用textdecker
,因为value
包含uint8数组数据而不是文本。通过IE。fetch
基于不,这不是我刚才意识到我的示例是多么基本的。。。但我也尝试了来自axios的requestType流,它对我的用例也不起作用。我真的需要使用套接字吗?我不确定你会使用什么,我只知道
fetch
不适合使用-尽管套接字看起来是正确的