Django<=1.6.10包括以下 ∨
# 在项目任意地方(建议在某个app中)创建middleware.py中间件
CorsMiddleware.py
# 修改settings.py文件
MIDDLEWARE_CLASSES = (
'......',
'......',
'app_name.middleware.CorsMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'......',
'......'
)
# middleware.py
class CorsMiddleware(object):
"""屏蔽CORS跨域"""
def process_response(self, request, response):
# 注: 使用*表示所有跨域请求都可以,这样会有风险
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Credentials'] = "true"
response['Access-Control-Allow-Methods'] = "GET,POST"
return response
完成
Django>=1.11包括以上 ^
# 安装
pip install django-cors-headers
# 在项目settings中进行配置
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
# CORS
CORS_ORIGIN_WHITELIST = (
'127.0.0.1:8080',
'localhost:8080',
)
CORS_ALLOW_CREDENTIALS = True # 指明在跨域访问中,后端是否支持对cookie的操作。
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = ('*')
#这个*表示所有其它请求都可以访问此站点,所以可以设置为有权限访问此站点的ip
#下面就是关于对预检请求的处理,允许正式请求的请求方法和请求头字段
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',
)
学习链接
https://blog.csdn.net/liuanpingfirst/article/details/86684029