最近得空整理下知识点,之前做一个项目前后端分离,前端访问后端api时出现的跨域问题
1、安装django-cors-headers
pip install django-cors-headers
2、配置
INSTALLED_APPS = [ #注册应用
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'django_crontab',
'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',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = () #白名单ip,可以不填
CORS_ALLOW_CREDENTIALS = True # 允许携带cookie
# 前端需要携带cookies访问后端时,需要设置
# withCredentials=True
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',
)