1.安装cors-headers⼯具
pip install django-cors-headers
2.安装cors-headers应⽤
# 注册应用
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders', # 解决跨域CORS
]
3.配置中间件(cors放在所有中间件的最外层,这样可以第一时间被检测,避免无意义的操作)
# 中间件
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',
]
4.添加⽩名单
# 允许哪些域名访问Django
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
# CORS 追加⽩名单
CORS_ORIGIN_WHITELIST = (
'http://127.0.0.1:5500',
'http://localhost:5500',
)
CORS_ALLOW_CREDENTIALS = True # 跨域时允许携带cookie
标签:跨域,middleware,cors,中间件,django,CORS,contrib From: https://www.cnblogs.com/yeli-oneselfblogs/p/17143159.html