[Django]-How to solve CORS problem of my Django API?

28πŸ‘

βœ…

You need to add corsheaders.middleware.CorsMiddleware middleware to the middleware classes in settings.py :

MIDDLEWARE_CLASSES = (
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.BrokenLinkEmailsMiddleware',
    'django.middleware.common.CommonMiddleware',
    #...
)

You have duplicate django.middleware.common.CommonMiddleware in your middleware classes.

You can then, either enable CORS for all domains by adding the following setting:

CORS_ORIGIN_ALLOW_ALL = True

Or Only enable CORS for specified domains:

CORS_ORIGIN_ALLOW_ALL = False

CORS_ORIGIN_WHITELIST = (
    'http://localhost:8000',
)
πŸ‘€MSaadat

9πŸ‘

Try to add this in your settings:

from corsheaders.defaults import default_headers

CORS_ALLOW_HEADERS = default_headers + (
    'Access-Control-Allow-Origin',
)
πŸ‘€Nevenoe

0πŸ‘

I got this error when I visited http://127.0.0.1:8000 in my browser but used fetch('http://localhost:8000'); in my JavaScript code. The solution is to use either 127.0.0.1 or localhost but not mix them.

0πŸ‘

The only thing that helped me, was installing django-cors-headers:

pip install django-cors-headers

Then update the django settings.py file with the following:

INSTALLED_APPS = [
    ...
    "corsheaders",
    ...
]

MIDDLEWARE = [
    ...
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...
]
πŸ‘€Vova

0πŸ‘

Here is another tip that I haven’t seen mentioned anywhere.

When testing your Django app from a HTML file that you have stored locally and opened up from your file system, the submit form will have a Null origin.

Therefore to let CORS permit this you need to add Null to your CORS_ALLOWED_ORIGINS settings such as:

CORS_ALLOWED_ORIGINS = [
    "http://localhost:8000",
    "http://127.0.0.1:8000",
    "null",
]

HOWEVER allowing requests from a null origin can introduce potential security concerns, as it opens up your Django application to requests from any source, including local file systems and potentially malicious origins.

What I should have been doing is placing my test.html into the djagno folder and accessing it via http://127.0.0.1:8000/test.html instead.

πŸ‘€Goomblepop

Leave a comment