利用package django-cors-headers
1. install
>pip install django-cors-headers
2. register
INSTALLED_APPS = [ '***', 'corsheaders', ]
3. middleware
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', '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', ]
4. while list
CORS_ORIGIN_WHITELIST = (
# 白名单:
"http.xxx.xxx.xxx
)
# 允许白名单中的 host 跨域请求时携带 cookie
CORS_ALLOW_CREDENTIALS = True
options: CORS_ORIGIN_ALLOW_ALL = True # allow all 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', )