zoukankan      html  css  js  c++  java
  • 前后端分离后的,浏览器导致的跨域问题

    1、什么是跨域?

      就是由于域名不同,或者端口不同,或者协议不同浏览器的同源策略就会自动将不同源的请求进行阻拦。形成跨域。

    2、什么是简单请求?  

      HTTP方法是下列方法之一

        HEAD, GET,POST

      HTTP头信息不超出以下几种字段

        Accept, Accept-Language, Content-Language, Last-Event-ID

        Content-Type只能是下列类型中的一个

          application/x-www-from-urlencoded

          multipart/form-data

          text/plain

      任何一个不满足上述要求的请求,即会被认为是复杂请求~~

      复杂请求会先发出一个预请求,我们也叫预检,OPTIONS请求~~

    2、解决方法

    方法一:jsonp

       通过jsonp不阻止src请求入手实现

        

    class Test(APIView):
    
        def get(self, request):
            callback = request.query_params.get("callback", "")
            ret = callback + "(" + "'success'" + ")"
            return HttpResponse(ret)
    后端代码
    <button id="btn_one">点击我向JsonP1发送请求</button>
    <script>
        // 测试发送请求失败 跨域不能得到数据
        $('#btn_one').click(function () {
            $.ajax({
                url: "http://127.0.0.1:8000/jsonp1",
                type: "get",
                success: function (response) {
                    console.log(response)
                }
            })
        });
        
        function handlerResponse(response) {
            alert(response)
        };
        
        window.onload = function () {
            $("#btn_one").click(function () {
                let script_ele = document.createElement("script");
                script_ele.src = "http://127.0.0.1:8000/jsonp1?callback=handlerResponse";
                document.body.insertBefore(script_ele, document.body.firstChild);
            })
        }
    
    
    </script>
    前端代码

    方法二:添加响应头  

        写一个中间件,将浏览器拒绝的都让他允许就好。

      

    <button id="my_button">点我你将有意想不到的收获</button>
        <script>
            $("#my_button").click(function () {
                $.ajax({
                    url:"http://127.0.0.1:8000/cors/my_cors/",
                    type:"put",                          # 复杂请求的请求方法,需要中间件中允许Methods
                    contentType:"application/json",      # 配置了ContentType,中间件中要写相应的命令允许
                    success:function (data) {
                        console.log(data)
                    }
                })
            })
        </script>
    from django.utils.deprecation import MiddlewareMixin
    
    
    class MyCors(MiddlewareMixin):
        def process_response(self, request, response):
            # 写了这条命令后,默认允许所有
            response["Access-Control-Allow-Origin"] = "*"
            # 如果是复杂请求,就会先发送一个OPTIONS进行预检测
            if request.method == "OPTIONS":
                # 当AJAX 请求中如果设置了ContentType,就需要在中间件中写这条允许Content-Type
                response["Access-Control-Allow-Headers"] = "Content-Type"
                # 如果是put,patch,delete 等请求方式,需要先配置以下命令
                response["Access-Control-Allow-Methods"] = "PUT,PATCH,DELETE"
            return response
    中间件中配置,解决跨域

      然后在settings的中间件中注册该中间件

    方法三:通过django-cors-headers

  • 相关阅读:
    Codeforces Round #344 (Div. 2) C. Report 其他
    Codeforces Round #344 (Div. 2) B. Print Check 水题
    Codeforces Round #344 (Div. 2) A. Interview 水题
    8VC Venture Cup 2016
    CDOJ 1280 772002画马尾 每周一题 div1 矩阵快速幂 中二版
    CDOJ 1280 772002画马尾 每周一题 div1 矩阵快速幂
    CDOJ 1279 班委选举 每周一题 div2 暴力
    每周算法讲堂 快速幂
    8VC Venture Cup 2016
    Educational Codeforces Round 9 F. Magic Matrix 最小生成树
  • 原文地址:https://www.cnblogs.com/wf123/p/9991603.html
Copyright © 2011-2022 走看看