1.安装插件
pip install django-cors-headers
2.注册app
INSTALLED_APPS = [
...
'corsheaders'
]
3.注册插件
# corsheaders.middleware.CorsMiddleware 要放到最上方,因为插件是依次执行的
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.设置白名单
# CORS白名单,在CORS中127.0.0.1和localhost不同所以要分别写入
# 且地址需要加上域名
CORS_ORIGIN_WHITELIST = (
'http://127.0.0.1:8080',
'http://localhost:8080',
)
# 跨域时允许携带cookie
CORS_ALLOW_CREDENTIALS = True
5.允许访问的域名
# 跟白名单保持一直,但不用加端口号
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']