【问题标题】:I get a CORS-Error while doing a request for a API using XHR使用 XHR 请求 API 时出现 CORS 错误
【发布时间】:2021-12-13 11:05:18
【问题描述】:

我们正在向我们的一位在线分销商提出 API 请求。 但是,我们得到了一个 CORS 错误。

CORS 政策已阻止从源“http://www.im-cmp.ch”访问“https://api.cloud.im/marketplace/eu/products”处的 XMLHttpRequest:响应预检请求未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

我们在 Postman 中完成了请求,并且成功了。我尝试将 requestHeaders 设置为与 Postman 中设置的完全相同的方式(包括隐藏的标头),但是,由于无法设置隐藏的标头,因此出现错误。

拒绝设置不安全的标头“Host”

这是客户端问题还是服务器问题?我可能错过了 requestHeader 吗?

  var xhr = new XMLHttpRequest();
  xhr.withCredentials = true;

  xhr.addEventListener("readystatechange", function() {
    if(this.readyState === 4) {
      console.log(this.responseText);
   }
  });

  xhr.open("GET", "https://api.cloud.im/marketplace/eu/products");
  xhr.setRequestHeader("X-Subscription-Key", "OUR PERSONAL SUBSCRIPTION KEY"); 
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.setRequestHeader("Authorization", "OUR BEARER TOKEN");
  //      xhr.setRequestHeader("Host", "http://www.im-cmp.ch/");
  xhr.setRequestHeader("accept", "*/*");
  //      xhr.setRequestHeader("Accept-Encoding", "gzip, deflate, br");
  //      xhr.setRequestHeader("Connection", "keep-alive");
  xhr.send();

【问题讨论】:

    标签: javascript api xmlhttprequest cors


    【解决方案1】:

    这绝对是服务器问题。

    服务器必须发送Access-Control-Allow-Origin-header:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

    此外,错误指出这发生在 preflight-request 期间,这意味着事先提出了 OPTIONS 请求,这也需要 CORS 所需的响应标头。

    该请求在 Postman 中有效,因为 CORS 是一项仅在浏览器中真正相关的功能,以保护用户。

    编辑:

    服务器允许您使用Access-Control-Allow-Headers-header 发送的请求标头也很重要:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-06
      • 2021-02-16
      • 2019-09-09
      • 2019-09-16
      • 2018-09-27
      • 2020-10-12
      • 2016-10-03
      • 2016-03-30
      相关资源
      最近更新 更多