获取 API - iTunes 搜索 API 错误

fetch api - itunes search api error

本文关键字:API 错误 搜索 获取 iTunes      更新时间:2023-09-26

我正在尝试使用iTunes搜索API和fetch api。

当我尝试以下内容时,我在控制台中得到响应。

  fetch('https://api.github.com/users/bootstrap').then(function(response) {
    return response.json();
  }).then(function(j) {
    console.log(j);
  });

但是当我尝试时

  fetch('https://itunes.apple.com/search?term=jack+johnson',{mode: 'no-cors'}).then(function(response) {
    return response.json();
  }).then(function(a) {
    console.log(a);
  });

我收到错误Uncaught (in promise) SyntaxError: Unexpected end of input(…)

是否可以以这种方式获取iTunes API数据?

谢谢戴夫

来自 MDN (https://developer.mozilla.org/en-US/docs/Web/API/Request/mode):

no-cors — 防止方法不是 HEAD、GET 以外的任何方法 或发布。如果任何 ServiceWorker 拦截了这些请求,他们可能不会 添加或覆盖除这些标头之外的任何标头。此外,JavaScript可能无法访问生成的响应的任何属性。这确保了 服务工作者不会影响 Web 的语义,并且 防止因数据泄露而引起的安全和隐私问题 域。

这就是为什么您在 JS 中得到空响应和解析空字符串时出现 JSON 错误的原因 JSON.parse("") .