1.安装django-cors-headers
pip install django-cors-headers
2.配置INSTALLED_APPS:
INSTALLED_APPS = [ ... 'corsheaders',#处理跨域 ]
3.配置MIDDLEWARE(注意上下位置,不能颠倒):
MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ]
4.settings.py中添加配置信息:
# 指明在跨域访问中,后端是否支持对cookie的操作 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', )