跨域的几种方式-以获取天气数据为例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36146776/article/details/90179174

自我总结

出于安全原因,浏览器限制从脚本内发起的跨源HTTP请求,例如,XMLHttpRequest与提取API遵循同源策略。这意味着使用这些API的Web应用程序只能从加载应用程序的同一源请求HTTP资源,除非来自其他来源的响应包含正确的CORS标头。
同源就是“协议”、“域名”、“端口”相同。

在这里插入图片描述

1、可以跨域的标签

script的src,img的src等,css的link,
video和audio嵌入多媒体资源。
object embed applet的插件。
@font-face 引入的字体。一些浏览器允许跨域字体( cross-origin fonts),一些需要同源字体(same-origin fonts)。

和 载入的任何资源。站点可以使用X-Frame-Options消息头来阻止这种形式的跨域交互。

2、fetch 官网链接

<script>
  fetch('https://www.tianqiapi.com/api/').then(res=>{
    return res.json();
  }).then(res=>{
    console.log(res);
  })
</script>

3、jsonp 利用的是script的标签,只能get数据,不能发送数据

<script type="text/javascript">
  let scr = document.createElement('script');
  scr.type = 'text/javascript';
  scr.src = 'https://www.tianqiapi.com/api?callback=onBack';
  document.head.appendChild(scr);
  // 回调执行函数
  function onBack(res) {
    console.log(JSON.stringify(res));
  }
</script>

4、XMLHttpRequest 官网链接

<script>
  let xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://www.tianqiapi.com/api/')
  xhr.send();
  xhr.addEventListener("load", function () {
    console.log(JSON.parse(this.responseText));
  });
</script>

5、postMessage

此例子来自参考:跨域、JSONP 、CORS、postMessage
postMessage(data,origin)方法接受两个参数

//a.html
<iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe>
<script>       
    var iframe = document.getElementById('iframe');
    iframe.onload = function() {
        var data = {
            name: 'aym'
        };
        // 向domain2传送跨域数据
        iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.domain2.com');
    };
 
    // 接受domain2返回数据
    window.addEventListener('message', function(e) {
        alert('data from domain2 ---> ' + e.data);
    }, false);
</script>

//b.html  与a.html不同源

<script>
    // 接收domain1的数据
    window.addEventListener('message', function(e) {
        alert('data from domain1 ---> ' + e.data);
 
        var data = JSON.parse(e.data);
        if (data) {
            data.number = 16;
 
            // 处理后再发回domain1
            window.parent.postMessage(JSON.stringify(data), 'http://www.domain2.com');
        }
    }, false);
</script>

6、框架的应用

需要注意的是:jquery、vue、angular、react等跨域其实都是基于XMLHttpRequest来封装的。

//jquery
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script>
    $.ajax({
      type: 'GET',
      url: 'https://www.tianqiapi.com/api/',
      data: 'version=v1&city=广州',
      dataType: 'JSON',
      error: function () {
        alert('网络错误');
      },
      success: function (res) {
        console.log(res);
      }
    });
</script>

// vue
this.$http.jsonp('https://www.tianqiapi.com/api/', {
    params: {},
    jsonp: 'onBack'
}).then((res) => {
    console.log(res); 
})

参考链接:同源策略

参考总结:

更加优秀的总结
在这里插入图片描述

百度脑图

CORS 支持所有类型的 HTTP 请求,是跨域 HTTP 请求的根本解决方案
JSONP 只支持 GET 请求,JSONP 的优势在于支持老式浏览器,以及可以向不支持 CORS 的网站请求数据。
不管是 Node 中间件代理还是 nginx 反向代理,主要是通过同源策略对服务器不加限制。
日常工作中,用得比较多的跨域方案是 cors 和 nginx 反向代理

猜你喜欢

转载自blog.csdn.net/sinat_36146776/article/details/90179174
今日推荐