1、安装django-cors-headers模块:
pip install django-cors-headers
2、插入Django的APP配置中:
INSTALLED_APPS
= [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
]
3、注册CorsMiddleware中间件:
MIDDLEWARE
= [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'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',
)
不知道其他的配置需不需要,留作以后再说!