解决Django Rest Framework中的跨域问题

  • 时间:
  • 来源:互联网
  • 文章标签:

方案一:

全局配置

自定义中间件

# my_md.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'] = "*"

        # 允许你携带Content-Type请求头
        # response['Access-Control-Allow-Headers'] = "Content-Type"

        # 允许你发送DELETE,PUT
        # response['Access-Control-Allow-Methods'] = "DELETE,PUT"
        return response


# setting.py
MIDDLEWARE = [
    'app1.my_md.CORSMiddleware',
]

局部配置

from django.http import JsonResponse


ret={'code':1000, 'data':list(Course.objects.all().values())}
response = JsonResponse(ret)
response['Access-Control-Allow-Origin'] = "*"
return response

 方案二:

在虚拟环境下安装pip install django-cors-headers

在setting配置

加入中间件 最好放在csrf的中间件前面  并且设置变量为True

这样就解决了前后端分离的  跨域请求了

转载于:https://www.cnblogs.com/qicun/p/10139232.html

本文链接http://www.taodudu.cc/news/show-647638.html