JavaScript 九種跨域方式實現原理

前言css

先後端數據交互常常會碰到請求跨域,什麼是跨域,以及有哪幾種跨域方式,這是本文要探討的內容。html

1、什麼是跨域?前端

1.什麼是同源策略及其限制內容?jquery

同源策略是一種約定,它是瀏覽器最核心也最基本的安全功能,若是缺乏了同源策略,瀏覽器很容易受到 XSS、CSFR 等攻擊。所謂同源是指"協議+域名+端口"三者相同,即使兩個不一樣的域名指向同一個 ip 地址,也非同源。

同源策略限制內容有:webpack

Cookie、LocalStorage、IndexedDB 等存儲性內容
DOM 節點
AJAX 請求發送後,結果被瀏覽器攔截了
可是有三個標籤是容許跨域加載資源:nginx

<img src=XXX>
<link href=XXX>
<script src=XXX>
2.常見跨域場景web

當協議、子域名、主域名、端口號中任意一個不相同時,都算做不一樣域。不一樣域之間相互請求資源,就算做「跨域」。常見跨域場景以下圖所示:

特別說明兩點:ajax

第一:若是是協議和端口形成的跨域問題「前臺」是無能爲力的。express

第二:在跨域問題上,僅僅是經過「URL 的首部」來識別而不會根據域名對應的 IP 地址是否相同來判斷。「URL 的首部」能夠理解爲「協議, 域名和端口必須匹配」。json

這裏你或許有個疑問:請求跨域了,那麼請求到底發出去沒有?

跨域並非請求發不出去,請求能發出去,服務端能收到請求並正常返回結果,只是結果被瀏覽器攔截了。你可能會疑問明明經過表單的方式能夠發起跨域請求,爲何 Ajax 就不會?由於歸根結底,跨域是爲了阻止用戶讀取到另外一個域名下的內容,Ajax 能夠獲取響應,瀏覽器認爲這不安全,因此攔截了響應。可是表單並不會獲取新的內容,因此能夠發起跨域請求。同時也說明了跨域並不能徹底阻止 CSRF,由於請求畢竟是發出去了。

2、跨域解決方案

1.jsonp

1)JSONP 原理

利用 script 標籤沒有跨域限制的漏洞,網頁能夠獲得從其餘來源動態產生的 JSON 數據。JSONP 請求必定須要對方的服務器作支持才能夠。

2)JSONP 和 AJAX 對比

JSONP 和 AJAX 相同,都是客戶端向服務器端發送請求,從服務器端獲取數據的方式。但 AJAX 屬於同源策略,JSONP 屬於非同源策略(跨域請求)

3)JSONP 優缺點

JSONP 優勢是簡單兼容性好,可用於解決主流瀏覽器的跨域數據訪問的問題。缺點是僅支持 get 方法具備侷限性,不安全可能會遭受 XSS 攻擊。

4)JSONP 的實現流程

