1

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

Tobbenda
  • 63
  • 2
  • 8
  • Does this answer your question? [Using Fetch API to Access JSON](https://stackoverflow.com/questions/37663674/using-fetch-api-to-access-json) – basic Oct 10 '20 at 18:50
  • Unfortunately, no. It returns a 'UnhandledPromiseRejectionWarning' error complaining about 'invalid json response body' and 'Unexpected end of JSON input'. In postman however, the 'Content-Type' header is in fact 'Application/json'. Thanks anyways. – Tobbenda Oct 10 '20 at 18:57

1 Answers1

3

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