Access-Control-Allow-Origin in Django app when accessed with Phonegap

Sascuash picture Sascuash · Mar 12, 2014 · Viewed 95.5k times · Source

I'm developing a Phonegap app for my Django based app, but when trying to make Ajax calls I get this error:

XMLHttpRequest cannot load http://domain.herokuapp.com/getcsrf/?tags=jquery%2Cjavascript&tagmode=any&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 

How can I make it so my Django app allows cross origin for some urls?

Here's my Ajax code:

get: function() {
    $.getJSON("http://domain.herokuapp.com/getcsrf/",
    {
        tags: "jquery,javascript",
        tagmode: "any",
        format: "json"
    },
    function(data) {
        $.each(data.items, function(item){
            console.log(item);
            });
    });
}

Answer

stormlifter picture stormlifter · Mar 12, 2014

Django by default does not provide the headers necessary to provide cross origin. The easiest way would be to just use this Django app that handles it for you: https://github.com/ottoyiu/django-cors-headers

You can then set whichever domains you want white listed using the settings

CORS_ORIGIN_WHITELIST = (
    'google.com',
    'hostname.example.com'
)

to support allowing all, just use the setting... CORS_ALLOW_ALL_ORIGINS = True and then do any filtering of the request in middleware or in the view.