Troubles Overcome

Notes on Web Development

Your firewall can cause CORS preflight to fail.

# #

I can’t tell you exactly why CORS preflight requests are failing in your case. There are many things you can try, but I will tell you this: if you’ve tried a few things and it won’t work, ask yourself whether you’re behind a firewall controlled by someone else. If you are, read the rest of this post.

Setting CORS Response Headers with PHP

# #

Now and then, when using cross-domain XHR requests for this or that, preflight will fail with the error: “Access-Control-Allow-Origin does not allow origin: [whatever] …”. This is due to the server being misconfigured in most instances. But it’s worth noting that you can override Apache’s headers with PHP—although this will be ugly if you’re not using PHP to process the cross-domain request and return material.

CORS Requests from Localhost & Cloudflare

# #

So here’s the situation: you have a website running Apache (and perhaps nginx, but in that case only as a reverse proxy), and you want to secure the site and leverage a CDN to reduce load times, and you chose Cloudflare. And now you want to host server-side code on the same webserver, under the same domian, which processes ajax requests (or other XHRs) from a mobile app. Your options are essentially two if you want to keep things light: JSONP or CORS. Since JSONP is quickly receding into the mists of ancient history, to be dropped in favor of CORS, you should use CORS.

The trouble is that if you try it, given the situation above, it will never work. Cloudflare is happy to allow CORS requests from, say, to your server, but not from http://localhost[:xxxx] to the server. Why? I have no idea. But if you’re in the above situation, trying to have an app issue CORS requests from the device to the server, not using Cloudflare is apparently a solution.

Notice: this is not just the old Chrome bug, as indicated by two pieces of evidence. First: it’s true in other browsers; the requests are “canceled” in Chrome, and return a 301 in FireFox (curiously). Second: a cross-domain XHR request issued from Chrome, which is canceled when directed to a server with Cloudflare, will succeed when directed to a server without Cloudflare. (I’ve tested this.) So, it does look as though* Cloudflare will not issue the CORS headers for a request with an origin of http://localhost. Issuing *the same* request from another web server (as indicated above) will work fine.

*True, the configurations of these two servers were different, but only subtly, aside from Cloudflare.