林东洲html
1 天前前端
想学习更多前端或编程知识,欢迎关注专栏: 敲代码,学编程 - 知乎专栏
阅读本文前,但愿你有必定的 JS/Node 基础,这里不另外介绍如何使用 ajax 作异步请求,若是不了解,能够先看:node
Ajax 知识体系大梳理 - 掘金nginx
最近在面试的时候常被问到如何解决跨域的问题,看了网上的一些文章后,发现许多文章都没有写清楚明白,使读者(我)感到困惑,因此今天我整理了一下经常使用跨域的技巧,写这篇关于跨域文章的目的在于:git
这篇文章的全部代码我放在了 happylindz/blog Github 上,建议你 clone 下来,方便你阅读代码,跟我一块儿测试。github
后面代码的测试环境:不考虑跨域的兼容性问题,旨在理解其思想面试
使用过 Ajax 的同窗都知道其便利性,能够在不向服务器提交完整的页面的状况下,实现局部更新页面。可是浏览器处于对安全方面的考虑,不容许跨域调用其余页面的对象,这对于咱们在注入 iframe 或是 ajax 应用上带来很多麻烦。ajax
简单说来,只有当协议,域名,端口相同的时候才算是同一个域名,不然均认为须要作跨域的处理。chrome
今天一共介绍七种经常使用跨域的方式,关于跨域大概能够分为 iframe 的跨域和纯粹的跨全域请求。npm
下面就先介绍三种跨全域的方法:
1. JSONP:
只要说到跨域,就必须聊到 JSONP,JSONP全称为:JSON with Padding,可用于解决主流浏览器的跨域数据访问的问题。
Web 页面上调用 js 文件不受浏览器同源策略的影响,因此经过 Script 便签能够进行跨域的请求:
实例:
后端逻辑:
//server.js const url = require('url'); require('http').createServer((req, res) => { const data = { x: 10 }; const callback = url.parse(req.url, true).query.callback; res.writeHead(200); res.end(`${callback}(${JSON.stringify(data)})`); }).listen(3000, '127.0.0.1'); console.log('启动服务,监听 127.0.0.1:3000');
经过 node server.js 启动服务,监听端口 3000,这样服务端就创建起来了
前端页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index.html</title> </head> <body> <script> function jsonpCallback(data) { alert('得到 X 数据:' + data.x); } </script> <script src="http://127.0.0.1:3000?callback=jsonpCallback"></script> </body> </html>
逻辑已经写好了,那如何来模拟一个跨域的场景呢?
这里咱们经过端口号的不一样来模拟跨域的场景,经过 http://127.0.0.1:8080 端口来访问页面。先经过 npm 下载 http-server 模块:
nom install -g http-server
而且在页面同目录下输入:
http-server
这样就能够经过端口 8080 访问 index.html 刚才那个页面了,至关因而开启两个监听不一样端口的 http 服务器,经过页面中的请求来模拟跨域的场景。打开浏览器,访问 http://127.0.0.1:8080 就能够看到从 http://127.0.0.1:3000 获取到的数据了。
至此,经过 JSONP 跨域获取数据已经成功了,可是经过这种事方式也存在着必定的优缺点:
优势:
缺点:
2. CORS:
CORS 是一个 W3C 标准,全称是"跨域资源共享"(Cross-origin resource sharing)它容许浏览器向跨源服务器,发出 XMLHttpRequest 请求,从而克服了 ajax 只能同源使用的限制。
CORS 须要浏览器和服务器同时支持才能够生效,对于开发者来讲,CORS 通讯与同源的 ajax 通讯没有差异,代码彻底同样。浏览器一旦发现 ajax 请求跨源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感受。
所以,实现 CORS 通讯的关键是服务器。只要服务器实现了 CORS 接口,就能够跨源通讯。
首先前端先建立一个 index.html 页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CORS</title> </head> <body> <script> const xhr = new XMLHttpRequest(); xhr.open('GET', 'http://127.0.0.1:3000', true); xhr.onreadystatechange = function() { if(xhr.readyState === 4 && xhr.status === 200) { alert(xhr.responseText); } } xhr.send(null); </script> </body> </html>
这彷佛跟一次正常的异步 ajax 请求没有什么区别,关键是在服务端收到请求后的处理:
require('http').createServer((req, res) => { res.writeHead(200, { 'Access-Control-Allow-Origin': 'http://localhost:8080' }); res.end('这是你要的数据:1111'); }).listen(3000, '127.0.0.1'); console.log('启动服务,监听 127.0.0.1:3000');
关键是在于设置相应头中的 Access-Control-Allow-Origin,该值要与请求头中 Origin 一致才能生效,不然将跨域失败。
接下来再次开启两个 http 服务器进程:
打开浏览器访问 http://localhost:8080 就能够看到:
成功的关键在于 Access-Control-Allow-Origin 是否包含请求页面的域名,若是不包含的话,浏览器将认为这是一次失败的异步请求,将会调用 xhr.onerror 中的函数。
CORS 的优缺点:
这里只是对 CORS 作一个简单的介绍,若是想更详细地了解其原理的话,能够看看下面这篇文章:
3. Server Proxy:
服务器代理,顾名思义,当你须要有跨域的请求操做时发送请求给后端,让后端帮你代为请求,而后最后将获取的结果发送给你。
假设有这样的一个场景,你的页面须要获取 CNode:Node.js专业中文社区 论坛上一些数据,如经过 https://cnodejs.org/api/v1/topics,当时由于不一样域,因此你能够将请求后端,让其对该请求代为转发。
代码以下:
const url = require('url'); const http = require('http'); const https = require('https'); const server = http.createServer((req, res) => { const path = url.parse(req.url).path.slice(1); if(path === 'topics') { https.get('https://cnodejs.org/api/v1/topics', (resp) => { let data = ""; resp.on('data', chunk => { data += chunk; }); resp.on('end', () => { res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(data); }); }) } }).listen(3000, '127.0.0.1'); console.log('启动服务,监听 127.0.0.1:3000');
经过代码你能够看出,当你访问 http://127.0.0.1:3000 的时候,服务器收到请求,会代你发送请求https://cnodejs.org/api/v1/topics 最后将获取到的数据发送给浏览器。
一样地开启服务:
打开浏览器访问 http://localhost:3000/topics,就能够看到
跨域请求成功。
纯粹的跨全域请求的方式已经介绍完了,另外介绍四种经过 iframe 跨域与其它页面通讯的方式。
4. location.hash:
在 url 中,http://www.baidu.com#helloworld 的 "#helloworld" 就是 location.hash,改变 hash 值不会致使页面刷新,因此能够利用 hash 值来进行数据的传递,固然数据量是有限的。
假设 localhost:8080 下有文件 cs1.html 要和 localhost:8081 下的 cs2.html 传递消息,cs1.html 首先建立一个隐藏的 iframe,iframe 的 src 指向 localhost:8081/cs2.html,这时的 hash 值就能够作参数传递。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CS1</title> </head> <body> <script> // http://localhost:8080/cs1.html let ifr = document.createElement('iframe'); ifr.style.display = 'none'; ifr.src = "http://localhost:8081/cs2.html#data"; document.body.appendChild(ifr); function checkHash() { try { let data = location.hash ? location.hash.substring(1) : ''; console.log('得到到的数据是:', data); }catch(e) { } } window.addEventListener('hashchange', function(e) { console.log('得到的数据是:', location.hash.substring(1)); }); </script> </body> </html>
cs2.html 收到消息后经过 parent.location.hash 值来修改 cs1.html 的 hash 值,从而达到数据传递。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CS2</title> </head> <body> <script> // http://locahost:8081/cs2.html switch(location.hash) { case "#data": callback(); break; } function callback() { const data = "some number: 1111" try { parent.location.hash = data; }catch(e) { // ie, chrome 下的安全机制没法修改 parent.location.hash // 因此要利用一个中间的代理 iframe var ifrproxy = document.createElement('iframe'); ifrproxy.style.display = 'none'; ifrproxy.src = 'http://localhost:8080/cs3.html#' + data; // 该文件在请求域名的域下 document.body.appendChild(ifrproxy); } } </script> </body> </html>
因为两个页面不在同一个域下IE、Chrome不容许修改parent.location.hash的值,因此要借助于 localhost:8080 域名下的一个代理 iframe 的 cs3.html 页面
<script> parent.parent.location.hash = self.location.hash.substring(1); </script>
以后老规矩,开启两个 http 服务器:
这里为了图方便,将 cs1,2,3 都放在同个文件夹下,实际状况的话 cs1.html 和 cs3.html 要与 cs2.html 分别放在不一样的服务器才对。
以后打开浏览器访问 localhost:8080/cs1.html,注意不是 8081,就能够看到获取到的数据了,此时页面的 hash 值也已经改变。
固然这种方法存在着诸多的缺点:
5. window.name:
window.name(通常在 js 代码里出现)的值不是一个普通的全局变量,而是当前窗口的名字,这里要注意的是每一个 iframe 都有包裹它的 window,而这个 window 是top window 的子窗口,而它天然也有 window.name 的属性,window.name 属性的神奇之处在于 name 值在不一样的页面(甚至不一样域名)加载后依旧存在(若是没修改则值不会变化),而且能够支持很是长的 name 值(2MB)。
举个简单的例子:
你在某个页面的控制台输入:
window.name = "Hello World"; window.location = "http://www.baidu.com";
页面跳转到了百度首页,可是 window.name 却被保存了下来,仍是 Hello World,跨域解决方案彷佛能够呼之欲出了:
首先建立 a.html 文件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>a.html</title> </head> <body> <script> let data = ''; const ifr = document.createElement('iframe'); ifr.src = "http://localhost:8081/b.html"; ifr.style.display = 'none'; document.body.appendChild(ifr); ifr.onload = function() { ifr.onload = function() { data = ifr.contentWindow.name; console.log('收到数据:', data); } ifr.src = "http://localhost:8080/c.html"; } </script> </body> </html>
以后在建立 b.html 文件:
<script> window.name = "你想要的数据!"; </script>
http://localhost:8080/a.html 在请求远端服务器 http://localhost:8081/b.html 的数据,咱们能够在该页面下新建一个 iframe,该 iframe 的 src 属性指向服务器地址,(利用 iframe 标签的跨域能力),服务器文件 b.html 设置好 window.name 的值。
可是因为 a.html 页面和该页面 iframe 的 src 若是不一样源的话,则没法操做 iframe 里的任何东西,因此就取不到 iframe 的 name 值,因此咱们须要在 b.html 加载完后从新换个 src 去指向一个同源的 html 文件,或者设置成 'about:blank;' 都行,这时候我只要在 a.html 相同目录下新建一个 c.html 的空页面便可。若是不从新指向 src 的话直接获取的 window.name 的话会报错:
老规矩,打开两个 http 服务器:
打开浏览器就能够看到结果:
6. postMessage:
postMessage 是 HTML5 新增长的一项功能,跨文档消息传输(Cross Document Messaging),目前:Chrome 2.0+、Internet Explorer 8.0+, Firefox 3.0+, Opera 9.6+, 和 Safari 4.0+ 都支持这项功能,使用起来也特别简单。
首先建立 a.html 文件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>a.html</title> </head> <body> <iframe src="http://localhost:8081/b.html" style='display: none;'></iframe> <script> window.onload = function() { let targetOrigin = 'http://localhost:8081'; window.frames[0].postMessage('我要给你发消息了!', targetOrigin); } window.addEventListener('message', function(e) { console.log('a.html 接收到的消息:', e.data); }); </script> </body> </html>
建立一个 iframe,使用 iframe 的一个方法 postMessage 能够想 http://localhost:8081/b.html 发送消息,而后监听 message,能够得到其余文档发来的消息。
一样的 b.html 文件:
<script> window.addEventListener('message', function(e) { if(e.source != window.parent) { return; } let data = e.data; console.log('b.html 接收到的消息:', data); parent.postMessage('我已经接收到消息了!', e.origin); }); </script>
一样的开启 http 服务器:
打开浏览器一样能够看到:
对 postMessage 感兴趣的详细内容能够看看教程:
7. document.domain:
对于主域相同而子域不一样的状况下,能够经过设置 document.domain 的办法来解决,具体作法是能够在 http://www.example.com/a.html 和 http://sub.example.com/b.html 两个文件分别加上 document.domain = "a.com";而后经过 a.html 文件建立一个 iframe,去控制 iframe 的 window,从而进行交互,固然这种方法只能解决主域相同而二级域名不一样的状况,若是你异想天开的把 script.example.com 的 domain 设为 qq.com 显然是没用的,那么如何测试呢?
测试的方式稍微复杂点,须要安装 nginx 作域名映射,若是你电脑没有安装 nginx,请先去安装一下: nginx news
先建立一个 a.html 文件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>a.html</title> </head> <body> <script> document.domain = 'example.com'; let ifr = document.createElement('iframe'); ifr.src = 'http://sub.example.com/b.html'; ifr.style.display = 'none'; document.body.append(ifr); ifr.onload = function() { let win = ifr.contentWindow; alert(win.data); } </script> </body> </html>
在建立一个 b.html 文件:
<script> document.domain = 'example.com'; window.data = '传送的数据:1111'; </script>
以后打开 http 服务器:
这时候只是开启了两个 http 服务器,还须要经过 nginx 作域名映射,将 Example Domain 映射到 localhost:8080,sub.example.com 映射到 localhost:8081 上
打开操做系统下的 hosts 文件:mac 是位于 /etc/hosts 文件,并添加:
127.0.0.1 www.example.com 127.0.0.1 sub.example.com
这样在浏览器打开这两个网址后就会访问本地的服务器。
以后打开 nginx 的配置文件:/usr/local/etc/nginx/nginx.conf,并在 http 模块里添加:
上面代码的意思是:若是访问本地的域名是 Example Domain,就由 localhost:8080 代理该请求。
因此咱们这时候在打开浏览器访问 Example Domain 的时候其实访问的就是本地服务器 localhost:8080。
最后打开浏览器访问 http://www.example.com/a.html 就能够看到结果:
8. flash:
这种方式我没有尝试过,很差往下定论,感兴趣的话能够上网搜看看教程。
前面八种跨域方式我已经所有讲完,其实讲道理,经常使用的也就是前三种方式,后面四种更多时候是一些小技巧,虽然在工做中不必定会用到,可是若是你在面试过程当中可以提到这些跨域的技巧,无疑在面试官的心中是一个加分项。
上面阐述方法的时候可能有些讲的不明白,但愿在阅读的过程当中建议你跟着我敲代码,当你打开浏览器看到结果的时候,你也就能掌握到这种方法。