将模式设置为“ no-cors”时通过访存访问API时出错 [英] Error when accessing API with fetch while setting mode to 'no-cors'

查看:212
本文介绍了将模式设置为“ no-cors”时通过访存访问API时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试使用JS解决获取承诺时,请根据'no-cors' Questions / 36878255 / allow-access-control-allow-origin-header-using-html5-fetch-api>此答案。但是,将模式设置为'cors'会导致:

When trying to resolve a fetch promise with JS is set the mode to 'no-cors' based on this answer. However setting the mode to 'cors' results in having:


以$ b $取值的权限b来自起源'http:// localhost:3000'的'{endpoint}'
已被CORS策略阻止:
请求的$ b上没有'Access-Control-Allow-Origin'标头$ b资源。如果不透明的响应满足您的需求,请将请求的
模式设置为 no-cors,以在禁用CORS的情况下获取资源。

Access to fetch at '{endpoint}' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

因此我在函数中编写了此代码:

So I wrote this in my function:

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
      }));
    });
  }

这将导致以下错误未捕获(承诺)语法错误:意外结束输入的输入返回response.json(),但没有其他消息。我在做什么错了?

This results in following error Uncaught (in promise) SyntaxError: Unexpected end of input for return response.json(), but with no further message. What am I doing wrong?

推荐答案


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

If an opaque response serves your needs

不是。您想查看响应。您看不到不透明的响应(这是不透明的响应的意思)。

It doesn't. You want to see the response. You can't see an opaque response (that is what opaque response means).

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

no-cors mode means that if the browser has to do anything that requires permission from CORS, it will fail silently instead of throwing an error.

因此,它是静默地未能获得响应,然后尝试将所有内容解析为JSON(这会引发不同的错误)。

So it is silently failing to get the response, then trying to parse that nothing as JSON (which throws a different error).

您需要:


  • 不使用 no-cors 模式

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

请参阅此问题,以获取有关一般CORS的更多信息

这篇关于将模式设置为“ no-cors”时通过访存访问API时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