文章目錄
- 一、什么是跨域?
- 二、什么是同源策略?
- 三、解決方案
- 1.JSONP跨域
- 2.跨域資源共享(CORS)
- 簡單請求
- CORS跨域示例
- 3.nginx代理跨域
- nginx配置解決iconfont跨域
- nginx反向代理介面跨域
- 4.nodejs中間件代理跨域
- 5.document.domain + iframe跨域
- 6.location.hash + iframe跨域
- 7.window.name + iframe跨域
- 8.postMessage跨域
- 9.WebSocket協議跨域
- 10.瀏覽器開啟跨域
- 四、同源策略在防什么
- 五、總結
一、什么是跨域?
在前端領域中,跨域是指瀏覽器允許向服務器發送跨域請求,從而克服Ajax只能同源使用的限制,
??
??當跨域時會收到以下錯誤

二、什么是同源策略?
同源策略是一種約定,由Netscape公司1995年引入瀏覽器,它是瀏覽器最核心也最基本的安全功能,如果缺少了同源策略,瀏覽器很容易受到XSS、CSFR等攻擊,所謂同源是指"協議+域名+埠"三者相同,即便兩個不同的域名指向同一個ip地址,也非同源,
URL組成:

同源策略限制以下幾種行為:
- Cookie、LocalStorage 和 IndexDB 無法讀取
- DOM和JS物件無法獲得
- AJAX 請求不能發送
三、解決方案
1.JSONP跨域
原理:就是利用<script>標簽沒有跨域限制,通過<script>標簽src屬性,發送帶有callback引數的GET請求,服務端將介面回傳資料拼湊到callback函式中,回傳給瀏覽器,瀏覽器決議執行,從而前端拿到callback函式回傳的資料,
缺點:只能發送get一種請求,
實作:
1)原生JS實作:
<script>
var script = document.createElement('script');
script.type = 'text/javascript';
// 傳參一個回呼函式名給后端,方便后端回傳時執行這個在前端定義的回呼函式
script.src = 'http://www.domain2.com:8080/login?user=admin&callback=handleCallback';
document.head.appendChild(script);
// 回呼執行函式
function handleCallback(res) {
alert(JSON.stringify(res));
}
</script>
服務端回傳如下(回傳時即執行全域函式):
handleCallback({"success": true, "user": "admin"})
jquery Ajax實作:
$.ajax({
url: 'http://www.domain2.com:8080/login',
type: 'get',
dataType: 'jsonp', // 請求方式為jsonp
jsonpCallback: "handleCallback", // 自定義回呼函式名
data: {}
});
Vue axios實作:
this.$http = axios;
this.$http.jsonp('http://www.domain2.com:8080/login', {
params: {},
jsonp: 'handleCallback'
}).then((res) => {
console.log(res);
})
后端node.js代碼:
var querystring = require('querystring');
var http = require('http');
var server = http.createServer();
server.on('request', function(req, res) {
var params = querystring.parse(req.url.split('?')[1]);
var fn = params.callback;
// jsonp回傳設定
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.write(fn + '(' + JSON.stringify(params) + ')');
res.end();
});
server.listen('8080');
console.log('Server is running at port 8080...');
2.跨域資源共享(CORS)
CORS是一個W3C標準,全稱是"跨域資源共享"(Cross-origin resource sharing),
它允許瀏覽器向跨源服務器,發出XMLHttpRequest請求,從而克服了AJAX只能同源使用的限制,
CORS需要瀏覽器和服務器同時支持,目前,所有瀏覽器都支持該功能,IE瀏覽器不能低于IE10,
??瀏覽器將CORS跨域請求分為簡單請求和非簡單請求,
??只要同時滿足一下兩個條件,就屬于簡單請求
(1)使用下列方法之一:
- head
- get
- post
(2)請求的Heder是
- Accept
- Accept-Language
- Content-Language
- Content-Type: 只限于三個值:application/x-www-form-urlencoded、multipart/form-data、text/plain
不同時滿足上面的兩個條件,就屬于非簡單請求,瀏覽器對這兩種的處理,是不一樣的,
簡單請求
對于簡單請求,瀏覽器直接發出CORS請求,具體來說,就是在頭資訊之中,增加一個Origin欄位,
GET /cors HTTP/1.1
Origin: http://api.bob.com
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...
上面的頭資訊中,Origin欄位用來說明,本次請求來自哪個源(協議 + 域名 + 埠),服務器根據這個值,決定是否同意這次請求,
CORS跨域示例
原生ajax:
var xhr = new XMLHttpRequest(); // IE8/9需用window.XDomainRequest兼容
// 前端設定是否帶cookie
xhr.withCredentials = true;
xhr.open('post', 'http://www.domain2.com:8080/login', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=admin');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
jquery ajax:
$.ajax({
...
xhrFields: {
withCredentials: true // 前端設定是否帶cookie
},
crossDomain: true, // 會讓請求頭中包含跨域的額外資訊,但不會含cookie
...
});
3.nginx代理跨域
nginx代理跨域,實質和CORS跨域原理一樣,通過組態檔設定請求回應頭Access-Control-Allow-Origin…等欄位,
nginx配置解決iconfont跨域
瀏覽器跨域訪問js、css、img等常規靜態資源被同源策略許可,但iconfont字體檔案(eot|otf|ttf|woff|svg)例外,此時可在nginx的靜態資源服務器中加入以下配置,
location / {
add_header Access-Control-Allow-Origin *;
}
nginx反向代理介面跨域
跨域問題:同源策略僅是針對瀏覽器的安全策略,服務器端呼叫HTTP介面只是使用HTTP協議,不需要同源策略,也就不存在跨域問題,
實作思路:通過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;
}
}
4.nodejs中間件代理跨域
node中間件實作跨域代理,原理大致與nginx相同,都是通過啟一個代理服務器,實作資料的轉發,也可以通過設定cookieDomainRewrite引數修改回應頭中cookie中域名,實作當前域的cookie寫入,方便介面登錄認證,
使用node + express + http-proxy-middleware搭建一個proxy服務器,
前端代碼:
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();
中間件服務器代碼:
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...');
5.document.domain + iframe跨域
該方式只能用于二級域名相同的情況下,比如a.test.com和b.test.com適用于該方式, 只需要給頁面添加document.domain ='test.com’表示二級域名都相同就可以實作跨域,
www. baidu. com .
三級域 二級域 頂級域 根域
實作原理:兩個頁面都通過js強制設定document.domain為基礎主域,就實作了同域,
例子:
父視窗:(www.domain.com/a.html)
<iframe id="iframe" src="http://child.domain.com/b.html"></iframe>
<script>
document.domain = 'domain.com';
var user = 'admin';
</script>
子視窗:(child.domain.com/a.html)
<script>
document.domain = 'domain.com';
// 獲取父視窗中變數
console.log('get js data from parent ---> ' + window.parent.user);
</script>
6.location.hash + iframe跨域
實作原理: a欲與b跨域相互通信,通過中間頁c來實作, 三個頁面,不同域之間利用iframe的location.hash傳值,相同域之間直接js訪問來通信,
具體實作:A域:a.html -> B域:b.html -> A域:c.html,a與b不同域只能通過hash值單向通信,b與c也不同域也只能單向通信,但c與a同域,所以c可通過parent.parent訪問a頁面所有物件,
a.html:(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');
// 向b.html傳hash值
setTimeout(function() {
iframe.src = iframe.src + '#user=admin';
}, 1000);
// 開放給同域c.html的回呼方法
function onCallback(res) {
alert('data from c.html ---> ' + res);
}
</script>
b.html:(www.domain2.com/b.html)
<iframe id="iframe" src="http://www.domain1.com/c.html" style="display:none;"></iframe>
<script>
var iframe = document.getElementById('iframe');
// 監聽a.html傳來的hash值,再傳給c.html
window.onhashchange = function () {
iframe.src = iframe.src + location.hash;
};
</script>
c.html:(www.domain1.com/c.html)
<script>
// 監聽b.html傳來的hash值
window.onhashchange = function () {
// 再通過操作同域a.html的js回呼,將結果傳回
window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', ''));
};
</script>
7.window.name + iframe跨域
window.name屬性的獨特之處:name值在不同的頁面(甚至不同域名)加載后依舊存在,并且可以支持非常長的 name 值(2MB),
通過iframe的src屬性由外域轉向本地域,跨域資料即由iframe的window.name從外域傳遞到本地域,這個就巧妙地繞過了瀏覽器的跨域訪問限制,但同時它又是安全操作,
a.html:(www.domain1.com/a.html)
var proxy = function(url, callback) {
var state = 0;
var iframe = document.createElement('iframe');
// 加載跨域頁面
iframe.src = url;
// onl oad事件會觸發2次,第1次加載跨域頁,并留存資料于window.name
iframe.onload = function() {
if (state === 1) {
// 第2次onload(同域proxy頁)成功后,讀取同域window.name中資料
callback(iframe.contentWindow.name);
destoryFrame();
} else if (state === 0) {
// 第1次onload(跨域頁)成功后,切換到同域代理頁面
iframe.contentWindow.location = 'http://www.domain1.com/proxy.html';
state = 1;
}
};
document.body.appendChild(iframe);
// 獲取資料以后銷毀這個iframe,釋放記憶體;這也保證了安全(不被其他域frame js訪問)
function destoryFrame() {
iframe.contentWindow.document.write('');
iframe.contentWindow.close();
document.body.removeChild(iframe);
}
};
// 請求跨域b頁面資料
proxy('http://www.domain2.com/b.html', function(data){
alert(data);
});
proxy.html:(www.domain1.com/proxy.html)
中間代理頁,與a.html同域,內容為空即可,
b.html:(www.domain2.com/b.html)
<script>
window.name = 'This is domain2 data!';
</script>
8.postMessage跨域
postMessage
?postMessage是HTML5 XMLHttpRequest Level 2中的API,且是為數不多可以跨域操作的window屬性之一,它可用于解決以下方面的問題:
- 頁面和其打開的新視窗的資料傳遞
- 多視窗之間訊息傳遞
- 頁面與嵌套的iframe訊息傳遞
- 上面三個場景的跨域資料傳遞
otherWindow.postMessage(message, targetOrigin, [transfer]);
- otherWindow: 其他視窗的一個參考,比如 iframe 的 contentWindow 屬性、執行window.open回傳的視窗物件、或者是命名過或數值索引的window.frames,
- message: 將要發送到其他 window 的資料,
- targetOrigin: 通過視窗的 origin 屬性來指定哪些視窗能接收到訊息事件.
- transfer(可選) : 是一串和 message 同時傳遞的Transferable物件. 這些物件的所有權將被轉移給訊息的接收方,而發送一方將不再保有所有權
例子:
a.html:(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:(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>
9.WebSocket協議跨域
原理:這種方式本質沒有使用了 HTTP 的回應頭, 因此也沒有跨域的限制,
WebSocket protocol是HTML5一種新的協議,它實作了瀏覽器與服務器全雙工通信,同時允許跨域通訊,是server push技術的一種很好的實作,
在網路瀏覽器和服務器之間建立“套接字”連接,簡單地說:客戶端和服務器之間存在持久的連接,而且雙方都可以隨時開始發送資料,
前端代碼:
<script>
let socket = new WebSocket("ws://localhost:8080");
socket.onopen = function() {
socket.send("holle");
};
socket.onmessage = function(e) {
console.log(e.data);
};
</script>
后端代碼 :
const WebSocket = require("ws");
const server = new WebSocket.Server({ port: 8080 });
server.on("connection", function(socket) {
socket.on("message", function(data) {
socket.send(data);
});
});
10.瀏覽器開啟跨域
其實跨域問題是瀏覽器策略,源頭是他,關閉這個功能
Windows
找到你安裝的目錄
.\Google\Chrome\Application\chrome.exe --disable-web-security --user-data-dir=xxxx
Mac
~/Downloads/chrome-data這個目錄可以自定義.
/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary --disable-web-security --user-data-dir=~/Downloads/chrome-data
四、同源策略在防什么
跨域只存在于瀏覽器端,而瀏覽器為 web 提供訪問入口,我們在可以瀏覽器內打開很多頁面,正是這樣的開放形態,所以我們需要對他有所限制,就比如林子大了,什么鳥都有,我們需要有一個統一的規范來進行約定才能保障這個安全性,
- 限制不同源的請求,防止JavaScript代碼對非同源頁面的各種請求(CSRF攻擊)
例如用戶登錄 a 網站,同時新開 tab 打開了 b 網站,如果不限制同源, b 可以像 a 網站發起任何請求,會讓不法分子有機可趁, - 限制 dom 操作,對其他頁面DOM元素(通常包含敏感資訊,比如input標簽)的讀取()
釣魚網站
五、總結
- jsonp(只支持get請求,支持老的IE瀏覽器)適合加載不同域名的js、css,img等靜態資源;
- CORS(支持所有型別的HTTP請求,但瀏覽器IE10以下不支持)適合做ajax各種跨域請求;
- Nginx代理跨域和nodejs中間件跨域原理都相似,都是搭建一個服務器,直接在服務器端請求HTTP介面,這適合前后端分離的前端專案調后端介面,
- document.domain+iframe適合主域名相同,子域名不同的跨域請求,
- postMessage、websocket都是HTML5新特性,兼容性不是很好,只適用于主流瀏覽器和IE10+,

參考
https://segmentfault.com/a/1190000022398875
https://juejin.cn/post/6844903882083024910
本文鏈接https://blog.csdn.net/qq_39903567/article/details/115532420
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/275411.html
標籤:其他
上一篇:python3 加密模塊的實作(hashlib,hmac)
下一篇:關于多執行緒的學習(上)
