Breaking the cross-domain barrier in AJAX and Backbone
XHRfield withCrendentials, Cookies, JSONP, CORS and all those stuff... what to do for the needed scenario. It is really a mess out there and I clarified for myself all of this and put it in a nice little table so I remember well :
Challenge 1. You want cookies passed on AJAX request on HTTPS to a different domains.
Popular solution 1. In backbone.js, you can edit this function and add crossDomain = true and xhrFields's withCrendentials:true
*However* browser will now reject content. You will see Content-Length non-zero, but empty response. The response is cancelled by the browser. So this solution does *not* work :
Backbone.sync = function(method, model, options) {
if (!options.crossDomain) {
options.crossDomain = true;
}
if (!options.xhrFields) {
options.xhrFields = {withCredentials:true};
}
(...)
With express in node.js server
access-control-allow-origin: * (same)
access-control-allow-headers: Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version (same)
access-control-allow-methods: GET, POST (same)
access-control-expose-headers: X-Api-Version, X-Request-Id, X-Response-Time (same)
| [GET, dataType: json] xhrFields: withCrendential:true crossDomains: true | [GET, dataType: jsonp] xhrFields: withCrendential:true crossDomains: true | [POST] xhrFields: withCrendential:true crossDomains: true | ||
|---|---|---|---|---|
| Firefox 13 | With cookies : blocked No cookies : pass | |||
| Firefox 15 | With cookies : blocked No cookies : pass | |||
| Firefox 22 | ||||
| Chrome 20 | With cookies : blocked No cookies : pass | |||
| Internet Explorer 9 | blocked |
Troubleshooting 101
HTTPS Certificates
Having HTTPS certificate errors in dev mode and you want to test with an accepted certificate?
Solution: Test on Windows with Fiddler2, which will act as a proxy and replace the HTTPS certificate with a valid one http://fiddler2.com/
Recent Comments