When making an Ajax call on the front end and calling a WCF service through Ajax, I encountered an issue with adding headers. As a result, a preflight OPTIONS request is triggered but fails due to the URL being blocked by CORS policy.
I tried adding the following code to my web.config file, but it didn't resolve the issue:
<system.webServer>
<security>
<requestFiltering>
<verbs>
<add verb="OPTIONS" allowed="true" />
<add verb="POST" allowed="true" />
<add verb="GET" allowed="true" />
<add verb="DELETE" allowed="false" />
</verbs>
</requestFiltering>
</security>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,POST,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="accept, cache-control, content-type, authorization, context" />
</customHeaders>
</httpProtocol>
</system.webServer>
$.ajax({
async: true,
type: "POST",
headers: {
'Authorization': 'Basic ' + btoa(BasicAuth),
'Context': 'Context' + btoa(ContextHeader)
},
contentType: "application/json; charset=utf-8",
data: '{"Id": "' + Id + '" }',
url: URL + "/MethodName",
success: function (result) {
response = result;
if (response == true)
Xrm.Page.data.refresh(true);
$('#msgDiv').fadeOut('slow');
},
error: function (status) {
console.log(status.status);
$('#msgDiv').fadeOut('slow');
Configurations.OnFailure(status);
}
});
The above JavaScript code was written to handle the issue.
While it works fine on HTTP calls, HTTPS calls are not successful.
An error message in the console states:
enter code here
OPTIONS 400 (Bad Request)
Access to XMLHttpRequest at '' from origin 'https://Localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status