A final thought (jsonp) from "cross-domain" leads

1. What is cross-domain?

  • When the protocol, the sub-domain, the domain master, the port number is not the same as any one, are counted as a different domain. Cross-domain is not unable to request, the request can be issued, the server to receive the request and returns the results to normal, but because there is a "same origin policy" browser, the result was the browser blocks.

    • For example: When jq present ajax request js or a page, the request protocol when the current domain, sub-domain, the domain master, the port number is not the same as any one, all cross-domain,

    • Finally, it simply: The browser has the "same origin policy", namely: because there is a "same origin policy" browser, the browser can only think of domain currently resides send Ajax, if the request is sent to another domain, the browser it will error.

2. The processing of cross-domain two methods

There are two solutions:

  1. cors method:

    • This method is a main method, by providing the response header of the response object, allowing to force the browser to accept cross-domain response object

      def api (request) :
         ret : = HttpResponse('百度')
         ret["Access-Control- Allow -Origin"] = "*”  #设置响应对象的响应头,接受任何跨域响应对象
         return ret
  2. jsonp: This is an idea, not the best way to deal with the problem of cross-domain , absolute blast thinking

    • One solution to cross-domain solutions, is a mechanism clever, you can bypass the browser's same-origin policy, cross-domain (dynamically created script tag).
    • In the third part of the essence!

3. The ultimate idea (the best part)

再次声明: jsonp这是一种思想,不是解决跨域的最好办法,只是一个解决跨域的方案,是一种巧妙的机制,可以绕过浏览器的同源策略,实现跨域(动态创建script标签)。但是这个思想是真的牛逼,一起来看

  • First, think about the root causes of cross-domain: Because there is a "same origin policy" browser, the browser can only think of domain currently resides send Ajax, if the request is sent to another domain, the browser will give an error.
    • Origin policy exists browser
    • Blocking request response object

3.1 js cross-domain example:

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> 
<script>
        // 同源请求
        function sendMsg1() {
            $.ajax({
                url:'/msg/',//默认端口8000
                type:'GET',
                success:function (arg) {
                    console.log(arg);
                }
            })
        }
        // 跨域请求
        function sendMsg2() {
            $.ajax({
                url:'http://127.0.0.1:9000/api/',
                type:'GET',
                success:function (arg) {
                    console.log(arg);
                }
            })
        }
</script>

Cross-domain error when the request triggers:

Focus here , to this I do not know you have not paid attention to it, although the response object ajax request was blocked, but the referenced jquery source <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>remains in effect! My God, is cross-domain ajax, jquery not? Also! Because when the protocol, subdomains main domain name, a port number is not the same any, are counted as different domains ! but why did not intercept my jquery it?

  • Because srcowned pass "same origin policy" in!, That is, the same origin policy will not block the request src attribute response object

Since it is so, that if I <script>write a request url does my src tag? Do things!

3.2 jsonp bypass the same-origin policy example

  • Because srcowned pass "same origin policy" in!, That is, the same origin policy will not block the request src attribute response object
// 前端页面

    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script>
        // 同源请求
        function sendMsg1() {
            $.ajax({
                url:'/msg/',
                type:'GET',
                success:function (arg) {
                    console.log(arg);
                }
            })
        }
        // 依旧跨域
        function sendMsg2() {
            var tag = document.createElement('script'); //创建一个script标签
            tag.src = 'http://127.0.0.1:9000/api/?callback=f1';  //更改src属性
            document.head.appendChild(tag);  // 添加到head中
            document.head.removeChild(tag);  //删除该标签
        }

        function f1(arg) {   // 请求响应完毕后,要执行的函数
            console.log(arg);
        }

    </script>
# 目标域的api接口
def api(request):
    func_name = request.GET.get('callback')
    return HttpResponse('%s("百度")' %func_name)  # 灵活接受前端的参数,并将该参数和数据一起返回

Call ~ create a script tag, change the src attribute, added to the head, remove the label, all in one, perfect cross-domain!

  • Create a scriptlabel, change the src:
在跨域请求出发时,创建一个script标签,并将src的值赋值为要请求的url,并动态设置参数callback=f1,f1是为了返回对象后执行定义的f1函数,出发自定义的动作
  • The custom script tag is added to the head

        将自定义的script标签添加到head中后,script标签就会根据url请求一个js文件,并按照javascript的方式执行,也就是去url请求一个响应对象,也就是 f1("百度"),你是不是想到了什么?没错,如果在此时你定义了
      function f1(arg) {   
          console.log(arg);
       }
    这么一个函数,这个函数就会被执行,那么跨域的问题不就解决了,也就是可以任你摆布了
  • Delete the label

    在head添加了script标签,得到f1("百度")后f1函数会立即执行,防止多次请求head中script标签过多,删了就行!

We're done!

  • But it only made jsonp get request,

summary


​        浏览器的"同源策略"不会拦截src的请求响应,通过该机制就可以绕过浏览器的同源策略.

​        再重复一次:jsonp一个解决跨域的方案,是一种巧妙的机制,可以绕过浏览器的同源策略,实现跨域(动态创建script标签).这是一种思想一种机制.

Guess you like

Origin www.cnblogs.com/bigox/p/11610027.html