目录[-]

安装中间件

pip3 install django-cors-headers

settings.py里配置

from corsheaders.middleware import CorsMiddleware
INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)
MIDDLEWARE = [
     'corsheaders.middleware.CorsMiddleware',   #在最上面加入这一行即可
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
#添加参数为true
CORS_ORIGIN_ALLOW_ALL = True
#下面这些可以不用设置
#跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
#设置白名单

# CORS_ORIGIN_WHITELIST = (  '*')
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',
)
set 'X-Frame-Options' to 'sameorigin'
如果遇到这个问题,在settings.py文件里加上

X_FRAME_OPTIONS = 'ALLOWALL'
XS_SHARING_ALLOWED_METHODS = ['POST','GET','OPTIONS', 'PUT', 'DELETE']