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

13.6k Views Asked by At

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

3

There are 3 best solutions below

2
On BEST ANSWER

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'
  }
});
0
On

I think the api you're using is the problem. I tried to make it work, but got the same error. Also tried to use axios but it's the same thing.

I tried to fetch data with Postman and it worked perfectly, so.. my guess is that the api you're trying to use does not support all origin, since the API I tried to use works perfectly with your code.

const api_url = "https://randomuser.me/api";
0
On

I was facing the same problem when running the test cases. In my test case, there was the API call and I have used the useEffect react hook for updating the state.

 useEffect(() => {
    getDetailsFromAPI("param")
}, []);

So, While running the test case, I was getting the same error

 FetchError: invalid json response body at  reason: Unexpected end of JSON input

  at ../../node_modules/node-fetch/lib/index.js:272:32

For solving this error I have mock the promise in the test case, which resolved my issue.

import fetch from 'node-fetch';

const mockJsonPromise = Promise.resolve(mydata); // 2
    const mockFetchPromise = Promise.resolve({ // 3
        json: () => mockJsonPromise,
        ok: () => true
    });
    fetch.mockImplementation(() => mockFetchPromise);