十、跨域问题


返回

10.1 JSONP解决跨域

  • 利用浏览器不阻止src请求的原理,解决跨域

  • 后端代码

    from django.http import HttpResponse
    from rest_framework.views import APIView
    
    
    class DemoView(APIView):
        def get(self, request):
            res = "handlerResponse('这是js代码')"
            return HttpResponse(res)  # 这里用HttpResponse
            
    
  • 前端代码

    <head>
        <script>
            function handlerResponse(data) {
                console.log(data)
            }
        </script>
        <script src="http://127.0.0.1:8000/demo/"></script>
    </head>
    
    

10.2 添加响应头解决跨域

  • 通过中间件添加响应头middlewares.py

    from django.utils.deprecation import MiddlewareMixin
    
        
    class MyCors(MiddlewareMixin):
        def process_response(self, request, response):
            response["Access-Control-Allow-Origin"] = "*"  # "*"任何域都不拦截
            response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS, PUT, DELETE"  # 允许的请求方式
            if request.method == "OPTIONS":
                response["Access-Control-Allow-Headers"] = "content-type, AUTHENTICATION"  # 允许的请求数据类型,AUTHENTICATION = 'token值'
            return response
    
    
返回