如何从API调用后返回的“ Passthrough”对象访问数据?

问题描述

我正在将带有节点获取的获取请求发送到以下URL:http://fantasy.premierleague.com/api/bootstrap-static/,以便获取一些JSON数据。在浏览器中访问URL或使用邮递员发送get-request都将返回预期的JSON数据。

但是,当我从节点发送请求时,我得到了一个我不知道如何从中提取数据的对象(如下图)。

我对节点不是很有经验,但是我之前已经成功进行了API调用。通常使用response.json()或JSON.parse(response)或response.body或response.toString()或其中的某些组合解析响应对我有用。我对缓冲区和流不熟悉,但并不自信,解决方案可能与缓冲区和流有关,但是我似乎无法弄清楚。

根据我的尝试,我会得到不同的错误和对象。我试过使用fetch和来自节点的简单http请求。

此电话:

enter image description here

返回此:

enter image description here

如果我执行JSON.parse(response),则会出现以下错误:

enter image description here

Response.body看起来像这样:

1/2

2/2

解决方法

Fetch返回响应流,如similar question的答案中所述。 您可以读取数据块,并将数据块添加到数组,然后对数据进行任何处理。一种更简单的方法是使用npm请求包。这是一个例子。

const request = require('request');
let options = {json: true};

const url = 'http://fantasy.premierleague.com/api/bootstrap-static/'
request(url,options,(error,res,body) => {
    if (error) {
        return  console.log(error)
    };

    if (!error && res.statusCode == 200) {
        console.log(body);
        // do something with JSON,using the 'body' variable
    };
});

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...