服务端安装跨域组件
pip install django-cors-headers
添加子应用,settings/dev.py,代码:
python
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders', # cors跨域子应用
'home', # apps已经在上面加入到python的系统导包路径列表了,这里还是出现背景颜色,原因是python虽然找到home,pycharm不知道。所以可以鼠标右键,设置apps为mark as source root
]
注册CorsMiddleware中间件【必须写在第一个位置】,settings/dev.py,代码:
python
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # cors跨域的中间件
'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',
]
添加客户端访问服务端的白名单,设置允许哪些客户端客户端跨域访问服务端,settings/dev.py,代码:
python
# CORS的配置信息:
# 方案1:
# CORS_ORIGIN_WHITELIST = (
# 'http://www.leshen.cn:3000',
# )
# CORS_ALLOW_CREDENTIALS = False # 不允许ajax跨域请求时携带cookie
# 方案2:
CORS_ALLOW_ALL_ORIGINS = True