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:
1
2
3
|
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:
1
2
3
4
5
6
7
|
require([
"dojo/request"
],
function
(request) {
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’sXMLHttpRequest
to send that information:
1
2
3
4
5
6
7
8
|
require([
"dojo/request"
],
function
(request) {
headers: {
"X-Requested-With"
:
null
},
withCredentials:
true
});
});
|