#以中间件方式解决API数据访问跨域问题
1.API下新建文件夹下写PY文件
a.引入内置类继承:
from django.middleware.common import MiddlewareMixin class CORSMiddleware(MiddlewareMixin): def process_response(self,request,response): #添加响应头 #允许你的域名来获取我的数据,'*'也可以单独设置 response['Access-Control-Allow-Origin'] = '*' #允许携带Content-Type请求头 response['Access-Control-Allow-Headers'] = 'Content-Type' #如果PUT或者别的请求形式报错 response['Access-Control-Allow-Methods'] = 'put,' return response
b.重写继承类:
可以引入,也可以如下重写方法 class MiddlewareMixin: def __init__(self, get_response=None): self.get_response = get_response super().__init__() def __call__(self, request): response = None if hasattr(self, 'process_request'): response = self.process_request(request) response = response or 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'] = '*' #允许携带Content-Type请求头,如果允许别的请求头加入,写在后面,如k1 response['Access-Control-Allow-Headers'] = 'Content-Type,k1' return response
2.settings中间件添加
MIDDLEWARE = [ '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', 'middleware.CorsMiddleware.CORSMiddleware'#引入处理跨域的类 ]