Search code examples
javascriptnode.jsjsonfetchpass-through

How to access data from "Passthrough" object returned after API call?


I am sending a fetch request with node-fetch to the following url: 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: enter image description here

Returns this: enter image description here

If I do JSON.parse(response) i get the following error: enter image description here

Response.body looks like this: 1/2 2/2


Solution

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