让django支持跨域的原理比较简单,让django的http返回头中支持来源域名就OK了,通过安装django-cors-headers插件并设置相关参数即可实现,方法如下:
1.安装django-cors-headers
pip3 install django-cors-headers
2.修改settings.py
- INSTALLED_APPS中增加
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', #新增项 ]
- MIDDLEWARE中增加
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', #新增项 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
-
文件末尾增加如下行设置
# 跨域增加忽略 CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ( '*' )
3.验证跨域是否生效
从localhost:8080网站通过axios发送跨域请求到工作于8888端口的django,请求的返回头中增加了如下内容:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:8080
axios工作正常~