Configuring IIS to Allow CORS Requests (Fixing AJAX Calls to an API)
The problem: sending AJAX requests from an HTML5 application running on my local machine to an API hosted under IIS (Google Cloud).
The Setup
Client: HTML/JS app on local machine
Server: API under IIS (Google Cloud)
The request looked like this:
$.post({
url: apiEndpoint + "Init",
contentType: "application/json; charset=utf-8",
data: data,
success: function (response) {
logResponse("API response [Init]", response.d);
},
error: function (xhr, status, error) {
logResponse('Fail to call init API', data);
}
});
The error looked like this:
Originally, there was crossDomain: true in the AJAX request, but it didn’t help.
There were also crossdomain.xml and clientaccesspolicy.xml on the server — also useless for this case.
What I Tried (And Why It Didn’t Help)
I found many client-side “solutions” for AJAX, but they did not solve the issue.
1) Adding headers in AJAX
headers: {
'Access-Control-Allow-Origin': '*'
}
This approach is ineffective because CORS is controlled by the server response headers, not by what the client sends.
2) Adding only Access-Control-Allow-Origin on server
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
After that change, the browser error changed to this:
The Fix
So I added:
<add name="Access-Control-Allow-Headers" value="Content-Type" />
to the same <system.webServer> → <httpProtocol> → <customHeaders> section.
Conclusion
No need to add anything to the AJAX request — no custom headers and not even crossDomain: true.
Just add the following to web.config under <system.webServer>:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
That’s it. End of story.
Unfortunately — the long story :-\
Comments
Post a Comment