zoukankan      html  css  js  c++  java
  • 跨域的集中整理(根据某培训机构课程笔记)

    跨域的集中方法:

    一、JSONP

    缺点只能获取get请求,需要后端配合返回cb(data)。

    二、CORS

    后端各种设置header

    res.SetHeaders(Access-Control-Allow-Origin, "")

    res.SetHeaders(Access-Control-Allow-Credentials, "")

    res.SetHeaders(Access-Control-Expose-Headers, "")

    三、postMessage

    域A页面A.html中使用iframe嵌套域B的B.html,则A.html中这么写:

    <!DOCTYPE html>
    <html>
    
    <head>
      <style>
      </style>
    </head>
    
    <body>
      我是A
      <iframe src="http://localhost:4000/B.html" frameborder="0" id="iframe" onload="handleLoaded()"></iframe>
      <script>
        function handleLoaded() {
          let iframe = document.getElementById('iframe');
          iframe.contentWindow.postMessage('hello?','http://localhost:4000')
        }
        window.onmessage = function (e) {
          console.log('回消息了', e.data)
        }
      </script>
    </body>
    
    </html>

     B中这么写:

    <!DOCTYPE html>
    <html>
    
    <head>
        <meta charset="UTF-8">
        <style>
        </style>
        <title>测试</title>
    </head>
    <body>
        我是C
        <script>
            window.onmessage=function(e){
                console.log(e,'e')
                e.source.postMessage('我是土豆',e.origin)
            }
        </script>
    </body>
    
    </html>
    

      需要注意的一点是测试的时候,A代码中iframe的src地址要写成隔壁域名下的B.html,造成我测试的时候总是报如下错误:

    Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:4000') does not match the recipient window's origin ('http://localhost:3000').

    四、document.domin

    只适合同一主域名下的的网页通信。方法就是给要通信的网页script代码下面都放上document.domin="XXX",即可。

    五、window.name

    AB同域、C独立域,A嵌套C,C设置window.name,A中C加载完毕后,将iframe的src换成B,但是window.name不会变,好像是bug一样。

    六、location.hash

    AB同域、C独立域,A嵌套C,C动态加载B,然后B通过parent.parent.location.hash=“”,然后A监听hashchange事件去拿hash变化。

    七、nginx配置。

    配置,类似CORS。

    八、websoket。

    不受同源策略限制。

    九、webpack代理Proxy。

  • 相关阅读:
    java IO流详解
    java设计模式之单例模式(几种写法及比较)
    JS定时刷新页面及跳转页面
    遍历map的四种方法
    String 中去掉空格
    TSP问题_遗传算法(STL大量使用)
    无向图的深度优先生成树和广度优先生成树
    Prim算法求最小生成树
    哈夫曼编码_静态库
    中序线索化二叉树
  • 原文地址:https://www.cnblogs.com/liujiekun/p/11163043.html
Copyright © 2011-2022 走看看