response.body.getReader is not a function

随声附和 提交于 2019-12-24 13:01:09

问题


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();

回答1:


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

You can try the following:

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));

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:

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

Hope it helps !



来源:https://stackoverflow.com/questions/57664058/response-body-getreader-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!