平時在開發中老是會遇到各類跨域問題,一直沒有很好地瞭解其中的原理,以及其各類實現方案。今天在這好好總結一下。
本文完整的源代碼請猛戳github博客,建議你們動手敲敲代碼。javascript
通常來講,當一個請求url的協議、域名、端口三者之間任意一個與當前頁面地址不一樣即爲跨域。
之因此會跨域,是由於受到了同源策略的限制,同源策略要求源相同才能正常進行通訊,即協議、域名、端口號都徹底一致。css
爲何會有同源策略呢?
同源政策的目的,是爲了保證用戶信息的安全,防止惡意的網站竊取數據。html
設想這樣一種狀況:A網站是一家銀行,用戶登陸之後,又去瀏覽其餘網站。若是其餘網站能夠讀取A網站的 Cookie,會發生什麼?前端
很顯然,若是 Cookie 包含隱私(好比存款總額),這些信息就會泄漏。更可怕的是,Cookie 每每用來保存用戶的登陸狀態,若是用戶沒有退出登陸,其餘網站就能夠冒充用戶,隨心所欲。由於瀏覽器同時還規定,提交表單不受同源政策的限制。java
因而可知,"同源政策"是必需的,不然 Cookie 能夠共享,互聯網就毫無安全可言了。node
同源策略限制內容有:python
下面爲容許跨域資源嵌入的示例,即一些不受同源策略影響的標籤示例:jquery
<script src="..."></script>
標籤嵌入跨域腳本。語法錯誤信息只能在同源腳本中捕捉到。<link rel="stylesheet" href="...">
標籤嵌入CSS。因爲CSS的鬆散的語法規則,CSS的跨域須要一個設置正確的Content-Type
消息頭。不一樣瀏覽器有不一樣的限制: IE, Firefox, Chrome, Safari
和 Opera
。<img>
嵌入圖片。支持的圖片格式包括PNG,JPEG,GIF,BMP,SVG
<video>
和 <audio>
嵌入多媒體資源。<object>
, <embed>
和 <applet>
的插件。@font-face
引入的字體。一些瀏覽器容許跨域字體( cross-origin fonts)
,一些須要同源字體(same-origin fonts)
。<frame>
和<iframe>
載入的任何資源。站點可使用X-Frame-Options
消息頭來阻止這種形式的跨域交互。常見的跨域場景webpack
URL 說明 是否容許通訊 http://www.domain.com/a.js http://www.domain.com/b.js 同一域名,不一樣文件或路徑 容許 http://www.domain.com/lab/c.js http://www.domain.com:8000/a.js http://www.domain.com/b.js 同一域名,不一樣端口 不容許 http://www.domain.com/a.js https://www.domain.com/b.js 同一域名,不一樣協議 不容許 http://www.domain.com/a.js http://192.168.4.12/b.js 域名和域名對應相同ip 不容許 http://www.domain.com/a.js http://x.domain.com/b.js 主域相同,子域不一樣 不容許 http://domain.com/c.js http://www.domain1.com/a.js http://www.domain2.com/b.js 不一樣域名 不容許
注意:關於跨域,有兩個誤區:
一、動態請求就會有跨域的問題(錯)。跨域只存在於瀏覽器端,不存在於安卓/ios/Node.js/python/ java等其它環境
二、跨域就是請求發不出去了(錯)。跨域請求能發出去,服務端能收到請求並正常返回結果,只是結果被瀏覽器攔截了
jsonp
的跨域原理是利用script
標籤不受跨域限制而造成的一種方案。
下面咱們來簡單看一下代碼實現ios
<!-- index.html 文件 --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script> var script = document.createElement('script'); script.type = 'text/javascript'; // 傳參並指定回調執行函數爲onBack script.src = 'http://127.0.0.1:3000/login?user=admin&callback=onBack'; document.head.appendChild(script); // 回調執行函數 function onBack(res) { alert(JSON.stringify(res)); } </script> </body> </html>
node
var qs = require('querystring'); var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { console.log(req); var params = qs.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('3000'); console.log('Server is running at port 3000...');
咱們能夠看到返回的結果:
postMessage是HTML5 XMLHttpRequest Level 2中的API,且是爲數很少能夠跨域操做的window屬性之一。
語法:otherWindow.postMessage(message, targetOrigin, [transfer])
;
otherWindow
:指目標窗口,也就是給哪一個window發消息,是 window.frames 屬性的成員或者由 window.open 方法建立的窗口;message
屬性是要發送的消息,類型爲 String、Object (IE八、9 不支持);
data
屬性爲 window.postMessage 的第一個參數;origin
屬性表示調用window.postMessage() 方法時調用頁面的當前狀態;source
屬性記錄調用 window.postMessage() 方法的窗口信息;targetOrigin
:屬性來指定哪些窗口能接收到消息事件,其值能夠是字符串"*"(表示無限制)或者一個URI。transfer
:是一串和message 同時傳遞的 Transferable 對象. 這些對象的全部權將被轉移給消息的接收方,而發送一方將再也不保有全部權。看一下簡單的demo
<!-- index.html 文件 --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>AAAAAAAAAAAA</h1> <iframe src="http://localhost:4000/b.html" id="frame" onload="load()"></iframe> <script> function load(params){ let iframe = document.getElementById('frame'); iframe.onload = function() { const data = { name: 'aym' }; //獲取iframe中的窗口,給iframe裏嵌入的window發消息 iframe.contentWindow.postMessage(JSON.stringify(data), 'http://localhost:4000'); }; // 接收b.html回過來的消息 window.onmessage = function(e){ console.log(e.data) } } </script> </body> </html>
<!-- b.html 文件 --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>BBBBBBBBB</h1> <script> window.addEventListener('message', function(e) { console.log('data from domain1 ---> ' + e.data); let data = JSON.parse(e.data); if (data) { data.number = 16; // 處理後再發回domain1 window.parent.postMessage(JSON.stringify(data), 'http://127.0.0.1:8080'); } }, false); </script> </body> </html>
WebSocket protocol是HTML5一種新的協議。它實現了瀏覽器與服務器全雙工通訊,同時容許跨域通信,是server push技術的一種很好的實現。
原生WebSocket API使用起來不太方便,咱們使用Socket.io,它很好地封裝了webSocket接口,提供了更簡單、靈活的接口,也對不支持webSocket的瀏覽器提供了向下兼容。
<!-- index.html 文件 --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div>user input:<input type="text"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.dev.js"></script> <script> var socket = io('http://127.0.0.1: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> </body> </html>
node服務端文件
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.'); }); });
實現原理:同源策略是瀏覽器須要遵循的標準,而若是是服務器向服務器請求就無需遵循同源策略。
主要訪問路徑
實現代碼:
前端代碼示例:
<!-- index.html 文件 --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>1111</h1> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script> $.ajax({ url: 'http://127.0.0.1:3000/login?user=admin&password=123', success: function(result) { console.log(result) }, error: function(msg) { console.log(msg) } }) </script> </body> </html>
代理服務器
var express = require('express'); var proxy = require('http-proxy-middleware'); var app = express(); var options = { dotfiles: 'ignore', etag: false, extensions: ['htm', 'html'], index: false, maxAge: '1d', redirect: false, setHeaders: function (res, path, stat) { res.set('x-timestamp', Date.now()) } } app.use(express.static('public', options)) app.use('/', proxy({ // 代理跨域目標接口 target: 'http://127.0.0.1:4000', changeOrigin: true, // 修改響應頭信息,實現跨域並容許帶cookie onProxyRes: function(proxyRes, req, res) { res.header('Access-Control-Allow-Origin', 'http://127.0.0.1'); res.header('Access-Control-Allow-Credentials', 'true'); }, // 修改響應信息中的cookie域名 cookieDomainRewrite: '127.0.0.1' // 能夠爲false,表示不修改 })); app.listen(3000); console.log('Proxy server is listen at port 3000...');
應用服務器
// 服務器 const http = require("http"); const server = http.createServer(); const qs = require("querystring"); server.on("request", function(req, res) { var params = qs.parse(req.url.split('?')[1]); console.log(req.url, params); // 向前臺寫 cookie res.writeHead(200, { "Set-Cookie": "l=a123456;Path=/;Domain=127.0.0.1;HttpOnly" // HttpOnly:腳本沒法讀取 }); res.write(JSON.stringify({ data: 'I LOVE YOU', ...params })); res.end(); }); server.listen("4000"); console.log('listen 4000...')
最終效果
跨域原理: 同源策略是瀏覽器的安全策略,不是HTTP協議的一部分。服務器端調用HTTP接口只是使用HTTP協議,不會執行JS腳本,不須要同源策略,也就不存在跨越問題。
實現思路:經過nginx配置一個代理服務器(域名與domain1相同,端口不一樣)作跳板機,反向代理訪問domain2接口,而且能夠順便修改cookie中domain信息,方便當前域cookie寫入,實現跨域登陸。:經過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; } }
Nodejs後臺示例:
var http = require('http'); var server = http.createServer(); var qs = require('querystring'); server.on('request', function(req, res) { var params = qs.parse(req.url.split('?')[1]); // 向前臺寫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...');
前端代碼示例:
var xhr = new XMLHttpRequest(); // 前端開關:瀏覽器是否讀寫cookie xhr.withCredentials = true; // 訪問nginx中的代理服務器 xhr.open('get', 'http://www.domain1.com:81/?user=admin', true); xhr.send();
普通跨域請求:只服務端設置Access-Control-Allow-Origin便可,前端無須設置,若要帶cookie請求:先後端都須要設置。
雖然設置 CORS 和前端沒什麼關係,可是經過這種方式解決跨域問題的話,會在發送請求時出現兩種狀況,分別爲簡單請求和複雜請求。
簡單請求
只要同時知足如下兩大條件,就屬於簡單請求
GET、HEAD、POST
text/plain
、multipart/form-data
、application/x-www-form-urlencoded
複雜請求
凡是不一樣時知足上面兩個條件,就屬於複雜請求。
複雜請求的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)
原理:window.name屬性的獨特之處:name值在不一樣的頁面(甚至不一樣域名)加載後依舊存在。
下面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頁面
// 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);
實現原理:兩個頁面都經過js強制設置document.domain
爲基礎主域,就實現了同域。
該方式只能用於二級域名相同的狀況下,好比 a.test.com
和 b.test.com
適用於該方式。 只須要給頁面添加 document.domain ='test.com'
表示二級域名都相同就能夠實現跨域。
咱們看個例子:頁面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>
後續更多文章將在個人 github第一時間發佈,歡迎關注。