Ken专注后端技术 2020-05-28
利用 django-cors-headers插件来解决前后端分离时遇到的跨域问题
pip install django-cors-headers
在INSTALLED_APPS里添加"corsheaders"
INSTALLED_APPS = [ ... ‘corsheaders‘ ... ]
在MIDDLEWARE_CLASSES中添加配置
MIDDLEWARE_CLASSES = ( ... ‘corsheaders.middleware.CorsMiddleware‘, # 新加入的内容 ‘django.middleware.common.CommonMiddleware‘, # 原来已经存在的项目 ... )
在settings.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‘, ‘orgin‘, ‘user-agent‘, ‘x-csrftoken‘, ‘x-requested-with‘, )