什么是跨域请求,可查看Flask-处理跨域请求进行了解。本文重点介绍Django中如何处理跨域请求,分为以下3个步骤。
Step1:安装django-cors-headers库。
pip install django-cors-headers
Step2:在setting.py文件中设置中间件,添加'corsheaders.middleware.CorsMiddleware',并注释掉'django.middleware.csrf.CsrfViewMiddleware'。
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware', # 添加中间件
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware', 需注释掉,否则Post请求时会报错:Forbidden (CSRF cookie not set.)
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Step3:设置跨域请求的相关条件。
# 跨域请求相关条件
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = ()
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)