Search code examples
javascriptdjangodjango-rest-frameworkdjango-cors-headers

How do I debug enabling CORS on my Django REST api


I'm trying to enable CORS on a simple django rest server.

I've followed the suggestions here How can I enable CORS on Django REST Framework.

Specifically I have:

1) done

pip install django-cors-headers

2)

added corsheaders to my installed apps

3) added corsheaders.middleware.CorsMiddleware at the top of the MIDDLEWARE section of my Django settings file

4) added

  CORS_ORIGIN_ALLOW_ALL = True
  CORS_ALLOW_CREDENTIALS = True
  CORS_ORIGIN_WHITELIST = (
   'localhost:3000/radioDestinations/',
   'localhost:8080',
   )

but it's still not working.

When I send the request to the server (using a javascript fetch request) I get an error in the browser (...blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present...), but I don't get any output in the serve console.

How can I find out where the problem is?


Solution

  • django-cors-headers is reasonably fool-proof and your configuration seems correct to me.

    There is however a gotcha I've had issues with, which might be your problem too:
    If you configure your server to serve static files without invoking Django / Python (pretty common, even on the built-in server), django-cors-headers cannot apply a CORS header to those responses. Depending on the browser, this will cause problems with asynchronous requests, fonts and sometimes even images, video and audio.