聲明一個回調函數,其函數名(如 show)當作參數值,要傳遞給跨域請求數據的服務器,函數形參爲要獲取目標數據(服務器返回的 data)。
建立一個script標籤,把那個跨域的 API 數據接口地址,賦值給 script 的 src,還要在這個地址中向服務器傳遞該函數名(能夠經過問號傳參:?callback=show)。
服務器接收到請求後,須要進行特殊的處理:把傳遞進來的函數名和它須要給你的數據拼接成一個字符串,例如:傳遞進去的函數名是 show,它準備好的數據是show('我不愛你')。
最後服務器把準備的數據經過 HTTP 協議返回給客戶端,客戶端再調用執行以前聲明的回調函數(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](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](http://crossdomain.com/jsonServerResponse)"``,`
dataType:``"jsonp"``,`
type:``"get"``,``//能夠省略`
jsonpCallback:``"show"``,``//->自定義傳遞給服務器的函數名,而不是使用jQuery自動生成的,可省略`
jsonp:``"callback"``,``//->把傳遞函數名的那個形參callback,可省略`
success:``function` `(data){`
console.log(data);}`
});`

2.cors

CORS 須要瀏覽器和後端同時支持。IE 8 和 9 須要經過 XDomainRequest 來實現。

瀏覽器會自動進行 CORS 通訊,實現 CORS 通訊的關鍵是後端。只要後端實現了 CORS,就實現了跨域。

服務端設置 Access-Control-Allow-Origin 就能夠開啓 CORS。 該屬性表示哪些域名能夠訪問資源,若是設置通配符則表示全部網站均可以訪問資源。

雖然設置 CORS 和前端沒什麼關係,可是經過這種方式解決跨域問題的話,會在發送請求時出現兩種狀況,分別爲簡單請求和複雜請求。

1) 簡單請求

只要同時知足如下兩大條件,就屬於簡單請求

條件 1:使用下列方法之一:

GET
HEAD
POST
條件 2:Content-Type 的值僅限於下列三者之一:

text/plain
multipart/form-data
application/x-www-form-urlencoded
請求中的任意 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](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](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 通訊的關鍵。

3.postMessage

postMessage 是 HTML5 XMLHttpRequest Level 2 中的 API,且是爲數很少能夠跨域操做的 window 屬性之一,它可用於解決如下方面的問題:

頁面和其打開的新窗口的數據傳遞
多窗口之間消息傳遞
頁面與嵌套的 iframe 消息傳遞
上面三個場景的跨域數據傳遞
postMessage()方法容許來自不一樣源的腳本採用異步方式進行有限的通訊,能夠實現跨文本檔、多窗口、跨域消息傳遞。

otherWindow.postMessage(message, targetOrigin, [transfer]);

message: 將要發送到其餘 window 的數據。
targetOrigin:經過窗口的 origin 屬性來指定哪些窗口能接收到消息事件,其值能夠是字符串"*"(表示無限制)或者一個 URI。在發送消息的時候,若是目標窗口的協議、主機地址或端口這三者的任意一項不匹配 targetOrigin 提供的值,那麼消息就不會被髮送;只有三者徹底匹配,消息纔會被髮送。
transfer(可選):是一串和 message 同時傳遞的 Transferable 對象. 這些對象的全部權將被轉移給消息的接收方,而發送一方將再也不保有全部權。
接下來咱們看個例子: http://localhost:3000/a.html頁面向http://localhost:4000/b.html傳遞「我愛你」,而後後者傳回"我不愛你"。

// a.html`
<``iframe` `src``=``"[http://localhost:4000/b.html](http://localhost:4000/b.html)"` `frameborder``=``"0"`
id``=``"frame"` `onload``=``"load()"``></``iframe``//等它加載完觸發一個事件`
//內嵌在[http://localhost:3000/a.html](http://localhost:3000/a.html)`
<script>`
function load() {`
let frame = document.getElementById('frame')`
frame.contentWindow.postMessage('我愛你', '[http://localhost:4000](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)
 }

4.websocket

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](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();
歡迎加入全棧開發交流划水交流圈:582735936
面向划水1-3年前端人員
幫助突破划水瓶頸,提高思惟能力
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('我不愛你')
 });
})
  1. Node 中間件代理(兩次跨域)

實現原理:同源策略是瀏覽器須要遵循的標準,而若是是服務器向服務器請求就無需遵循同源策略。
代理服務器,須要作如下幾個步驟:

接受客戶端請求 。
將請求 轉發給服務器。
拿到服務器 響應 數據。
將 響應 轉發給客戶端。

咱們先來看個例子:本地文件 index.html 文件,經過代理服務器http://localhost:3000向目標服務器http://localhost:4000請求數據。

// index.html([http://127.0.0.1:5500](http://127.0.0.1:5500/))`
<``script` `src``=``"[https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js](https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js)"``></``script``>`
<``script``>`
$.ajax({`
url: '[http://localhost:3000](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](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](http://localhost:3000/)'``)`
})`
// server2.js([http://localhost:4000](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](http://localhost:4000/)'``)`
})`

6.nginx 反向代理

實現原理相似於 Node 中間件代理,須要你搭建一箇中轉 nginx 服務器,用於轉發請求。

使用 nginx 反向代理實現跨域,是最簡單的跨域方式。只須要修改 nginx 的配置便可解決跨域問題,支持全部瀏覽器,支持 session,不須要修改任何代碼,而且不會影響服務器性能。

實現思路:經過 nginx 配置一個代理服務器(域名與 domain1 相同,端口不一樣)作跳板機,反向代理訪問 domain2 接口,而且能夠順便修改 cookie 中 domain 信息,方便當前域 cookie 寫入,實現跨域登陸。

先下載nginx,而後將 nginx 目錄下的 nginx.conf 修改以下:

// proxy服務器
server {
 listen  80;
 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](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...');

7.window.name + iframe

window.name 屬性的獨特之處:name 值在不一樣的頁面(甚至不一樣域名)加載後依舊存在,而且能夠支持很是長的 name 值(2MB)。

其中 a.html 和 b.html 是同域的,都是http://localhost:3000;而 c.html 是http://localhost:4000

// a.html([http://localhost:3000/b.html](http://localhost:3000/b.html))`
<``iframe` `src``=``"[http://localhost:4000/c.html](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](http://localhost:3000/b.html)';`
first = false;`
}else{`
// 第2次onload(同域b.html頁)成功後,讀取同域window.name中數據`
console.log(iframe.contentWindow.name);`
}`
歡迎加入全棧開發交流划水交流圈:582735936
面向划水1-3年前端人員
幫助突破划水瓶頸,提高思惟能力
}`
</``script``>`

b.html 爲中間代理頁,與 a.html 同域,內容爲空。

// c.html([http://localhost:4000/c.html](http://localhost:4000/c.html))`
<``script``>`
window.name = '我不愛你'`
</``script``>`

總結:經過 iframe 的 src 屬性由外域轉向本地域,跨域數據即由 iframe 的 window.name 從外域傳遞到本地域。這個就巧妙地繞過了瀏覽器的跨域訪問限制,但同時它又是安全操做。

8.location.hash + iframe

實現原理: 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](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](http://localhost:3000/b.html)#idontloveyou';`
document.body.appendChild(iframe);`
9.document.domain + 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](http://b.zf1.cn:3000/b.html)"` frameborder``=``"0"`onload``=``"load()"` `id``=``"frame"``></``iframe``>`
<``script``>`
document.domain = 'zf1.cn'`
function load() {`
}`
歡迎加入全棧開發交流划水交流圈:582735936
面向划水1-3年前端人員
幫助突破划水瓶頸,提高思惟能力
</``script``>`
</``body``>`
// b.html
<body>
 hellob
 <script>
  document.domain = 'zf1.cn'
  var a = 100;
 </script>
</body>

3、總結

CORS 支持全部類型的 HTTP 請求,是跨域 HTTP 請求的根本解決方案JSONP 只支持 GET 請求,JSONP 的優點在於支持老式瀏覽器,以及能夠向不支持 CORS 的網站請求數據。不論是 Node 中間件代理仍是 nginx 反向代理,主要是經過同源策略對服務器不加限制。平常工做中,用得比較多的跨域方案是 cors 和 nginx 反向代理

相關文章
相關標籤/搜索