如何从“直通"访问数据?API调用后返回的对象? [英] How to access data from "Passthrough" object returned after API call?

查看:55
本文介绍了如何从“直通"访问数据?API调用后返回的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向以下网址发送带有节点获取的获取请求:

返回此:

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

Response.body看起来像这样:

解决方案

Fetch返回响应流,如http://fantasy.premierleague.com/api/bootstrap-static/ in order to get back some JSON-data. Accessing the URL in the browser, or sending a get-request with postman both returns the expected JSON data.

However, when i send the request from node, I get back an object that I do not know how to extract the data from (pics below).

I am not very experienced with node but I have made successful API calls before. Usually parsing the response with response.json() or JSON.parse(response) or response.body or response.toString() or some combinations of those have worked for me. I am half familiar with buffers and streams, but not confident and the solution might be related to those, however I cannot seem to figure it out.

I get som different errors and objects depending on what I try. I have tried using fetch and just plain http requests from node.

This call:

Returns this:

If I do JSON.parse(response) i get the following error:

Response.body looks like this:

解决方案

Fetch returns a response stream as mentioned here in the answer to a similar question You can read data in chunks and add the chunk to array and then do whatever you need to do with that data. A simpler approach would be to use npm request package. Here's an example.

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

这篇关于如何从“直通"访问数据?API调用后返回的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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