django-cors-headers安裝與配置
官方文檔:https://pypi.org/project/django-cors-headers/
安裝
pip install django-cors-headers
使用
添加到settings.py
中, 按如下進行配置
# settings.py
INSTALLED_APPS = [
'corsheaders',
]
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
# 在settings.py文件末尾添加如下配置
# 跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
# 這里添加你允許的跨域來源
'http://127.0.0.1',
)
# 添加運行的請求方法
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
# 添加允許的請求頭
CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'Pragma',
)
至此問題解決