Django解决跨域俩方案
Posted abraverman
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django解决跨域俩方案相关的知识,希望对你有一定的参考价值。
首先你的pip下载一个第三方库贼厉害的:
pip install corsheaders
然后在项目的setting.py里面引入第三方库,如下:
INSTALLED_APPS = [ ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘coffee.apps.CoffeeConfig‘, ‘rest_framework‘, ‘corsheaders‘ # 引入第三方库 ]
接着配置setting.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 = ( ‘XMLHttpRequest‘, ‘X_FILENAME‘, ‘accept-encoding‘, ‘authorization‘, ‘content-type‘, ‘dnt‘, ‘origin‘, ‘user-agent‘, ‘x-csrftoken‘, ‘x-requested-with‘, ‘Pragma‘, ) # 结束:加入了中间件来实现跨域请求
再次访问的时候用AJAX带上请求头就可以了,注意哦,是请求头,不是数据哦!
首先在APP下面创建一个cors.py,里面写入如下内容
# cors.py class MiddlewareMixin(object): def __init__(self, get_response=None): self.get_response = get_response super(MiddlewareMixin, self).__init__() def __call__(self, request): response = None if hasattr(self, ‘process_request‘): response = self.process_request(request) if not response: response = self.get_response(request) if hasattr(self, ‘process_response‘): response = self.process_response(request, response) return response class CORSMiddleware(MiddlewareMixin): def process_response(self,request,response): # 添加响应头 # 允许你的域名来获取我的数据 response[‘Access-Control-Allow-Origin‘] = "*" if request.method == "OPTIONS": # 允许你携带Content-Type请求头 response[‘Access-Control-Allow-Headers‘] = "Content-Type" # 允许你发送DELETE,PUT # response[‘Access-Control-Allow-Methods‘] = "DELETE,PUT" return response
然后在setting.py里面配置一下
MIDDLEWARE = [ ‘django.middleware.security.SecurityMiddleware‘, ‘django.contrib.sessions.middleware.SessionMiddleware‘, ‘django.middleware.common.CommonMiddleware‘, ‘django.middleware.csrf.CsrfViewMiddleware‘, # ‘django.middleware.csrf.CsrfResponseMiddleware‘, ‘django.contrib.auth.middleware.AuthenticationMiddleware‘, ‘django.contrib.messages.middleware.MessageMiddleware‘, ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘, ‘coffee.cors.CORSMiddleware‘, # 引入跨域 ]
然后前后端分离的时候带上请求头就可以了!
完美收官!
以上是关于Django解决跨域俩方案的主要内容,如果未能解决你的问题,请参考以下文章