Including Cookies On A Ajax Request For Cross Domain Request Using Pure Javascript
Solution 1:
Here is an XMLHttpRequest() example that i have used for CORS with cookie credentials successfully in Chrome, FF 3.5+, Safari 4+, IE10+. If this does not work, it is probably something wrong with server configuration or browser compatibility.
// GET requestvar xhr = newXMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = 'application/json';
xhr.processData = false;
xhr.contentType = false;
xhr.onload = function() {
// Successful requestif (xhr.status == 200) {
success(xhr.response);
}
};
xhr.onerror = function() {
// Crossdomain request deniedif (xhr.status === 0) {
corsFailed(xhr.response);
}
};
xhr.crossDomain = true;
xhr.withCredentials = true;
xhr.send();
I know that safari and IE10+ require the user to allow third party cookies in their browser preferences. I don't think there is any way around this without using custom headers in place of cookies and setting the Access-Control-Allow-Headers on the server to include the custom headers. Also I believe you need Access-Control-Allow-Headers: "Content-Type".
To go back as far as IE8/9, you would need to implement a fallback to XDomainRequest(), but those do not support cookie credentials.
The processData and contentType flags may only be necessary for POST requests. I use FormData() objects when doing POSTs, not JSON.
Solution 2:
It can't be done in js, you need to modify the headers sent from the server:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:X-Requested-With, X-Prototype-Version, Content-Type, Origin, Allow
Access-Control-Allow-Methods:POST, GET, OPTIONS
Access-Control-Allow-Origin:http://yourdomainAccess-Control-Max-Age:1728000
How to add those headers, depend on which software are you using to serve pages.
Post a Comment for "Including Cookies On A Ajax Request For Cross Domain Request Using Pure Javascript"