前端跨域总结

2021-11-30  本文已影响0人  咆哮小狮子

声明

本人也在不断的学习和积累中,文章中有不足和误导的地方还请见谅,可以给我留言指正。希望和大家共同进步,共建和谐学习环境。

跨域

 1、什么是跨域

指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制。

 2、同源策略

是指协议,域名,端口都要相同,其中有一个不同都会产生跨域;


跨域示例
 3、同源策略限制以下行为:
  • Cookie、LocalStorage 和 IndexDB 无法读取
  • DOM 和 JS 对象无法获取
  • Ajax请求发送不出去

解决方案

 据我了解的,总结了以下几种方式,有其他方式的可以给我留言:
 1、domain

  假设我们现在有一个页面 a.html 它的地址为http://www.a.com/a.html , 在a.html 在中有一个iframe,iframe的src为http://a.com/b.html,这个页面与它里面的iframe框架是不同域的,所以我们是无法通过在页面中书写js代码来获取iframe中的东西的;
  a.html内容:

<script type="text/javascript">
    function test(){
        var iframe = document.getElementById('ifame');
        var win = document.contentWindow;
        var doc = win.document;//这里获取不到iframe里的document对象
        var name = win.name;//这里同样获取不到window对象的name属性
    }
</script>
<iframe id = "iframe" src="http://a.com/b.html" onload = "test()"></iframe>

  使用domain设置,a.html中的内容修改为:

<iframe id = "iframe" src="http://a.com/b.html" onload = "test()"></iframe>
<script type="text/javascript">
    document.domain = 'a.com'; //设置成主域
    function test(){
        alert(document.getElementById('iframe').contentWindow);  //contentWindow 可取得子窗口的 window 对象
    }
</script>

  在b.html 中也设置

<script type="text/javascript">
    document.domain = 'a.com';//在iframe载入这个页面也设置document.domain,使之与主页面的document.domain相同
</script>
 2、jsonp

  采用这种方法,是由于html标签src属性不受同源限制。
  优点:它不像XMLHttpRequest对象实现的Ajax请求那样受到同源策略的限制;它的兼容性更好,在更加古老的浏览器中都可以运行,不需要XMLHttpRequest或ActiveX的支持;并且在请求完毕后可以通过调用callback的方式回传结果。
  缺点:它只支持GET请求而不支持POST等其它类型的HTTP请求;它只支持跨域HTTP请求这种情况,不能解决不同域的两个页面之间如何进行JavaScript调用的问题。

  原生方法:

function jsonp({url,callback}) {
  let script = document.createElement('script');
  script.src = `${url}&callback=${callback}`;
  document.head.appendChild(script);
}

  node服务:

const http = require('http');
const url = require('url');
const queryString = require('querystring');
const data = JSON.stringify({
  title: 'hello,jsonp!'
})

const server = http.createServer((request, response) => {
  let addr = url.parse(request.url);
  if (addr.pathname == '/jsonp') {
    let cb = queryString.parse(addr.query).callback;
    response.writeHead(200, { 'Content-Type': 'application/json;charset=utf-8' })
    response.write(cb + '('+ data +')'); // 回调
  } else {
    response.writeHead(403, { 'Content-Type': 'text/plain;charset=utf-8' })
    response.write('403');
  }
  response.end();
})

server.listen(3000, () => {
  console.log('Server is running on port 3000!');
})

  页面调用:

jsonp({
  url: 'http://localhost:3000/jsonp?from=1',
  callback: 'getData',
})

function getData(res) {
  console.log(res); // {title: "hello,jsonp!"}
}

  jQuery方法:

$(function () {  
  $.ajax({
    url: 'http://localhost:3000/jsonp?from=1',
    type: 'get',
    dataType: 'jsonp',
    success: function(res) {
      console.log(res); // {title: "hello,jsonp!"}
    }
  })
})
 3、CROS

  CORS(Cross -Origin Resource Sharing),跨域资源共享,是一个W3C标准,在http的基础上发布的标准协议。
  CORS需要游览器和服务器同时支持,解决了游览器的同源限制,使得跨域资源请求得以实现。它有两种请求,一种是简单请求,另外一种是非简单请求。
