0

Axios code: result.data is empty, result has status 200.

    const axios = require('axios');

    axios.get('https://fantasy.premierleague.com/api/bootstrap-static/')
    .then(result => {
        console.log(result);
        console.log(result.data);

    })
    .catch (error=>{
        console.log(error);
    });

https code (returns JSON from API):

const https = require('https');

https.get('https://fantasy.premierleague.com/api/bootstrap-static/', (response)=>{
    let data = '';
    response.on('data', (chunk) =>{
        data += chunk;
    });
    response.on('end', ()=>{
        console.log(data);
    })
})

The fantasy API returns JSON only I believe. Can anyone let me know what I need to do to get the axios get request to return the data?

If I use a different API with the axios code, for example (https://api.chucknorris.io/jokes/random) it works fine. It seems to be something different with this API perhaps?

Gazza Knight
  • 5
  • 1
  • 5
  • The API is returning a buffer. You don't have your `Axios` code written to handle the buffer like you do in your `https.get` code. – Dshiz Oct 26 '20 at 17:07
  • @Dshiz It is returning an empty string data: ''. – Gazza Knight Oct 26 '20 at 17:30
  • yes because the response is 200 OK before receiving the large amount of data is finished, which is being sent in chunks (array buffers). – Dshiz Oct 26 '20 at 18:21

1 Answers1

0

@Gazza Knight, Problem here is the circular reference in JSON which API is returning.

and the reason why Axios is unable to process the response is that the type of the response (typeof(result)) in case of Axios is object and errors out because of cyclic reference in JSON while using the https result is returned as a 'string' (typeof(data)) in case of https. Hence, the https is writing the result correctly and Axios fail.

I hope the above explanation helps.

Hemant Kumar
  • 186
  • 6
  • Thank you, where is the circular reference? I am trying to understand how they work. – Gazza Knight Oct 26 '20 at 17:55
  • Cyclic reference is when an object tries to refer to itself. Here are a few helping links https://stackoverflow.com/questions/1493453/example-of-a-circular-reference-in-javascript#:~:text=Here%20the%20function%20saved%20in,referenced%20from%20the%20functions%20scope. https://stackoverflow.com/questions/15312529/resolve-circular-references-from-json-object – Hemant Kumar Oct 27 '20 at 02:29