Search code examples
javascriptnode.jsfetch-apinode-fetch

node-fetch help - getting FetchError: invalid json response > body at <url> reason: > Unexpected end of JSON input


I am new to node.js and APIs so I am hoping someone can help! I am trying to use node-fetch to get JSON data from the fantasy premier league API. I have successfully done this in the client, but from my node.js server file I keep getting the error:

UnhandledPromiseRejectionWarning: FetchError: invalid json response body at https://fantasy.premierleague.com/api/entry/3/ reason: Unexpected end of JSON input

The response itself has a status of 200, but the size is 0 so it is not returning any data. I know it should work, as the JSON is plainly visible when you visit the url and I have got fetch to work in the client-side code.

Here is the code I am using:

const fetch = require('node-fetch');

async function fetchEntry() {
    const api_url = 'https://fantasy.premierleague.com/api/entry/3/';
    const fetchEntry_response = await fetch(api_url);
    const json = await fetchEntry_response.json();
    console.log("json: " + JSON.stringify(json));
};

fetchEntry();

Note: On the client-side code I got a CORS error so needed to use a proxy (https://thingproxy.freeboard.io/fetch/https://fantasy.premierleague.com/api/entry/3/) to get it to work. I'm not sure if this is relevant?

Any help would be greatly appreciated!

Joe


Solution

  • Don't ask me why but adding a 'User-Agent' header seems to fix it:

    const response = await fetch(URL, {
      headers: {
        'User-Agent': 'ANYTHING_WILL_WORK_HERE'
      }
    });