1、安裝模塊git
pip install django-cors-headers
django-cors-headers 使用說明:https://github.com/ottoyiu/django-cors-headersgithub
2、添加到INSTALL_APPS中django
INSTALLED_APPS = ( ... 'coreschema', ... )
3、添加中間件session
下面添加中間件的說明:cors
CorsMiddleware
should be placed as high as possible, especially before any middleware that can generate responses such as Django's CommonMiddleware
or Whitenoise's WhiteNoiseMiddleware
. If it is not before, it will not be able to add the CORS headers to these responses.spa
Also if you are using CORS_REPLACE_HTTPS_REFERER
it should be placed before Django's CsrfViewMiddleware
(see more below).code
意思就是 要放的儘量靠前,必須在CsrfViewMiddleware以前。咱們直接放在第一個位置就行了csrf
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、設置爲True中間件
CORS_ORIGIN_ALLOW_ALL = True