【问题标题】:Identify fetch error as due to CORS issue识别由于 CORS 问题导致的提取错误
【发布时间】:2023-04-10 10:23:01
【问题描述】:

我想知道资源加载是否由于 CORS 错误而失败,因为我想使用我在服务器上设置的代理。除非绝对必要,否则我不想使用我的代理,因为会通过它传输大量额外数据。

当我这样做时:

fetch("https://some-resource-somewhere-that-a-user-has-provided")
    .then(response => {
      // do stuff with the response
    }).catch((e) => {
       // e === Error("TypeError: Failed to fetch")
    });

该错误非常无用(至少在 chrome 上),但控制台中有大红色文本为我提供了我需要的信息!

我该怎么说

TypeError: 获取失败

是 CORS 问题,还是其他负载问题?

【问题讨论】:

  • 您是否尝试过浏览器以外的其他东西,例如邮递员,检查 api 是否按计划工作?
  • 看看这是否有帮助:stackoverflow.com/questions/19325314/…
  • 如果浏览器由于与 CORS 相关的原因阻止您的前端代码访问响应,则浏览器将在 devtools 控制台中记录明确提及 CORS 的特定错误消息。因此,如果您在 devtools 控制台中没有看到任何提到 CORS 的错误消息,那么代码失败的原因与 CORS 无关。相反,它是网络问题、SSL 问题或其他问题。
  • @sideshowbarker - 请认真阅读整个问题!
  • @Darran Sweeney - 是的,端点可以工作,只是没有 Access-Control-Allow-Origin: * 响应标头。

标签: javascript error-handling cors fetch


【解决方案1】:

我想出了以下解决方案:

var xhttp = new XMLHttpRequest();
xhttp.onerror = function () {
  if (this.status === undefined || this.status === 0) {
    console.log('error due to CORS issue');
  } else {
    console.log("** An error occurred during the transaction", this);
  }

};
xhttp.open("GET", "https://stackoverflow.com", true);
xhttp.send();

【讨论】:

  • 太棒了,不过你能解释一下原因吗,你怎么知道这将永远是一个 CORs 问题?
  • 在 CORS 中,执行点是客户端。所以我的假设是不会有任何可用的状态。
猜你喜欢
  • 1970-01-01
  • 2014-10-23
  • 1970-01-01
  • 2021-05-03
  • 2010-12-20
  • 2013-03-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-17
相关资源
最近更新 更多