CORS django 'Access-Control-Allow-Origin'

Nathan picture Nathan · Feb 20, 2016 · Viewed 33.2k times · Source

I was trying to get a CORS request working. With the following JS code I get this error: XMLHttpRequest cannot load http://localhost:65491/?token=u80h9kil9kjuu02539buak4r6n&user=~me. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:50303' is therefore not allowed access.

this is the JS code:

$.ajax({
     url: "http://localhost:60906/",
     data: {token : 'u80h9kil9kjuu02539buak4r6n', user : '~me'},
     type: "GET",
     crossDomain: true,
     success: function( response ) {
         alert('Success!' + response);
         var context = response;
        }
  });

When I look at the network using chrome's devtools I see that there is no 'Access-Control-Allow-Origin' header indeed. But when I load the site manually it is present!

I used the following code to set the headers:

response = JsonResponse(simpleWeek)
response['Access-Control-Allow-Origin'] = '*'
return response

hoping for some help!

Answer

T. Opletal picture T. Opletal · Feb 21, 2016

It says No 'Access-Control-Allow-Origin' header is present on the requested resource. which means your server application needs tunning to accept cross origin requests. Cross origin requests are by default not working due to security reasons. You need to enable them.

For django there is a maintained package with good amount of settings just for this: https://github.com/ottoyiu/django-cors-headers/