1、安裝django-cors-headers模組:
pip install django-cors-headers
2、插入Django的APP配置中:
# 修改settings.py中的INSTALLED_APPS配置
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 新插入的corsheaders,之前的不變
'corsheaders',
]
3、註冊CorsMiddleware中介軟體:
# 插入CorsMiddleware到中介軟體列表
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# 插入CorsMiddleware到中介軟體列表,位置不能錯
'corsheaders.middleware.CorsMiddleware',
# --------------------------------------
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CorsMiddleware中介軟體放置的位置不能錯
4、配置檔案中的設定:
CORS_ORIGIN_ALLOW_ALL = True
配置上述一個配置項django介面就可以跨域訪問,下面是網上找的完整配置
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
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',
)
不知道其他的配置需不需要,留作以後再說!