Do not add the xhr.setRequestHeader("Access-Control-Allow-Origin:*") at the client side code.
To allow cross domain request, the server simply needs to add the Access-Control-Allow-Origin header to the response.
The value of the Access-Control-Allow-Origin should be the domain name of the request to be allowed or simply * if any origin is allowed.
Access-Control-Allow-Origin: http://domain1.com OR
Access-Control-Allow-Origin: *
If you are calling the Web API method then refer the below tested code and its working for the rest API.
Client Side Code Ajax Call:
function CallAjax() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:54118/api/values", true);
xhr.onload = function () {
console.log(xhr.responseText);
alert("sucuess");
};
xhr.send();
}
Server Side Changes :
In the Web API project you have to add the following configuration in the Web.config file. Under the system.webServer section add the following
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
</customHeaders>
</httpProtocol>
This will allow any domain to access the resource.
Hope this will be helpful :)