1、什麼是跨域?css
跨域是指一個域下的文檔或者腳本去請求另外一個域下的資源。(廣義)html
廣義的跨域:前端
一、資源跳轉:連接跳轉、重定向、表單提交。vue
二、資源嵌入:<link>、<script>、<img>、<frame>等dom標籤;還有background:url()、html5
@font-face()等文件外鏈css。node
三、腳本請求:js發起的ajax請求、dom和js對象的跨域操做等。 jquery
狹義的跨域:是由瀏覽器「同源策略」限制的一類請求場景。webpack
2、同源策略ios
同源策略/SOP(same origin policy)是一種約定,由Netscape公司1995年引入瀏覽器,它是瀏覽器最核心,也是最基本的安全功能,若是缺乏了同源策略,瀏覽器很容易受到XSS、CSFR等攻擊。nginx
所謂的同源是指「協議+域名+端口」三者相同,即使兩個不一樣的域名指向同一個IP地址,也非同源。
同源策略限制如下幾種行爲:
一、Cookie、LocalSrorage、IndexDB沒法讀取。
二、DOM和JS對象沒法得到。
三、AJAX請求不能發送。
常見跨域場景:
3、跨域解決方案
-- 經過jsonp跨域
-- document.domain + iframe跨域
-- location.hash + iframe
-- window.name + iframe跨域
-- postMessage跨域
-- 跨域資源共享(CORS)
-- nginx代理跨域
-- nodejs中間件代理跨域
-- WebSocket協議跨域
一、經過jsonp跨域
一般爲了減輕Web服務器的負載、咱們把js、css、img等靜態資源分離到另外一臺獨立域名的服務器上,在html頁面中再經過相應的標籤從不一樣域名下加載靜態資源而被瀏覽器容許,也就是資源嵌入的方式(建立<script>標籤的方式)
(1)原生:
服務端返回:
(2)、jquery ajax實現:
(3)、angular實現:
(4)vue實現:
後臺node.js代碼實現:
二、document.domain+iframe跨域
該方式僅限於主域相同,子域不相同的跨域應用場景。
實現原理:兩個頁面都經過js強制設置document.domain爲基礎生成,就實現了同域。
(1)、父窗口:http://www.domain.com/a.html
(2)、子窗口:http://child.domain.com/b.html
三、location.hash+iframe跨域
實現原理:a和b跨域相互通訊,經過中間頁c來實現。3個頁面,不一樣域之間利用iframe的location.hash傳值,相互域之間直接js訪問來通訊。
具體實現:A域:a.html -> B域:b.html -> A域:c.html,a與b不一樣域只能經過hash值單向通訊,b與c也不一樣域也只能單向通訊,但c與a同域,因此c可經過parent.parent訪問a頁面全部對象。
(1)、a.html : http://www.domain1.com/a.html
(2)、b.html:http://www.domain2.com/b.html
(3)、c.html:http://www.domain1.com/c.html
四、window.name+iframe跨域
window.name屬性的獨特之處:name(大小限制2M)值在不一樣的頁面(甚至不一樣域名)加載後依舊存在。
(1)、a.html http://www.domain1.com/a.html
1 var proxy = function(url, callback) { 2 var state = 0; 3 var iframe = document.createElement('iframe'); 4 5 // 加載跨域頁面 6 iframe.src = url; 7 8 // onload事件會觸發2次,第1次加載跨域頁,並留存數據於window.name 9 iframe.onload = function() { 10 if (state === 1) { 11 // 第2次onload(同域proxy頁)成功後,讀取同域window.name中數據 12 callback(iframe.contentWindow.name); 13 destoryFrame(); 14 15 } else if (state === 0) { 16 // 第1次onload(跨域頁)成功後,切換到同域代理頁面 17 iframe.contentWindow.location = 'http://www.domain1.com/proxy.html'; 18 state = 1; 19 } 20 }; 21 22 document.body.appendChild(iframe); 23 24 // 獲取數據之後銷燬這個iframe,釋放內存;這也保證了安全(不被其餘域frame js訪問) 25 function destoryFrame() { 26 iframe.contentWindow.document.write(''); 27 iframe.contentWindow.close(); 28 document.body.removeChild(iframe); 29 } 30 }; 31 32 // 請求跨域b頁面數據 33 proxy('http://www.domain2.com/b.html', function(data){ 34 alert(data); 35 });
(2)、proxy.html http://www.domain1.com/proxy....
中間代理頁,與a.html同域,內容爲空便可。
(3)、b.html http://www.domain2.com/b.html
注意:經過iframe的src屬性有外域轉向本地域,跨域數據即由iframe的window.name從外域傳遞到本地域。這個就巧妙的繞過了瀏覽器的跨域訪問限制,同時它又是安全操做。
五、postMssage跨域
postMessage是HTML5 XMLHttpRequest Level 2中的API,且是爲數很少能夠跨域操做的window屬性之一,它能夠解決如下方面的問題。
(1)頁面和其餘打開的新窗口的數據傳遞。
(2)多窗口之間消息傳遞。
(3)頁面與嵌套的iframe消息傳遞。
(4)上面三個場景的跨域數據出傳遞。
用法:postMessage(data,origin)方法接受兩個參數。
data:html5規範支持任意基本類型或可複製的對象,但部分瀏覽器只支持字符串,因此傳參時最好用JSON.stringfy()序列化。
origin:協議+主機+端口號,也能夠設置「 * 」,表示能夠傳遞給任意窗口,若是要制定和當前窗口同源的話設置爲「/」。
① a.html http://www.domain1.com/a.html
<iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe> <script> var iframe = document.getElementById('iframe'); iframe.onload = function() { var data = { name: 'aym' }; // 向domain2傳送跨域數據 iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.domain2.com'); }; // 接受domain2返回數據 window.addEventListener('message', function(e) { alert('data from domain2 ---> ' + e.data); }, false); </script>
② b.html http://www.domain2.com/b.html
<script> // 接收domain1的數據 window.addEventListener('message', function(e) { alert('data from domain1 ---> ' + e.data); var data = JSON.parse(e.data); if (data) { data.number = 16; // 處理後再發回domain1 window.parent.postMessage(JSON.stringify(data), 'http://www.domain1.com'); } }, false); </script>
六、跨域資源共享(CORS)
普通跨域請求:只服務端設置Access - Control - Allow - Origin便可,前段不用設置,若是要帶cookie請求:
先後端都須要設置。
須要注意的是:因爲同源策略的限制,所讀取的cookie爲跨域請求接口所在域的cookie,而非當前頁。若是想實現當前頁cookie的寫入能夠參考nginx反向代理中設置proxy_cookie_domain和NodeJs中間件代理中cookieDomainRewite參數的設置。
目前,全部瀏覽器都支持該功能(IE8+,IE8/9須要使用XDomainRequest對象來支持CORS),CORS也應成爲主流的跨域解決方案。
(1)前端設置
① 原生ajax
實例代碼:
② Jquery ajax
③ vue框架
a、axios設置:
b、vue-resource設置:
(2)服務端設置
若後端設置成功,前端瀏覽器控制檯則不會出現跨域報錯信息,繁殖說明沒有成功。
① Java後臺:
② NodeJs後臺實例
var http = require('http'); var server = http.createServer(); var qs = require('querystring'); server.on('request', function(req, res) { var postData = ''; // 數據塊接收中 req.addListener('data', function(chunk) { postData += chunk; }); // 數據接收完畢 req.addListener('end', function() { postData = qs.parse(postData); // 跨域後臺設置 res.writeHead(200, { 'Access-Control-Allow-Credentials': 'true', // 後端容許發送Cookie 'Access-Control-Allow-Origin': 'http://www.domain1.com', // 容許訪問的域(協議+域名+端口) /* * 此處設置的cookie仍是domain2的而非domain1,由於後端也不能跨域寫cookie(nginx反向代理能夠實現), * 但只要domain2中寫入一次cookie認證,後面的跨域接口都能從domain2中獲取cookie,從而實現全部的接口都能跨域訪問 */ 'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' // HttpOnly的做用是讓js沒法讀取cookie }); res.write(JSON.stringify(postData)); res.end(); }); }); server.listen('8080'); console.log('Server is running at port 8080...');
七、nginx代理跨域
(1)nginx配置解決iconfont跨域
瀏覽器跨域訪問js、css、img等常規靜態資源被同源策略許可,可是iconfont字體文件(eot|otf|ttf|woff|svg)例外,此時可在 nginx的靜態資源服務器中加入如下配置。
(2)nginx反向代理接口跨域
跨域原理:同源策略是瀏覽器的安全策略,不是HTTP協議的一部分。服務器端滴哦阿勇HTTP接口只是使用HTTP協議,不會執 行JS腳本,不須要同源策略,也就不存在跨域問題。
實現思路:經過nginx配置一個代理服務器(域名與domain1相同,端口不一樣)作跳板機,反向代理作domain2接口,而且能夠 順便修改cookie中domain信息,方便當前域cookie寫入,實現跨域登陸。
nginx具體配置:
#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; } }
前端代碼示例:
var xhr = new XMLHttpRequest(); // 前端開關:瀏覽器是否讀寫cookie xhr.withCredentials = true; // 訪問nginx中的代理服務器 xhr.open('get', 'http://www.domain1.com:81/?user=admin', true); xhr.send();
Node.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...');
八、NodeJs中間件代理跨域
node中間件實現跨域代理,原理大體與nginx相同,都是經過啓動一個代理服務器,實現數據的轉發,
也可與經過設置 cookieDomainRewrite參數修改響應頭中cookie中域名,實現當前域的cookie寫入,方便接口登陸認證。
非vue框架的跨域(2次跨域):
利用node + express + http-proxy-middleware搭建一個proxy服務器。
(1)前端代碼示例:
var xhr = new XMLHttpRequest(); // 前端開關:瀏覽器是否讀寫cookie xhr.withCredentials = true; // 訪問http-proxy-middleware代理服務器 xhr.open('get', 'http://www.domain1.com:3000/login?user=admin', true); xhr.send();
(2)中間件服務器:
var express = require('express'); var proxy = require('http-proxy-middleware'); var app = express(); app.use('/', proxy({ // 代理跨域目標接口 target: 'http://www.domain2.com:8080', changeOrigin: true, // 修改響應頭信息,實現跨域並容許帶cookie onProxyRes: function(proxyRes, req, res) { res.header('Access-Control-Allow-Origin', 'http://www.domain1.com'); res.header('Access-Control-Allow-Credentials', 'true'); }, // 修改響應信息中的cookie域名 cookieDomainRewrite: 'www.domain1.com' // 能夠爲false,表示不修改 })); app.listen(3000); console.log('Proxy server is listen at port 3000...');
(3)NodeJs後臺同6
vue框架的跨域(1次跨域):
利用node + webpack + webpack-dev-server代理接口跨域。在開發環境下,因爲vue渲染服務和接口代理服務都是
webpack-dev- server同一個,因此頁面與代理接口之間再也不跨域,無須設置headers跨域信息了。
webpack.config.js部分配置:
module.exports = { entry: {}, module: {}, ... devServer: { historyApiFallback: true, proxy: [{ context: '/login', target: 'http://www.domain2.com:8080', // 代理跨域目標接口 changeOrigin: true, secure: false, // 當代理某些https服務報錯時用 cookieDomainRewrite: 'www.domain1.com' // 能夠爲false,表示不修改 }], noInfo: true } }
九、webSocket協議跨域
webSocket protocol是HTML5一種新的協議,它實現了瀏覽器域服務器全雙工通訊,同時容許跨域通信,是server push
技術的一種很好的實現。
原生WebSocket API使用起來不太方便,咱們使用Sockie.io,它很好的封裝了webSocket接口,提供了更簡潔、靈活的接口,也對不支 持webSocket的瀏覽器提供了向下兼容。
(1)前端代碼:
<div>user input:<input type="text"></div> <script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script> <script> var socket = io('http://www.domain2.com:8080'); // 鏈接成功處理 socket.on('connect', function() { // 監聽服務端消息 socket.on('message', function(msg) { console.log('data from server: ---> ' + msg); }); // 監聽服務端關閉 socket.on('disconnect', function() { console.log('Server socket has closed.'); }); }); document.getElementsByTagName('input')[0].onblur = function() { socket.send(this.value); }; </script>
(2)NodeJs Socket後臺:
var http = require('http'); var socket = require('socket.io'); // 啓http服務 var server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-type': 'text/html' }); res.end(); }); server.listen('8080'); console.log('Server is running at port 8080...'); // 監聽socket鏈接 socket.listen(server).on('connection', function(client) { // 接收信息 client.on('message', function(msg) { client.send('hello:' + msg); console.log('data from client: ---> ' + msg); }); // 斷開處理 client.on('disconnect', function() { console.log('Client socket has closed.'); }); });
原文出處:https://www.cnblogs.com/wangyfax/p/11710709.html