• DRF跨域,简单请求和复杂请求


    跨域就是跨域名,跨端口

    - 为什么会有跨域?

      浏览器有同源限制策略

    - 绕过浏览器同源策略就可以跨域

      -  方式一: jsonp(利用浏览器特性)

         在html动态创建script标签

         同源策略会阻止ajax请求,但不阻止具有src属性的标签

         <script src='xxx'></script>

         <img src='xxx' />

      - 方式二: cors(硬刚) 

         添加中间件设置cors

          

    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"] = "*"
    
            return response

    简单请求  复杂请求

    1、请求方式:HEAD、GET、POST
    2、请求头信息:
        Accept
        Accept-Language
        Content-Language
        Last-Event-ID
        Content-Type 对应的值是以下三个中的任意一个
            application/x-www-form-urlencoded
            multipart/form-data
            text/plain

    注意:同时满足以上两个条件时,则是简单请求,否则为复杂请求

      

    简单请求和非简单请求的区别

      简单请求:一次请求

      复杂请求:两次请求,在发送数据之前会先发一次请求用于做“预检”,只有“预检”通过后才再发送一次请求

      

    - 请求方式:OPTIONS
    - "预检"其实做检查,检查如果通过则允许传输数据,检查不通过则不再发送真正想要发送的消息
    - 如何"预检"
         => 如果复杂请求是PUT等请求,则服务端需要设置允许某请求,否则"预检"不通过
            Access-Control-Request-Method
         => 如果复杂请求设置了请求头,则服务端需要设置允许某请求头,否则"预检"不通过
            Access-Control-Request-Headers        text/plain
    关于预检
    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"
    
            if request.method == 'OPTIONS':
                response["Access-Control-Allow-Headers"] = "Content-Type"
    
    
            return response
    实例
  • 相关阅读:
    ubuntu 卸载干净软件(包括配置文件)
    Unable to lock the administration directory (/var/lib/dpkg/) is another process using it?
    linux watch 命令
    [转]如何成为优秀的程序员?
    【转】css浮动元素的知识
    Hierarchical data in postgres
    【转】supervisord使用
    手动安装pip
    zoj1649-Rescue (迷宫最短路径)【bfs 优先队列】
    poj3278-Catch That Cow 【bfs】
  • 原文地址:https://www.cnblogs.com/erhao9767/p/10158647.html
Copyright © 2020-2023  润新知