Intro
I recently built a recipe app using a third-party API that supports CORS. Things were going along well, it was working well on all of the latest browsers (Chrome 28, Firefox 23, IE10). But when I started testing on Internet Explorer 8/9, I wasn’t getting any sort of response from the back-end. I immediately panicked, added a console.log fix and started placing breakpoints on my ajax statements to see what sort of request I was getting back.
The Problem
I came across a “No Transport” error being thrown by jQuery’s ajax. I had never heard of it, so after some searching on msdn and stackoverflow I came across a few suggestions to “quickly” fix this. Such as for jQuery 1.5+:
jQuery.support.cors = true;
After a couple other attempts, I accepted the fact that I will have to use IE’s XDomainRequest. To my astoundment, jQuery doesn’t natively support XDomainRequest.
Extending jQuery ajax to support XDomainRequest
Before I started implementing it, I came across a couple library’s on github and gists, but my journey to find the solution eventually lead me to @MoonScript’s jQuery-ajaxTransport-XDomainRequest repo on github. The examples provided worked like a charm on IE8, 9 and it looked like a reputable project, so I added a couple more tests to my outgoing ajax requests, then dropped in MoonScript’s library to my project. Problem solved. No need to reinvent the wheel here.
I couldn’t help myself so I’ll leave you with this:
Conclusion
Good news everybody, IE10 supports CORS using XMLHttpRequest. No more extending jQuery to support XDomainRequest.
XDomainRequest Gotchas
Some other things I came across that will save you a headache.
- The server protocol must be the same as the calling page protocol.
- This means you can’t make requests from file:// to http ://, http to https, or https to http (don’t ever do the latter)
- I found this the hard way by trying to run my code locally without first spinning up my localhost server.
- Only “text/plain” is supported for the request’s “Content Type header
- No custom headers can be added to the request
Resources:
Oh man, I can not believe that I can not send custom headers in the request ;( Do you know any workaround for this?
Oh man, I can not believe I can not send custom headers in the request for IE9 and IE8. Do you know about any workaround solution?