15

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!

T. Opletal
  • 2,124
  • 1
  • 15
  • 23
Nathan
  • 900
  • 2
  • 10
  • 28
  • Could you please show more code of your view? – Paul Feb 20 '16 at 10:43
  • have you tried to set crossDomain to true? It is false by default. – gaetanoM Feb 20 '16 at 12:21
  • @gaemaf This works, but now I get: `Failed to load resource: net::ERR_CONNECTION_REFUSED` I used a clean version of Chrome(like I always do when testing code) so there is no adblocker causing the problem. **never mind, typo in url, it still doesnt work!** I do get another error now. I'm editing the question now. – Nathan Feb 20 '16 at 16:00
  • have a look at this: https://github.com/ottoyiu/django-cors-headers/ – T. Opletal Feb 20 '16 at 18:47

3 Answers3

13

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/

T. Opletal
  • 2,124
  • 1
  • 15
  • 23
  • 1
    I used django-cors-headers, when request host is 'localhost' & '127.0.0.1', it did not work, No 'Access-Control-Allow-Origin' header. host is my ip, work well. – YETI Jul 15 '17 at 09:54
  • @YETI, Try `CORS_ORIGIN_ALLOW_ALL = True` as prescribed in the link given by T.Opletal – Wachaga Mwaura Nov 15 '18 at 08:36
  • This is so crucial, you can't do anything with the response unless you allow CORS. You can't even loop through it and print it out! Thanks a bunch T. Opletal – Wachaga Mwaura Nov 15 '18 at 08:38
3

After 2 hours of troubleshooting I found solution: TYPO in url. Check twice, maybe it will fix your issue too.

Seyhak Ly
  • 107
  • 2
-1

For this thing to work you need to do two thing:


  • instead of https:// just give http:// in your CORS_ORIGIN_WHITELIST in settings.py

  • add CORS_ORIGIN_ALLOW = True in the same file