首页 文章

在将模式设置为'no-cors' [重复]时使用提取访问API时出错

提问于
浏览
-1

这个问题在这里已有答案:

当尝试使用JS解析获取承诺时,将模式设置为'no-core'基于this answer . 但是,将模式设置为'corse'会导致:

对来自'http:// localhost:3000'的''的获取访问已被CORS策略阻止:请求的资源上没有'Access-Control-Allow-Origin'标头 . 如果不透明响应满足您的需要,请将请求的模式设置为“no-cors”以获取禁用CORS的资源 .

所以我在我的函数中写了这个:

search() {
    return fetch(`${baselink}${summonerEndpoint}${summoner}${apikey}`, {mode: 'no-cors'}).then(response => {
      return response.json()
    }).then(jsonResponse => {
      console.log(jsonResponse);
      if (!jsonResponse.info) {
        return [];
      }
      return jsonResponse.info.items.map(info => ({
        id: info.id,
        accountId: info.accountId,
        name: info.name,
        profileIconId: info.profileIconId,
        revisionDate: info.revisionDate,
        summonerLevel: info.summonerLevel
      }));
    });
  }

这导致 return response.json() 的错误 Uncaught (in promise) SyntaxError: Unexpected end of input ,但没有进一步的消息 . 我究竟做错了什么?

1 回答

  • 1

    如果不透明的响应满足您的需求

    它没有 . 你想看到响应 . 您无法看到不透明的响应(这是不透明响应的含义) .

    no-cors 模式意味着如果浏览器必须执行任何需要CORS许可的操作,它将以静默方式失败而不是抛出错误 .

    所以它默默无法获得响应,然后尝试将其解析为JSON(抛出不同的错误) .

    你需要:

    • 不使用 no-cors 模式

    • 使用CORS授予权限的服务器

    this question for more information about CORS in general .

相关问题