简体   繁体   中英

I get a CORS-Error while doing a request for a API using XHR

We're making a request for an API from one of our online-distributors. However, we get a CORS-Error.

Access to XMLHttpRequest at 'https://api.cloud.im/marketplace/eu/products' from origin 'http://www.im-cmp.ch' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

We did the request in Postman and it worked. I tried to set the requestHeaders the exact same way they are set in Postman (including the hidden headers), however, there is an Error since the hidden headers can't be set.

Refused to set unsafe header "Host"

Is this a client or a server problem? Am I maybe missing a 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();

This is definitely a server problem.

The server has to send the Access-Control-Allow-Origin -header: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS .

Also, the error states that this happened during a preflight -request, meaning there was a OPTIONS request made beforehand, which would also need the response-header(s) needed for CORS.

The request works in Postman, since CORS is a feature only really relevant in browsers, to protect users.

Edit:

Also it is important that the server allows the request-headers you are sending using the Access-Control-Allow-Headers -header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM