前言
在实现前后端分离项目(前端react,后端django)时遇到如下跨域问题,最终通过第三方包django-cors-headers的方式解决,特总结下来:
解决过程
通过第三方包方式:https://github.com/ottoyiu/django-cors-headers,具体实现如下:
1、安装django-cors-headers
pip install django-cors-headers
2、配置settings.py文件
a.在INSTALLED_APPS里添加“corsheaders”
INSTALLED_APPS = [ ... 'corsheaders', ... ]
b.在MIDDLEWARE_CLASSES添加配置:
MIDDLEWARE_CLASSES = ( ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... )
c.在sitting.py底部添加
CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = () 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', )
参考链接:
https://www.cnblogs.com/skyflask/p/10675706.html