一、問題描述
二、解決方法
1.安裝django-cors-headers
pip install -i https://pypi.douban.com/simple django-cors-headers
2.將corsheaders添加到settings.py文件的INSTALLED_APPS中,盡量放在前面
INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'drf_yasg' ]
3.添加中間件
需要添加在CommonMiddleware中間件之前
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', '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.添加白名單
# CORS_ORIGIN_ALLOW_ALL為True,指定所有域名(ip)都可以訪問后端接口,默認為False CORS_ORIGIN_ALLOW_ALL = True
也可以通過白名單列表添加指定的ip或域名
# CORS_ORIGIN_WHITELIST指定能夠訪問后端接口的ip或域名列表 CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:8080', 'http://localhost:8080', 'http://192.168.6.23:8080' ]
5.允許跨域時攜帶Cookie
# CORS_ALLOW_CREDENTIALS允許跨域時攜帶Cookie,默認為False CORS_ALLOW_CREDENTIALS = True