response.body.getReader不是函数 [英] response.body.getReader is not a function

查看:285
本文介绍了response.body.getReader不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用访存调用网络api.我想将响应读取为流,但是当我在response.body上调用getReader()时,出现错误:"TypeError:response.body.getReader不是函数".

I'm making a call to a web api using fetch. I want to read the response as a stream however when I call getReader() on response.body I get the error: "TypeError: response.body.getReader is not a function".

  const fetch = require("node-fetch");
  let response = await fetch(url);
  let reader = response.body.getReader();

推荐答案

fetch的JavaScript实现与节点node-fetch的JavaScript实现之间有区别.

There is a difference between the javascript implementation of fetch and the one of node node-fetch.

您可以尝试以下操作:

const fetch = require('node-fetch');

fetch(url)
    .then(response => response.body)
    .then(res => res.on('readable', () => {
    let chunk;
    while (null !== (chunk = res.read())) {
        console.log(chunk.toString());
    }
}))
.catch(err => console.log(err));

主体返回Node本机可读流,您可以使用方便命名的read()方法读取该流.

The body returns a Node native readable stream, which you can read using the conveniently named read() method.

您可以在此处下找到有关差异的更多信息.更具体地说:

You can find more about the differences under here. More specifically:

为方便起见,res.bodyNode.js可读流,因此可以独立处理解码.

For convenience, res.body is a Node.js Readable stream, so decoding can be handled independently.

希望有帮助!

这篇关于response.body.getReader不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