解決Access Control Allow Origin header問題 - jenhaoyang/backend_blog GitHub Wiki

Step 1 - Install django-cors-headers

pip install django-cors-headers

Step 2 - Add corsheader to the Installed App list in settings.py

INSTALLED_APPS = [
...
'corsheaders',
...
]

Step 3 - Add CorsMiddleware to middleware list in settings.py

MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
...
]

Step 4 - You have two alternatives here. Either follow Option A or Option B

Step 4 ( Option A) - Allow access to all domains by just Adding the following variables in settings.py:

ALLOWED_HOSTS=['*']
CORS_ORIGIN_ALLOW_ALL = True

Step 4 ( Option B) - Do not allow access to all the domains, but the one which you are consuming the API. Add following variables in settings.py

ALLOWED_HOSTS=['http://localhost:5000']
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'http://localhost:5000',
)

You are good to go now. Thanks for reading

參考:
https://dzone.com/articles/how-to-fix-django-cors-error