Django 跨域问题解决办法---编写跨域中间件

Django 跨域问题解决办法---编写跨域中间件

现在很多项目都是采用前后端分离,在前后端联调接口的时候很容易出现跨域的问题,django跨域的解决方案:在response header中加入Access-Control-Allow-Origin=*

编写跨域中间件

  1. 在项目目录下新增一个文件夹 corsmiddleware/
  2. 在corsmiddleware文件夹中创建__init__.py 及CorsMiddleware.py
  3. 在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',

]

重启服务

posted @ 2021-03-17 15:54  Jruing  阅读(347)  评论(0编辑  收藏  举报