摘要: 完全掌握跨域。javascript
先后端数据交互常常会碰到请求跨域,什么是跨域,以及有哪几种跨域方式,这是本文要探讨的内容。css
本文完整的源代码请猛戳GitHub博客,纸上得来终觉浅,建议动手敲敲代码html
同源策略是一种约定,它是浏览器最核心也最基本的安全功能,若是缺乏了同源策略,浏览器很容易受到XSS、CSFR等攻击。所谓同源是指"协议+域名+端口"三者相同,即使两个不一样的域名指向同一个ip地址,也非同源。前端
同源策略限制内容有:java
可是有三个标签是容许跨域加载资源:node
<img src=XXX>
<link href=XXX>
<script src=XXX>
当协议、子域名、主域名、端口号中任意一个不相同时,都算做不一样域。不一样域之间相互请求资源,就算做“跨域”。常见跨域场景以下图所示:jquery
特别说明两点:webpack
第一:若是是协议和端口形成的跨域问题“前台”是无能为力的。nginx
第二:在跨域问题上,仅仅是经过“URL的首部”来识别而不会根据域名对应的IP地址是否相同来判断。“URL的首部”能够理解为“协议, 域名和端口必须匹配”。git
这里你或许有个疑问:请求跨域了,那么请求到底发出去没有?
跨域并非请求发不出去,请求能发出去,服务端能收到请求并正常返回结果,只是结果被浏览器拦截了。你可能会疑问明明经过表单的方式能够发起跨域请求,为何 Ajax 就不会?由于归根结底,跨域是为了阻止用户读取到另外一个域名下的内容,Ajax 能够获取响应,浏览器认为这不安全,因此拦截了响应。可是表单并不会获取新的内容,因此能够发起跨域请求。同时也说明了跨域并不能彻底阻止 CSRF,由于请求毕竟是发出去了。
1) JSONP原理
利用 <script> 标签没有跨域限制的漏洞,网页能够获得从其余来源动态产生的 JSON 数据。JSONP请求必定须要对方的服务器作支持才能够。
2) JSONP和AJAX对比
JSONP和AJAX相同,都是客户端向服务器端发送请求,从服务器端获取数据的方式。但AJAX属于同源策略,JSONP属于非同源策略(跨域请求)
3) JSONP优缺点
JSONP优势是简单兼容性好,可用于解决主流浏览器的跨域数据访问的问题。缺点是仅支持get方法具备局限性,不安全可能会遭受XSS攻击。
4) JSONP的实现流程
<script>
标签,把那个跨域的API数据接口地址,赋值给script的src,还要在这个地址中向服务器传递该函数名(能够经过问号传参:?callback=show)。
show('我不爱你')
。在开发中可能会遇到多个 JSONP 请求的回调函数名是相同的,这时候就须要本身封装一个 JSONP函数。
// index.html function jsonp({ url, params, callback }) { return new Promise((resolve, reject) => { let script = document.createElement('script') window[callback] = function(data) { resolve(data) document.body.removeChild(script) } params = { ...params, callback } // wd=b&callback=show let arrs = [] for (let key in params) { arrs.push(`${key}=${params[key]}`) } script.src = `${url}?${arrs.join('&')}` document.body.appendChild(script) }) } jsonp({ url: 'http://localhost:3000/say', params: { wd: 'Iloveyou' }, callback: 'show' }).then(data => { console.log(data) })
上面这段代码至关于向http://localhost:3000/say?wd=Iloveyou&callback=show
这个地址请求数据,而后后台返回show('我不爱你')
,最后会运行show()这个函数,打印出'我不爱你'
// server.js let express = require('express') let app = express() app.get('/say', function(req, res) { let { wd, callback } = req.query console.log(wd) // Iloveyou console.log(callback) // show res.end(`${callback}('我不爱你')`) }) app.listen(3000)
5) jQuery的jsonp形式
JSONP都是GET和异步请求的,不存在其余的请求方式和同步请求,且jQuery默认就会给JSONP的请求清除缓存。
$.ajax({ url:"http://crossdomain.com/jsonServerResponse", dataType:"jsonp", type:"get",//能够省略 jsonpCallback:"show",//->自定义传递给服务器的函数名,而不是使用jQuery自动生成的,可省略 jsonp:"callback",//->把传递函数名的那个形参callback,可省略 success:function (data){ console.log(data);} });
CORS 须要浏览器和后端同时支持。IE 8 和 9 须要经过 XDomainRequest 来实现。
浏览器会自动进行 CORS 通讯,实现 CORS 通讯的关键是后端。只要后端实现了 CORS,就实现了跨域。
服务端设置 Access-Control-Allow-Origin 就能够开启 CORS。 该属性表示哪些域名能够访问资源,若是设置通配符则表示全部网站均可以访问资源。
虽然设置 CORS 和前端没什么关系,可是经过这种方式解决跨域问题的话,会在发送请求时出现两种状况,分别为简单请求和复杂请求。
1) 简单请求
只要同时知足如下两大条件,就属于简单请求
条件1:使用下列方法之一:
条件2:Content-Type 的值仅限于下列三者之一:
请求中的任意 XMLHttpRequestUpload 对象均没有注册任何事件监听器; XMLHttpRequestUpload 对象可使用 XMLHttpRequest.upload 属性访问。
2) 复杂请求
不符合以上条件的请求就确定是复杂请求了。
复杂请求的CORS请求,会在正式通讯以前,增长一次HTTP查询请求,称为"预检"请求,该请求是 option 方法的,经过该请求来知道服务端是否容许跨域请求。
咱们用PUT
向后台请求时,属于复杂请求,后台需作以下配置:
// 容许哪一个方法访问我 res.setHeader('Access-Control-Allow-Methods', 'PUT') // 预检的存活时间 res.setHeader('Access-Control-Max-Age', 6) // OPTIONS请求不作任何处理 if (req.method === 'OPTIONS') { res.end() } // 定义后台返回的内容 app.put('/getData', function(req, res) { console.log(req.headers) res.end('我不爱你') })
接下来咱们看下一个完整复杂请求的例子,而且介绍下CORS请求相关的字段
// index.html let xhr = new XMLHttpRequest() document.cookie = 'name=xiamen' // cookie不能跨域 xhr.withCredentials = true // 前端设置是否带cookie xhr.open('PUT', 'http://localhost:4000/getData', true) xhr.setRequestHeader('name', 'xiamen') xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) { console.log(xhr.response) //获得响应头,后台需设置Access-Control-Expose-Headers console.log(xhr.getResponseHeader('name')) } } } xhr.send() //server1.js let express = require('express'); let app = express(); app.use(express.static(__dirname)); app.listen(3000); //server2.js let express = require('express') let app = express() let whitList = ['http://localhost:3000'] //设置白名单 app.use(function(req, res, next) { let origin = req.headers.origin if (whitList.includes(origin)) { // 设置哪一个源能够访问我 res.setHeader('Access-Control-Allow-Origin', origin) // 容许携带哪一个头访问我 res.setHeader('Access-Control-Allow-Headers', 'name') // 容许哪一个方法访问我 res.setHeader('Access-Control-Allow-Methods', 'PUT') // 容许携带cookie res.setHeader('Access-Control-Allow-Credentials', true) // 预检的存活时间 res.setHeader('Access-Control-Max-Age', 6) // 容许返回的头 res.setHeader('Access-Control-Expose-Headers', 'name') if (req.method === 'OPTIONS') { res.end() // OPTIONS请求不作任何处理 } } next() }) app.put('/getData', function(req, res) { console.log(req.headers) res.setHeader('name', 'jw') //返回一个响应头,后台需设置 res.end('我不爱你') }) app.get('/getData', function(req, res) { console.log(req.headers) res.end('我不爱你') }) app.use(express.static(__dirname)) app.listen(4000)
上述代码由http://localhost:3000/index.html
向http://localhost:4000/
跨域请求,正如咱们上面所说的,后端是实现 CORS 通讯的关键。
给你们推荐一个好用的BUG监控工具Fundebug,欢迎免费试用!
postMessage是HTML5 XMLHttpRequest Level 2中的API,且是为数很少能够跨域操做的window属性之一,它可用于解决如下方面的问题:
postMessage()方法容许来自不一样源的脚本采用异步方式进行有限的通讯,能够实现跨文本档、多窗口、跨域消息传递。
otherWindow.postMessage(message, targetOrigin, [transfer]);
接下来咱们看个例子: http://localhost:3000/a.html
页面向http://localhost:4000/b.html
传递“我爱你”,而后后者传回"我不爱你"。
// a.html <iframe src="http://localhost:4000/b.html" frameborder="0" id="frame" onload="load()"></iframe> //等它加载完触发一个事件 //内嵌在http://localhost:3000/a.html <script> function load() { let frame = document.getElementById('frame') frame.contentWindow.postMessage('我爱你', 'http://localhost:4000') //发送数据 window.onmessage = function(e) { //接受返回数据 console.log(e.data) //我不爱你 } } </script> // b.html window.onmessage = function(e) { console.log(e.data) //我爱你 e.source.postMessage('我不爱你', e.origin) }
Websocket是HTML5的一个持久化的协议,它实现了浏览器与服务器的全双工通讯,同时也是跨域的一种解决方案。WebSocket和HTTP都是应用层协议,都基于 TCP 协议。可是 WebSocket 是一种双向通讯协议,在创建链接以后,WebSocket 的 server 与 client 都能主动向对方发送或接收数据。同时,WebSocket 在创建链接时须要借助 HTTP 协议,链接创建好了以后 client 与 server 之间的双向通讯就与 HTTP 无关了。
原生WebSocket API使用起来不太方便,咱们使用Socket.io
,它很好地封装了webSocket接口,提供了更简单、灵活的接口,也对不支持webSocket的浏览器提供了向下兼容。
咱们先来看个例子:本地文件socket.html向localhost:3000
发生数据和接受数据
// socket.html <script> let socket = new WebSocket('ws://localhost:3000'); socket.onopen = function () { socket.send('我爱你');//向服务器发送数据 } socket.onmessage = function (e) { console.log(e.data);//接收服务器返回的数据 } </script> // server.js let express = require('express'); let app = express(); let WebSocket = require('ws');//记得安装ws let wss = new WebSocket.Server({port:3000}); wss.on('connection',function(ws) { ws.on('message', function (data) { console.log(data); ws.send('我不爱你') }); })
实现原理:同源策略是浏览器须要遵循的标准,而若是是服务器向服务器请求就无需遵循同源策略。
代理服务器,须要作如下几个步骤:
咱们先来看个例子:本地文件index.html文件,经过代理服务器http://localhost:3000
向目标服务器http://localhost:4000
请求数据。
// index.html(http://127.0.0.1:5500) <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script> $.ajax({ url: 'http://localhost:3000', type: 'post', data: { name: 'xiamen', password: '123456' }, contentType: 'application/json;charset=utf-8', success: function(result) { console.log(result) // {"title":"fontend","password":"123456"} }, error: function(msg) { console.log(msg) } }) </script> // server1.js 代理服务器(http://localhost:3000) const http = require('http') // 第一步:接受客户端请求 const server = http.createServer((request, response) => { // 代理服务器,直接和浏览器直接交互,须要设置CORS 的首部字段 response.writeHead(200, { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': '*', 'Access-Control-Allow-Headers': 'Content-Type' }) // 第二步:将请求转发给服务器 const proxyRequest = http .request( { host: '127.0.0.1', port: 4000, url: '/', method: request.method, headers: request.headers }, serverResponse => { // 第三步:收到服务器的响应 var body = '' serverResponse.on('data', chunk => { body += chunk }) serverResponse.on('end', () => { console.log('The data is ' + body) // 第四步:将响应结果转发给浏览器 response.end(body) }) } ) .end() }) server.listen(3000, () => { console.log('The proxyServer is running at http://localhost:3000') }) // server2.js(http://localhost:4000) const http = require('http') const data = { title: 'fontend', password: '123456' } const server = http.createServer((request, response) => { if (request.url === '/') { response.end(JSON.stringify(data)) } }) server.listen(4000, () => { console.log('The server is running at http://localhost:4000') })
上述代码通过两次跨域,值得注意的是浏览器向代理服务器发送请求,也遵循同源策略,最后在index.html文件打印出{"title":"fontend","password":"123456"}
实现原理相似于Node中间件代理,须要你搭建一个中转nginx服务器,用于转发请求。
使用nginx反向代理实现跨域,是最简单的跨域方式。只须要修改nginx的配置便可解决跨域问题,支持全部浏览器,支持session,不须要修改任何代码,而且不会影响服务器性能。
实现思路:经过nginx配置一个代理服务器(域名与domain1相同,端口不一样)作跳板机,反向代理访问domain2接口,而且能够顺便修改cookie中domain信息,方便当前域cookie写入,实现跨域登陆。
先下载nginx,而后将nginx目录下的nginx.conf修改以下:
// proxy服务器 server { listen 81; server_name www.domain1.com; location / { proxy_pass http://www.domain2.com:8080; #反向代理 proxy_cookie_domain www.domain2.com www.domain1.com; #修改cookie里域名 index index.html index.htm; # 当用webpack-dev-server等中间件代理接口访问nignx时,此时无浏览器参与,故没有同源限制,下面的跨域配置可不启用 add_header Access-Control-Allow-Origin http://www.domain1.com; #当前端只跨域不带cookie时,可为* add_header Access-Control-Allow-Credentials true; } }
最后经过命令行nginx -s reload
启动nginx
// index.html var xhr = new XMLHttpRequest(); // 前端开关:浏览器是否读写cookie xhr.withCredentials = true; // 访问nginx中的代理服务器 xhr.open('get', 'http://www.domain1.com:81/?user=admin', true); xhr.send(); // server.js var http = require('http'); var server = http.createServer(); var qs = require('querystring'); server.on('request', function(req, res) { var params = qs.parse(req.url.substring(2)); // 向前台写cookie res.writeHead(200, { 'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' // HttpOnly:脚本没法读取 }); res.write(JSON.stringify(params)); res.end(); }); server.listen('8080'); console.log('Server is running at port 8080...');
window.name属性的独特之处:name值在不一样的页面(甚至不一样域名)加载后依旧存在,而且能够支持很是长的 name 值(2MB)。
其中a.html和b.html是同域的,都是http://localhost:3000
;而c.html是http://localhost:4000
// a.html(http://localhost:3000/b.html) <iframe src="http://localhost:4000/c.html" frameborder="0" onload="load()" id="iframe"></iframe> <script> let first = true // onload事件会触发2次,第1次加载跨域页,并留存数据于window.name function load() { if(first){ // 第1次onload(跨域页)成功后,切换到同域代理页面 let iframe = document.getElementById('iframe'); iframe.src = 'http://localhost:3000/b.html'; first = false; }else{ // 第2次onload(同域b.html页)成功后,读取同域window.name中数据 console.log(iframe.contentWindow.name); } } </script>
b.html为中间代理页,与a.html同域,内容为空。
// c.html(http://localhost:4000/c.html) <script> window.name = '我不爱你' </script>
总结:经过iframe的src属性由外域转向本地域,跨域数据即由iframe的window.name从外域传递到本地域。这个就巧妙地绕过了浏览器的跨域访问限制,但同时它又是安全操做。
实现原理: a.html欲与c.html跨域相互通讯,经过中间页b.html来实现。 三个页面,不一样域之间利用iframe的location.hash传值,相同域之间直接js访问来通讯。
具体实现步骤:一开始a.html给c.html传一个hash值,而后c.html收到hash值后,再把hash值传递给b.html,最后b.html将结果放到a.html的hash值中。
一样的,a.html和b.html是同域的,都是http://localhost:3000
;而c.html是http://localhost:4000
// a.html <iframe src="http://localhost:4000/c.html#iloveyou"></iframe> <script> window.onhashchange = function () { //检测hash的变化 console.log(location.hash); } </script> // b.html <script> window.parent.parent.location.hash = location.hash //b.html将结果放到a.html的hash值中,b.html可经过parent.parent访问a.html页面 </script> // c.html console.log(location.hash); let iframe = document.createElement('iframe'); iframe.src = 'http://localhost:3000/b.html#idontloveyou'; document.body.appendChild(iframe);
该方式只能用于二级域名相同的状况下,好比 a.test.com 和 b.test.com 适用于该方式。
只须要给页面添加 document.domain ='test.com'
表示二级域名都相同就能够实现跨域。
实现原理:两个页面都经过js强制设置document.domain为基础主域,就实现了同域。
咱们看个例子:页面a.zf1.cn:3000/a.html
获取页面b.zf1.cn:3000/b.html
中a的值
// a.html <body> helloa <iframe src="http://b.zf1.cn:3000/b.html" frameborder="0" onload="load()" id="frame"></iframe> <script> document.domain = 'zf1.cn' function load() { console.log(frame.contentWindow.a); } </script> </body> // b.html <body> hellob <script> document.domain = 'zf1.cn' var a = 100; </script> </body>
Fundebug专一于JavaScript、微信小程序、微信小游戏、支付宝小程序、React Native、Node.js和Java线上应用实时BUG监控。 自从2016年双十一正式上线,Fundebug累计处理了9亿+错误事件,付费客户有Google、360、金山软件、百姓网等众多品牌企业。欢迎你们免费试用!