Dojo FAQ: How do I use CORS with Dojo?

By on January 15, 2014 1:11 pm

In web browsers that support Cross-Origin Resource Sharing (CORS) via XMLHttpRequest objects, Dojo’s XHR mechanism can make cross-domain requests out of the box.

Because of the same-origin policy of XMLHttpRequest, Dojo has long supported various methods of loading resources across domains – dojo/io/script and dojo/io/frame; dojo/request/script and dojo/request/iframe in recent versions (1.8+). However, modern web browsers have relaxed the same-origin policy to allow developers to perform cross-domain requests with one caveat: the server must allow cross-domain requests by responding to the request with the Access-Control-Allow-Origin header set to a value that includes the domain of the requesting code (or * to match all domains). If the browser supports CORS, it will complete the request as if it were a same-domain request. This feature is also available in Dojo:

require([ "dojo/request" ], function (request) {
    request("http://other.domain/resource");
});

While Dojo’s XHR mechanism supports CORS out of the box, it sets the X-Requested-With header by default, which will result in a pre-flighted request that may not be desirable. For requests that don’t include sensitive data or cause side effects, you can prevent the pre-flighted request by clearing the X-Requested-With header:

require([ "dojo/request" ], function (request) {
    request("http://other.domain/resource", {
        headers: {
            "X-Requested-With": null
        }
    });
});

If you need to send HTTP authentication credentials or cookies with your cross-domain request, simply setting the withCredentials option to true will allow the browser’s XMLHttpRequest to send that information:

require([ "dojo/request" ], function (request) {
    request("http://other.domain/resource", {
        headers: {
            "X-Requested-With": null
        },
        withCredentials: true
    });
});