Recently I've worked on the application making cross-domain ajax calls with YUI. While YUI offers io-xdr module for making cross-domain requests via Flash transport, it seems to me quite unnatural as it leads to unnecessary complexity. Moreover, io-xdr was marked deprecated several months ago without explicit mentioning the preferred way. An obvious alternative is using XMLHttpRequest as a transport for cross-domain requests. However, it has some limitations and undocumented pitfalls that I'd like to review in this post.
Cross-Domain request using XMLHttpRequest
Cross-domain requests can be sent using a common XMLHttpRequest object. The only requirement is that the server must be configured to properly handle those requests. Specifically, it should set the Access-Control-Allow-Origin response header according to Cross-Origin Resource Sharing specification. For more details and good tutorials you can refer to Mozilla documentation.
YUI IO Utility
When I've tried to create a cross-domain request with YUI IO Utility, I've got the following JavaScript error:
OPTIONS https://request-url Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers. io-base.js:731 XMLHttpRequest cannot load https://request-url. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.
Apparently, YUI IO Utility sends a preflight OPTIONS request first due to the X-Requested-With header. It looks like a recurring bug in YUI that seems to have been fixed. Anyway there is a guaranteed way to resolve this issue as you can unset headers since YUI 3.3.0. An example:
Y.io(remote_resource_uri, { headers: { 'X-Requested-With': 'disable' } });
YUI Datasource IO
As soon as you've found the above solution, it's easy to make Datasource.IO working with cross-domain requests. You just need to provide the optional ioConfig parameter to the datasource constructor:
var ds = new Y.DataSource.IO({ source: remote_resource_uri, ioConfig: { headers: { 'X-Requested-With': 'disable' } } });
Comments
Post a Comment