How to solve CORS problem of my Django API?
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',
)
Try to add this in your settings:
from corsheaders.defaults import default_headers
CORS_ALLOW_HEADERS = default_headers + (
'Access-Control-Allow-Origin',
)