【问题标题】:React fetch has error fetch was blocked by CORS policy [duplicate]React fetch 有错误 fetch 被 CORS 策略阻止 [重复]
【发布时间】:2019-04-12 11:17:29
【问题描述】:

我尝试让登录按钮单击调用 fetch REST 调用。

但是,问题是提取失败,并在 Javascript 控制台中显示此错误消息。

// 从源获取的访问已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头 // 如果不透明满足您的需要,请将请求模式设置为“no-cors”以获取禁用 CORS 的资源。 // 异常获取失败。

为什么会发生这种情况,为什么我不能通过 React 中的按钮单击调用 REST 调用?

私有句柄Login = () => {

    console.log("button submit");

    // Access to fetch from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
    // If an opaque serves your need set the requests mode to 'no-cors' to fetch the resource with CORS disabled.
    // Exception Failed to Fetch.
    fetch('https://gturnquist-quoters.cfapps.io/api/random')
    .then((res) => {
        if (res.status >= 400) {
            throw new Error("Bad response from server");
        }
        return res.json();
    })
    .then((stories) => {
        console.log(stories);
    });


    this.props.login(this.state);


}

【问题讨论】:

标签: reactjs fetch


【解决方案1】:

您尝试调用的 API 不允许通过 AJAX 从浏览器调用。它需要设置特定的 header 来指示允许哪些 ajax 请求。

更多:https://gturnquist-quoters.cfapps.io/api/random

【讨论】:

  • 你确定你在“More here”之后发布了正确的链接吗?
猜你喜欢
  • 2023-01-14
  • 2021-03-18
  • 2020-11-15
  • 2021-12-25
  • 2020-07-03
  • 2021-07-27
  • 2021-01-23
  • 1970-01-01
  • 2022-07-16
相关资源
最近更新 更多