0

I am getting this error when trying to call a REST api from Javascript using XMLHttpRequest object. The code is inside a html file on my local disk.

Failed to load https://<>: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Referred to this link and tried setting the header Access-Control-Allow-Origin but still getting the same error.

var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://<<url>>", false);
xhttp.setRequestHeader('Access-Control-Allow-Origin', '*');
xhttp.setRequestHeader('Content-type', 'application/json'); 
xhttp.setRequestHeader('Authorization', 'Basic ' + btoa(username + ':' + password));
xhttp.send();
stech
  • 675
  • 2
  • 9
  • 22
  • 3
    Your server needs to send the `'Access-Control-Allow-Origin'` header, not the client – user184994 Dec 23 '17 at 08:41
  • Access Control header should be present in the api you are trying to call. – Prasanna Venkatesh Dec 23 '17 at 08:43
  • If the API doesn't send `Access-Control-Allow-Origin`, it's not intended to be used from clients, you need to call it from the server. – Barmar Dec 23 '17 at 09:25
  • 1
    Since it requires authorization, doing it in the client means that the user can see the credentials. That's why it can only be used from the server, so these are hidden from the user. – Barmar Dec 23 '17 at 09:26
  • @user184994: If the server needs to send it, then how does it work with C# client making calls to the same server? – stech Dec 24 '17 at 09:42

0 Answers0