Django设置跨域访问
(1) 安装DjangoCors Headers
pip install django-cors-headers
(2) settings.py 配置如下
INSTALLED_APPS = [
# 'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
# 'django.contrib.messages',
# 'django.contrib.staticfiles',
# 添加应用index
'index',
# 添drf
'rest_framework',
# 添加DjangoCors Headers
'corsheaders',
]
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',
]
# 设置跨域设置
CORS_ALLOW_CREDENTIALS = True # 设置HTTP请求是否允许携带cookies信息,默认值为False
CORS_ORIGIN_ALLOW_ALL = True # 默认值为False,只允许CORS_ORIGIN_WHITELIST设置的域名列表发送HTTP请求,若为True,则允许所有域名发送HTTP请求。
CORS_ORIGIN_WHITELIST = () # 默认值为空列表,设置允许发送HTTP请求的域名,即部署前端项目的的服务器IP地址或域名
# 设置允许的HTTP请求方式,如GET,POST
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
# 设置非标准的HTTP请求头
CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)
标签:HTTP,跨域,middleware,django,访问,设置,CORS,contrib,Django
From: https://www.cnblogs.com/minqiliang/p/16586170.html