node-fetch 帮助 - 获取 FetchError: invalid json response > body at <url> 原因:> JSON 输入意外结束

joe*_*luk 2 javascript node.js fetch-api node-fetch

我是 Node.js 和 API 的新手,所以我希望有人能提供帮助!我正在尝试使用 node-fetch 从幻想英超联赛 API 获取 JSON 数据。我已在客户端中成功完成此操作,但从我的 node.js 服务器文件中我不断收到错误:

UnhandledPromiseRejectionWarning:FetchError: https://fantasy.premierleague.com/api/entry/3/处的 json 响应正文无效原因:JSON 输入意外结束

响应本身的状态为 200,但大小为 0,因此它不返回任何数据。我知道它应该可以工作,因为当您访问 url 时 JSON 是清晰可见的,并且我已经可以在客户端代码中使用 fetch 了。

这是我正在使用的代码:

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();
Run Code Online (Sandbox Code Playgroud)

注意:在客户端代码上,我遇到了 CORS 错误,因此需要使用代理(https://thingproxy.freeboard.io/fetch/https://fantasy.premierleague.com/api/entry/3/)让它发挥作用。我不确定这是否相关?

任何帮助将不胜感激!

小智 5

不要问我为什么,但添加“User-Agent”标头似乎可以修复它:

const response = await fetch(URL, {
  headers: {
    'User-Agent': 'ANYTHING_WILL_WORK_HERE'
  }
});
Run Code Online (Sandbox Code Playgroud)