CORS ajax requests and responses gotchas

When making cross-domain ajax calls to an api, your api server must return a status code of 200 in order to see your custom reponse object. This is a hack since browsers don’t handle CORS errors (status codes other than 2XX). So, remember to do that and just embed a http_status_code property on your repsonse if your client/ javascript application needs that. I include it just because it is a nice to have. This means that in your js code for ajax calls, everything will get routed to the success callback function (since it is always a 2XX response); no error callback is needed.

Also, when developing locally using a self-signed certificate on your api server, Google Chrome seems to not accept the preflight Options after a few minutes. As in, if you do a PUT or DELETE, it will work initially, but after a few minutes, the OPTIONS request hangs at the “(pending)” stage.

I figured out this was the case after searching around and found http://stackoverflow.com/questions/14492686/cors-request-fails-in-chrome-only-if-has-headers, which led to this bug: https://code.google.com/p/chromium/issues/detail?id=96007.

The way around this is to start Chrome with web security disabled: google-chrome –disable-web-security (be sure to shut down ALL currently-used Chrome instances, and then issue the command. Otherwise, Chrome will start like normal and ignore the disable-web-security flag). This should only be done while testing and debugging your app locally on your VM. When it comes time for production, the fact that you have a valid certificate for your https api server, should make this a moot point.

Interesting to note that Firefox does not have a problem with CORS and self-signed certs.

Your email address will not be published. Required fields are marked *

*