Troubleshoot jQuery ajax() CORS

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.

Tips:

  1. Use Fiddler to see what the actual server response error is.
  2. 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.
  3. If it is a real CORS issue, know what your ajax call is categorized as: simple requests or preflight requests.
  4. 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.
  5. 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).

Tools:

Fiddler, Browser Console

Reference:

http://techblog.constantcontact.com/software-development/using-cors-for-cross-domain-ajax-requests/

https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s