It can be challenging to troubleshoot jQuery ajax() failures.
Sometimes they are due to Cross-Domain policy, or Cross Origin Resource Sharing (CORS).
Other times, you are misled. For example, IE10 console messages may say:
“XMLHttpRequest for http://xxxx.com/xxxx requires Cross Origin Resource Sharing (CORS).”
But the real cause would be just an authentication error.
- Use Fiddler to see what the actual server response error is.
- Use Fiddler Composer to make direct ajax calls to the api server, bypassing your own web server. If it does not work, then it is probably has nothing to do work CORS.
- If it is a real CORS issue, know what your ajax call is categorized as: simple requests or preflight requests.
- If you see your browser makes a OPTION request, then it is doing a preflight request. Nowadays, it is probably due to the fact that you are using custom headers in the call.
- Following the articles below to fix it. Basically, it is just adding the correct HTTP response headers. You can do it at the code level. Or you can do it at your web server. For IIS, you can use web.config or IIS Http Response Headers. The headers to add include:
- Access-Control-Allow-Origin – necessary for any CORS. It can be set to “*” or your domain hosting the webpage “http://xxxx.com”.
- Access-Control-Allow-Methods – necessary if you use HTTP methods other than GET, POST, or HEAD.
- Access-Control-Allow-Headers – necessary if you use custom headers when you make the ajax call.
- Access-Control-Allow-Credentials – necessary if you use credentials (i.e. cookies or HTTP Auth).
Fiddler, Browser Console