Django 跨域问题解决办法---编写跨域中间件
Django 跨域问题解决办法---编写跨域中间件
现在很多项目都是采用前后端分离,在前后端联调接口的时候很容易出现跨域的问题,django跨域的解决方案:在response header中加入Access-Control-Allow-Origin=*
编写跨域中间件
- 在项目目录下新增一个文件夹 corsmiddleware/
- 在corsmiddleware文件夹中创建__init__.py 及CorsMiddleware.py
- 在CorsMiddleware.py文件中写入以下内容
"""解决跨域cors的中间件"""
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'] = "*"
# 允许你携带Content-Type请求头
response['Access-Control-Allow-Headers'] = "Content-Type"
# 允许你发送DELETE,PUT
# response['Access-Control-Allow-Methods'] = "DELETE,PUT"
return response
注册中间件
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# 要增加的中间件
'jruing_blog.corsmiddleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
重启服务
本文来自博客园,作者:Jruing,转载请注明原文链接:https://www.cnblogs.com/jruing/p/14549819.html