为何会存在跨域问题
因为出于安全考虑,浏览器规定JavaScript不能操做其余域下的页面DOM,不能接受其余域下的xhr请求(不仅是js,引用非同域下的字体文件,还有canvas引用非同域下的图片,也被同源策略所约束)
只要协议、域名、端口有一者不一样,就被视为非同域。css
如何解决
要解决跨域问题,就要绕过浏览器对js的限制,另辟蹊径html
这是最简单,也是最流行的跨域解决方案,它利用script标签不受同源策略的影响,解决跨域,须要后台配合,返回特殊格式的数据前端
前端git
<script> function JSONP(link) { let script=document.createElement("script"); script.src=link; document.body.appendChild(script); } function getUser(data) { console.log(data);// todo } const API_URL_USER='http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=getUser'; // 这里以爱奇艺的接口为例(来源网络,侵删) JSONP(API_URL_USER); </script>
后端github
// Express(Nodejs) // mock data const USERS=[ {name:"Tom",age:23}, {name:"Jack",age:23} ]; app.get("/user",function (req,res) { let cbName=req.query["callback"]; // 这里作一个容错处理 res.send(` try{ ${cbName}(${JSON.stringify(USRES)}); }catch(ex) { console.error("The data is invalid"); } `); });
跨域资源共享,是W3C的一个标准,它容许浏览器发送跨域服务器的请求,CORS须要浏览器和服务器同时支持json
后端canvas
简单请求和非简单请求详情,请阅读阮一峰老师的博文,这里再也不敖述segmentfault
app.use(function (req,res,next){ res.header('Access-Control-Allow-Origin', 'http://localhost:6666'); // 容许跨域的白名单,通常不建议使用 * 号 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); // 容许请求的方法,非简单请求,会进行预检 res.header('Access-Control-Allow-Headers', 'Content-Type'); // 容许请求携带的头信息,非简单请求,会进行预检 res.header('Access-Control-Allow-Credentials','true'); // 容许发送cookie,这里前端xhr也须要一块儿配置 `xhr.withCredentials=true` next(); });
只要是在与你同域下的服务器,新建一个代理(服务端不存在同源策略),将你的跨域请求所有代理转发后端
后端api
const proxy=require("http-proxy-middleware"); // 这里使用这个中间件完成代理 app.use('/api', proxy("http://b.com")); // http://a.com/api -> http://b.com/api
MDN里解释道它是获取/设置窗口的名称
,由于的它在不一样页面甚至域名加载后值都不会改变,该属性也被用于做为 JSONP 的一个更安全的备选来提供跨域通讯(cross-domain messaging)
前端
<!--http://a.com/page1.html--> <script> function request(url,callback) { let iframe=document.createElement("iframe"); let isFirst=true; iframe.style.display="none"; iframe.addEventListener("load",function () { if (isFirst) { isFirst=false; // 防止iframe循环加载 iframe.src="http://a.com/page2.html"; callback && callback(iframe.contentWindow.name); iframe.remove(); } }); iframe.src=url; } requeset("http://b.com/user",function (data) { console.log(data); // todo }); </script>
后端
// Express(Nodejs) // mock data const USERS=[ {name:"Tom",age:23}, {name:"Jack",age:23} ]; app.get("/user",function (req,res) { res.send(` <script> ;window.name=${JSON.stringify(USERS)}; </script> `); });
这个使用状况有限,例如
http://a.c.com
http://b.c.com
主域相同时,分别设置他们页面的document.domain="c.com";
嵌套两层iframe,达到第一层与第三层同域,就能够互相通讯了
<!--http://a.com/page1.html--> <script> let iframe=document.createElement("iframe"); iframe.style.display="none"; iframe.src="http://b.com/user.html"; window.addEventListener("hashchange",function () { console.log(location.hash.slice(1)); // todo }); </script>
<!--http://b.com/user.html--> <script> let iframe=document.createElement("iframe"); iframe.style.display="none"; function getUserData() { fetch("http://b.com/user") .then(res=>{ let data=res.json(); iframe.src=`http://a.com/page2.html#${data}`; }); } getUserData(); window.addEventListener("hashchange",function () { getUserData(); }); </script>
<script> top.location.hash=window.location.hash; </script>
这个只能发出去请求,没法获取到服务器的响应,经常用于网站流量统计
let img=new Image(); img.addEventListener("load",function () { console.log("Send success"); // todo }); img.src="http://site.c.com/a.gif?count=666";
<!-- http://a.com --> <button id="sendBtn">从B接口获取用户数据</button> <iframe src="http://b.com" id="ifr"></iframe> <script> window.addEventListener("message",function({detail,origin}){ if (origin==="http://b.com") { // 最好判断下消息来源 if (detail.type==="set-user") { console.log(detail.data); // todo } } }); sendBtn.addEventListener("click",function () { ifr.contentWindow.postMessage({ type:"get-user", },"http://b.com"); }); </script>
<!-- http://b.com --> <script> window.addEventListener("messagae",function({detail,origin}){ if (origin==="http://a.com") { // 最好判断下消息来源 if (detail.type==="get-user") { fetch("http://b.com/user") .then(res=>{ top.contentWindow.postMessage({ type:"set-user", data:res.json(), // 假设接口返回的是json格式的数据 },"http://a.com"); }) } } }); </script>
这个须要后台配合返回特殊格式的数据,TL,DR 能够看这个demo
WebSocket是一种通讯协议,该协议不实行同源政策,
注意须要浏览器和服务器都支持的状况下
<script src="//cdn.bootcss.com/socket.io/1.7.2/socket.io.min.js"></script> <script> var io = io.connect('http://b.com'); io.on('data', function (data) { console.log(data); // 接受来自服务器的消息 }); </script>
后端
// Nodejs const server = require('http').createServer(); const io = require('socket.io')(server); io.on('connection', function (client) { client.emit('data', 'This message from "http://b.com"'); });