简单请求
满足以下两个条件就属于简单请求,反之非简单。

  1. 请求方式是 GET、POST、HEAD;
  2. 响应头信息是 Accept、Accept-Language、Content-Language、Last-Event-ID、Content-Type(只限于application/x-www-form-urlencoded、multipart/form-data、text/plain);

  1、Access-Control-Allow-Origin,这个表示接受哪些域名的请求,如果是*号,那就是任何域名都可以请求;
  2、Access-Control-Allow-Credentials,这个表示是否允许携带cookie,默认是false,不允许携带;

    如果设置为true, 要发送cookie,允许域就必须指定域名方法;客户端http请求必须设置:

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

  3、Access-Control-Expose-Headers,这个表示服务器可接受的响应头字段,如果客户端发送过来请求携带的Cache-Control、Content-Language、Content-Type、Expires、Last-Modified,还有自定义请求头字段。

  就是除了简单请求的几种方法外,比如说PUT请求、DELETE请求,这种都是要发一个预检请求的,然后服务器允许,才会发送真正的请求。

  非简单请求有以下几个字段需要传递:
  1、Access-Control-Allow-Methods,值是以逗号分隔,比如:GET,POST,DELETE;
  2、Access-Control-Allow-Headers,值是默认字段或者自定义字段,例如:X-Auth-Info;
  3、Access-Control-Allow-Credentials,是否携带cookie信息;
  4、Access-Control-Max-Age,代表预检请求的有效期限,单位是秒。

 4、post Message

otherWindow:指目标窗口,也就是给哪个window发消息,是 window.frames 属性的成员或者由 window.open 方法创建的窗口
message: 是要发送的消息,类型为 String、Object (IE8、9 不支持)
targetOrigin: 是限定消息接收范围,不限制请使用 ‘*

  父页面通过postMessage('<msg>','<url>'),子页面接收消息,并且返回消息到父页面,父页面监听message事件接收消息。
  例如:http://map.domaintest.org:8089/parent.html发送消息给子页面http://map.domaintest.org:8089/son.html,子页面返回消息。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>父级页面</title>
</head>
<body>
  <button id="btn">发送消息</button>
  <iframe id="child" src="http://map.domaintest.org:8089/son.html" width="100%" height="300"></iframe>
  <script>
    let sendBtn = document.querySelector('#btn');
    sendBtn.addEventListener('click', sendMsg, false);
    function sendMsg () {  
      window.frames[0].postMessage('getMsg', 'http://map.domaintest.org:8089/son.html');
    }
    window.addEventListener('message', function (e) {
      let data = e.data;
      console.log('接收到的消息是:'+ data);
    })
  </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>子页面</title>
</head>
<body>
  <h2>窗口</h2>
  <p>我是另外一个窗口!</p>
  <script>
    window.addEventListener('message', function (e) {  
      if (e.source != window.parent) return;
      window.parent.postMessage('我是来自子页面的消息!', '*');
    }, false)
  </script>
</body>
</html>
 5、location.hash

 原理:父窗口可以对iframe进行URL读写,iframe也可以读写父窗口的URL,动态插入一个iframe然后设置其src为服务端地址,而服务端同样输出一端js代码,也同时通过与子窗口之间的通信来完成数据的传输。
 假如父页面是baidu.com/a.html,iframe嵌入的页面为google.com/b.html(此处省略了域名等url属性),要实现此两个页面间的通信可以通过以下方法。

 b.html内容:

try {  
    parent.location.hash = 'data';  
} catch (e) {  
    // ie、chrome的安全机制无法修改parent.location.hash,  
    var ifrproxy = document.createElement('iframe');  
    ifrproxy.style.display = 'none';  
    ifrproxy.src = "http://www.baidu.com/proxy.html#data";  
    document.body.appendChild(ifrproxy);  
}

 proxy.html内容:

//因为parent.parent(即baidu.com/a.html)和baidu.com/proxy.html属于同一个域,所以可以改变其location.hash的值  
parent.parent.location.hash = self.location.hash.substring(1);
 6、Nginx配置

  利用nginx作为反向代理

server {
    listen      80; #监听80端口,可以改成其他端口
    server_name  localhost; # 当前服务的域名
    #charset koi8-r;
    #access_log  logs/host.access.log  main;

    location / {
        proxy_pass http://localhost:81;
        proxy_redirect default;
    }

   location /apis { #添加访问目录为/apis的代理配置
       rewrite  ^/apis/(.*)$ /$1 break;
       proxy_pass  http://localhost:82;
   }
   #....省略下面的配置
}

参考

知乎-前端跨域知识总结
CSDN-前端跨域知识总结

上一篇 下一篇

猜你喜欢

热点阅读