美文网首页
前端跨域总结

前端跨域总结

作者: 咆哮小狮子 | 来源:发表于2021-11-30 17:01 被阅读0次

声明

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

跨域

 1、什么是跨域

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

 2、同源策略

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


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

解决方案

 据我了解的,总结了以下几种方式,有其他方式的可以给我留言:
  • domain设置,只适用于子域
  • jsonp方法,只适用于get请求
  • CROS,(跨域资源共享协议),适用于各种请求
  • post Message,适用于父子网页iframe通信
  • location.hash, 数据直接暴露在了url中,数据容量和类型都有限
  • Nginx 代理
 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);
  • 简单请求
    有三个CORS字段需要加在响应头中,前面部分都是以Access-Control开头:

  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.postMessage(message, targetOrigin);

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属性),要实现此两个页面间的通信可以通过以下方法。

  • a.html传送数据到b.html
  • a.html下修改iframe的src为google.com/b.html#paco
  • b.html监听到url发生变化,触发相应操作
  • b.html传送数据到a.html,由于两个页面不在同一个域下IE、Chrome不允许修改parent.location.hash的值,所以要借助于父窗口域名下的一个代理iframe
  • b.html下创建一个隐藏的iframe,此iframe的src是baidu.com域下的,并挂上要传送的hash数据,如src=”http://www.baidu.com/proxy.html#data
  • proxy.html监听到url发生变化,修改a.html的url(因为a.html和proxy.html同域,所以proxy.html可修改a.html的url hash)
  • a.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-前端跨域知识总结

相关文章

  • 跨域解决方案(史上最易懂)

    跨域总结 1.跨域思路 跨域解决方案一般分为两种:前端解决,后端解决 1.1 前端解决方案 通过前端解决的思想就是...

  • 关于设置env等环境变量的思考

    1、如何处理跨域后台处理跨域前端处理跨域浏览器处理跨域 前端本地处理跨域:代理线上跨域的处理方式:Nginx反向代...

  • 前端跨域整理

    前言 原文地址:前端跨域总结博主博客地址:Damonare的个人博客 正文 1. 什么是跨域? 跨域一词从字面意思...

  • 前端跨域总结

    前言 关于前端跨域的解决方法的多种多样实在让人目不暇接。以前碰到一个公司面试的场景是这样的,好几个人一起在等待面试...

  • 前端跨域总结

    1. 什么是跨域? 跨域一词从字面意思看,就是跨域名嘛,但实际上跨域的范围绝对不止那么狭隘。具体概念如下:只要协议...

  • 前端跨域总结

    转载:http://damonare.github.io/2016/10/30/%E5%89%8D%E7%AB%A...

  • 前端跨域总结

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

  • 浅谈前端跨域问题

    最近由于公司的一个项目需求需要前端解决跨域问题,因此学习了下跨域的相关知识,这里做一个总结,方便后期查阅。在讲跨域...

  • H5 知识点 - 收藏集 - 掘金

    跨域解决方案总结 - 前端 - 掘金为什么需要跨域? 就得先知道同源策略. 同源策略 同源策略是为了保证数据的安全...

  • 前端跨域整理

    前言 原文地址:前端跨域总结 博主博客地址:Damonare的个人博客 相信每一个前端er对于跨域这两个字都不会陌...

网友评论

      本文标题:前端跨域总结

      本文链接:https://www.haomeiwen.com/subject/ksjdxrtx.html