0

I have some JavaScript that looks like:

$(document).ready(function() {
    var csrftoken = getCookie();
    $.ajaxSetup({      
        cache       : false,    
        data        : null,      
        beforeSend  : function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }

    });
}); 

And I have some JavaScript that looks like:

jQuery.ajax({
    external : true,
    type     : "GET",
    url      : url,
    datatype : "json",
    async    : true,
    error    : function( jqxhr, textStatus, errorThrown ) {
        alert("error");
        console.log(url);
        console.log(jqxhr);
        console.log(textStatus);
        console.log(errorThrown);
    },
    success  : function(data) {
        if (data.status == "OK") {
            // do stuff;
        } else {
            alert("Error: Google Directions API returned the status code " + data.status);
        }
    }   
});

url is an external url. It asks Google Directions for some directions. If I just go there with my browser I get some nice json.

But if the code above executes I get a 405 and the following message "Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin"

I have 'django.middleware.csrf.CsrfViewMiddleware' installed.

I'm doing a lot of Googling to find out how to fix this but so far I can't find the problem.

My question is: How do I get this to work?

I'll keep looking for an answer in the meantime...

Stuff I've tried (in various combinations):

  • jsonp instead of json
  • crossDomain: true

I have verified that the line xhr.setRequestHeader("X-CSRFToken", csrftoken); is not called for the offending url

mariodev
  • 13,119
  • 3
  • 45
  • 56
Sheena
  • 13,328
  • 11
  • 65
  • 103

1 Answers1

0

Check your settings file for the correct values, like:

CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = ('127.0.0.1:8000', )
mariodev
  • 13,119
  • 3
  • 45
  • 56
  • @Sheena Can you put the app on github to debug it, since it turns into a guessing game.. – mariodev Nov 21 '13 at 13:02
  • Afraid not, it's not mine... In the meantime I just made the page that does the offending request server side and that works but it is a bit of a hack – Sheena Nov 22 '13 at 05:45