<article class="article fmt article-content " style="box-sizing: border-box; display: block; line-height: 1.6; margin-bottom: 1.5rem; color: rgb(33, 37, 41); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", "Liberation Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">
什么是跨域懂算?
跨域是指一個域下的文檔或腳本試圖去請求另一個域下的資源只冻,這里跨域是廣義的庇麦。
廣義的跨域:
<pre class="hljs language-xml" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">1.) 資源跳轉(zhuǎn): A鏈接计技、重定向、表單提交
2.) 資源嵌入: <link>山橄、<script>垮媒、<img>、<frame>等dom標簽航棱,還有樣式中background:url()睡雇、@font-face()等文件外鏈
3.) 腳本請求: js發(fā)起的ajax請求、dom和js對象的跨域操作等</pre>
其實我們通常所說的跨域是狹義的饮醇,是由瀏覽器同源策略限制的一類請求場景它抱。
什么是同源策略?
同源策略/SOP(Same origin policy)是一種約定朴艰,由Netscape公司1995年引入瀏覽器观蓄,它是瀏覽器最核心也最基本的安全功能混移,如果缺少了同源策略,瀏覽器很容易受到XSS侮穿、CSFR等攻擊歌径。所謂同源是指"協(xié)議+域名+端口"三者相同,即便兩個不同的域名指向同一個ip地址亲茅,也非同源回铛。
同源策略限制以下幾種行為:
<pre class="hljs language-mipsasm" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">1.) Cookie、LocalStorage 和 IndexDB 無法讀取
2.) DOM 和 Js對象無法獲得 3.) AJAX 請求不能發(fā)送</pre>
常見跨域場景
<pre class="hljs language-awk" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">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 同一域名,不同協(xié)議 不允許
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 不同域名 不允許</pre>
跨域解決方案
1、 通過jsonp跨域
2榕酒、 document.domain + iframe跨域
3胚膊、 location.hash + iframe
4、 window.name + iframe跨域
5想鹰、 postMessage跨域
6紊婉、 跨域資源共享(CORS)
7、 nginx代理跨域
8辑舷、 nodejs中間件代理跨域
9喻犁、 WebSocket協(xié)議跨域
一、 通過jsonp跨域
通常為了減輕web服務(wù)器的負載何缓,我們把js肢础、css,img等靜態(tài)資源分離到另一臺獨立域名的服務(wù)器上碌廓,在html頁面中再通過相應的標簽從不同域名下加載靜態(tài)資源传轰,而被瀏覽器允許,基于此原理谷婆,我們可以通過動態(tài)創(chuàng)建script慨蛙,再請求一個帶參網(wǎng)址實現(xiàn)跨域通信。
1.)原生實現(xiàn):
<pre class="html hljs language-xml" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;"> <script> var script = document.createElement('script');
script.type = 'text/javascript';
// 傳參一個回調(diào)函數(shù)名給后端纪挎,方便后端返回時執(zhí)行這個在前端定義的回調(diào)函數(shù)
script.src = 'http://www.domain2.com:8080/login?user=admin&callback=handleCallback';
document.head.appendChild(script);
// 回調(diào)執(zhí)行函數(shù)
function handleCallback(res) {
alert(JSON.stringify(res));
} </script></pre>
服務(wù)端返回如下(返回時即執(zhí)行全局函數(shù)):
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">handleCallback({"status": true, "user": "admin"})</pre>
2.)jquery ajax:
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">$.ajax({
url: 'http://www.domain2.com:8080/login',
type: 'get',
dataType: 'jsonp', // 請求方式為jsonp
jsonpCallback: "handleCallback", // 自定義回調(diào)函數(shù)名
data: {}
});</pre>
3.)vue.js:
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">this.$http.jsonp('http://www.domain2.com:8080/login', {
params: {},
jsonp: 'handleCallback'
}).then((res) => {
console.log(res);
})</pre>
后端node.js代碼示例:
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">var querystring = require('querystring');
var http = require('http');
var server = http.createServer();
server.on('request', function(req, res) {
var params = qs.parse(req.url.split('?')[1]);
var fn = params.callback;
// jsonp返回設(shè)置
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...');</pre>
jsonp缺點:只能實現(xiàn)get一種請求期贫。
二、 document.domain + iframe跨域
此方案僅限主域相同异袄,子域不同的跨域應用場景通砍。
實現(xiàn)原理:兩個頁面都通過js強制設(shè)置document.domain為基礎(chǔ)主域,就實現(xiàn)了同域烤蜕。
1.)父窗口:(http://www.domain.com/a.html)
<pre class="html hljs language-xml" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;"><iframe id="iframe" src="http://child.domain.com/b.html"></iframe>
<script> document.domain = 'domain.com';
var user = 'admin'; </script></pre>
2.)子窗口:(http://child.domain.com/b.html)
<pre class="html hljs language-xml" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;"><script> document.domain = 'domain.com';
// 獲取父窗口中變量
alert('get js data from parent ---> ' + window.parent.user); </script></pre>
三封孙、 location.hash + iframe跨域
實現(xiàn)原理: a欲與b跨域相互通信垢揩,通過中間頁c來實現(xiàn)。 三個頁面敛瓷,不同域之間利用iframe的location.hash傳值叁巨,相同域之間直接js訪問來通信呐籽。
具體實現(xiàn):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)
<pre class="html hljs language-xml" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;"><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的回調(diào)方法
function onCallback(res) {
alert('data from c.html ---> ' + res);
} </script></pre>
2.)b.html:(http://www.domain2.com/b.html)
<pre class="html hljs language-xml" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;"><iframe id="iframe" src="http://www.domain1.com/c.html" style="display:none;"></iframe>
<script> var iframe = document.getElementById('iframe');
// 監(jiān)聽a.html傳來的hash值,再傳給c.html
window.onhashchange = function () {
iframe.src = iframe.src + location.hash;
}; </script></pre>
3.)c.html:(http://www.domain1.com/c.html)
<pre class="html hljs language-xml" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;"><script> // 監(jiān)聽b.html傳來的hash值
window.onhashchange = function () {
// 再通過操作同域a.html的js回調(diào)硼端,將結(jié)果傳回
window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', ''));
}; </script></pre>
四并淋、 window.name + iframe跨域
window.name屬性的獨特之處:name值在不同的頁面(甚至不同域名)加載后依舊存在,并且可以支持非常長的 name 值(2MB)珍昨。
1.)a.html:(http://www.domain1.com/a.html)
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">var proxy = function(url, callback) {
var state = 0;
var iframe = document.createElement('iframe');
// 加載跨域頁面
iframe.src = url;
// onload事件會觸發(fā)2次县耽,第1次加載跨域頁,并留存數(shù)據(jù)于window.name
iframe.onload = function() {
if (state === 1) {
// 第2次onload(同域proxy頁)成功后镣典,讀取同域window.name中數(shù)據(jù)
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);
// 獲取數(shù)據(jù)以后銷毀這個iframe,釋放內(nèi)存兄春;這也保證了安全(不被其他域frame js訪問)
function destoryFrame() {
iframe.contentWindow.document.write('');
iframe.contentWindow.close();
document.body.removeChild(iframe);
}
};
// 請求跨域b頁面數(shù)據(jù)
proxy('http://www.domain2.com/b.html', function(data){
alert(data);
});</pre>
2.)proxy.html:(http://www.domain1.com/proxy....
中間代理頁澎剥,與a.html同域,內(nèi)容為空即可神郊。
3.)b.html:(http://www.domain2.com/b.html)
<pre class="html hljs language-xml" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;"><script> window.name = 'This is domain2 data!'; </script></pre>
總結(jié):通過iframe的src屬性由外域轉(zhuǎn)向本地域肴裙,跨域數(shù)據(jù)即由iframe的window.name從外域傳遞到本地域。這個就巧妙地繞過了瀏覽器的跨域訪問限制涌乳,但同時它又是安全操作。
五甜癞、 postMessage跨域
postMessage是HTML5 XMLHttpRequest Level 2中的API夕晓,且是為數(shù)不多可以跨域操作的window屬性之一,它可用于解決以下方面的問題:
a.) 頁面和其打開的新窗口的數(shù)據(jù)傳遞
b.) 多窗口之間消息傳遞
c.) 頁面與嵌套的iframe消息傳遞
d.) 上面三個場景的跨域數(shù)據(jù)傳遞
用法:postMessage(data,origin)方法接受兩個參數(shù)
data: html5規(guī)范支持任意基本類型或可復制的對象悠咱,但部分瀏覽器只支持字符串蒸辆,所以傳參時最好用JSON.stringify()序列化征炼。
origin: 協(xié)議+主機+端口號,也可以設(shè)置為"*"躬贡,表示可以傳遞給任意窗口谆奥,如果要指定和當前窗口同源的話設(shè)置為"/"。
1.)a.html:(http://www.domain1.com/a.html)
<pre class="html hljs language-xml" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;"><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傳送跨域數(shù)據(jù)
iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.domain2.com');
};
// 接受domain2返回數(shù)據(jù)
window.addEventListener('message', function(e) {
alert('data from domain2 ---> ' + e.data);
}, false); </script></pre>
2.)b.html:(http://www.domain2.com/b.html)
<pre class="html hljs language-xml" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;"><script> // 接收domain1的數(shù)據(jù)
window.addEventListener('message', function(e) {
alert('data from domain1 ---> ' + e.data);
var data = JSON.parse(e.data);
if (data) {
data.number = 16;
// 處理后再發(fā)回domain1
window.parent.postMessage(JSON.stringify(data), 'http://www.domain1.com');
}
}, false); </script></pre>
六拂玻、 跨域資源共享(CORS)
普通跨域請求:只服務(wù)端設(shè)置Access-Control-Allow-Origin即可酸些,前端無須設(shè)置,若要帶cookie請求:前后端都需要設(shè)置檐蚜。
需注意的是:由于同源策略的限制魄懂,所讀取的cookie為跨域請求接口所在域的cookie,而非當前頁闯第。如果想實現(xiàn)當前頁cookie的寫入市栗,可參考下文:七、nginx反向代理中設(shè)置proxy_cookie_domain 和 八咳短、NodeJs中間件代理中cookieDomainRewrite參數(shù)的設(shè)置填帽。
目前,所有瀏覽器都支持該功能(IE8+:IE8/9需要使用XDomainRequest對象來支持CORS))咙好,CORS也已經(jīng)成為主流的跨域解決方案盲赊。
1、 前端設(shè)置:
1.)原生ajax
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">// 前端設(shè)置是否帶cookie
xhr.withCredentials = true;</pre>
示例代碼:
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">var xhr = new XMLHttpRequest(); // IE8/9需用window.XDomainRequest兼容
// 前端設(shè)置是否帶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);
}
};</pre>
2.)jQuery ajax
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">$.ajax({
...
xhrFields: {
withCredentials: true // 前端設(shè)置是否帶cookie
},
crossDomain: true, // 會讓請求頭中包含跨域的額外信息敷扫,但不會含cookie
...
});</pre>
3.)vue框架
a.) axios設(shè)置:
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">axios.defaults.withCredentials = true</pre>
b.) vue-resource設(shè)置:
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">Vue.http.options.credentials = true</pre>
2哀蘑、 服務(wù)端設(shè)置:
若后端設(shè)置成功,前端瀏覽器控制臺則不會出現(xiàn)跨域報錯信息葵第,反之绘迁,說明沒設(shè)成功。
1.)Java后臺:
<pre class="java hljs language-java" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">/*
- 導入包:import javax.servlet.http.HttpServletResponse;
- 接口參數(shù)中定義:HttpServletResponse response
*/
// 允許跨域訪問的域名:若有端口需寫全(協(xié)議+域名+端口)卒密,若沒有端口末尾不用加'/'
response.setHeader("Access-Control-Allow-Origin", "http://www.domain1.com");
// 允許前端帶認證cookie:啟用此項后缀台,上面的域名不能為'*',必須指定具體的域名哮奇,否則瀏覽器會提示
response.setHeader("Access-Control-Allow-Credentials", "true");
// 提示OPTIONS預檢時膛腐,后端需要設(shè)置的兩個常用自定義頭
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");</pre>
2.)Nodejs后臺示例:
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">var http = require('http');
var server = http.createServer();
var qs = require('querystring');
server.on('request', function(req, res) {
var postData = '';
// 數(shù)據(jù)塊接收中
req.addListener('data', function(chunk) {
postData += chunk;
});
// 數(shù)據(jù)接收完畢
req.addListener('end', function() {
postData = qs.parse(postData);
// 跨域后臺設(shè)置
res.writeHead(200, {
'Access-Control-Allow-Credentials': 'true', // 后端允許發(fā)送Cookie
'Access-Control-Allow-Origin': 'http://www.domain1.com', // 允許訪問的域(協(xié)議+域名+端口)
/*
* 此處設(shè)置的cookie還是domain2的而非domain1,因為后端也不能跨域?qū)慶ookie(nginx反向代理可以實現(xiàn))鼎俘,
* 但只要domain2中寫入一次cookie認證哲身,后面的跨域接口都能從domain2中獲取cookie,從而實現(xiàn)所有的接口都能跨域訪問
*/
'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...');</pre>
七贸伐、 nginx代理跨域
1勘天、 nginx配置解決iconfont跨域
瀏覽器跨域訪問js、css、img等常規(guī)靜態(tài)資源被同源策略許可脯丝,但iconfont字體文件(eot|otf|ttf|woff|svg)例外商膊,此時可在nginx的靜態(tài)資源服務(wù)器中加入以下配置。
<pre class="hljs language-crmsh" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">location / {
add_header Access-Control-Allow-Origin *;
}</pre>
2宠进、 nginx反向代理接口跨域
跨域原理: 同源策略是瀏覽器的安全策略晕拆,不是HTTP協(xié)議的一部分。服務(wù)器端調(diào)用HTTP接口只是使用HTTP協(xié)議材蹬,不會執(zhí)行JS腳本实幕,不需要同源策略,也就不存在跨越問題赚导。
實現(xiàn)思路:通過nginx配置一個代理服務(wù)器(域名與domain1相同茬缩,端口不同)做跳板機,反向代理訪問domain2接口吼旧,并且可以順便修改cookie中domain信息凰锡,方便當前域cookie寫入,實現(xiàn)跨域登錄圈暗。
nginx具體配置:
<pre class="hljs language-nginx" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">#proxy服務(wù)器
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;
}
}</pre>
1.) 前端代碼示例:
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">var xhr = new XMLHttpRequest();
// 前端開關(guān):瀏覽器是否讀寫cookie
xhr.withCredentials = true;
// 訪問nginx中的代理服務(wù)器
xhr.open('get', 'http://www.domain1.com:81/?user=admin', true);
xhr.send();</pre>
2.) Nodejs后臺示例:
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">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...');</pre>
八、 Nodejs中間件代理跨域
node中間件實現(xiàn)跨域代理寸齐,原理大致與nginx相同欲诺,都是通過啟一個代理服務(wù)器,實現(xiàn)數(shù)據(jù)的轉(zhuǎn)發(fā)渺鹦,也可以通過設(shè)置cookieDomainRewrite參數(shù)修改響應頭中cookie中域名扰法,實現(xiàn)當前域的cookie寫入,方便接口登錄認證毅厚。
1塞颁、 非vue框架的跨域(2次跨域)
利用node + express + http-proxy-middleware搭建一個proxy服務(wù)器。
1.)前端代碼示例:
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">var xhr = new XMLHttpRequest();
// 前端開關(guān):瀏覽器是否讀寫cookie
xhr.withCredentials = true;
// 訪問http-proxy-middleware代理服務(wù)器
xhr.open('get', 'http://www.domain1.com:3000/login?user=admin', true);
xhr.send();</pre>
2.)中間件服務(wù)器:
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">var express = require('express');
var proxy = require('http-proxy-middleware');
var app = express();
app.use('/', proxy({
// 代理跨域目標接口
target: 'http://www.domain2.com:8080',
changeOrigin: true,
// 修改響應頭信息吸耿,實現(xiàn)跨域并允許帶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...');</pre>
3.)Nodejs后臺同(六:nginx)
2、 vue框架的跨域(1次跨域)
利用node + webpack + webpack-dev-server代理接口跨域咽安。在開發(fā)環(huán)境下伴网,由于vue渲染服務(wù)和接口代理服務(wù)都是webpack-dev-server同一個,所以頁面與代理接口之間不再跨域板乙,無須設(shè)置headers跨域信息了是偷。
webpack.config.js部分配置:
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">module.exports = {
entry: {},
module: {},
...
devServer: {
historyApiFallback: true,
proxy: [{
context: '/login',
target: 'http://www.domain2.com:8080', // 代理跨域目標接口
changeOrigin: true,
secure: false, // 當代理某些https服務(wù)報錯時用
cookieDomainRewrite: 'www.domain1.com' // 可以為false拳氢,表示不修改
}],
noInfo: true
}
}</pre>
九募逞、 WebSocket協(xié)議跨域
WebSocket protocol是HTML5一種新的協(xié)議蛋铆。它實現(xiàn)了瀏覽器與服務(wù)器全雙工通信,同時允許跨域通訊放接,是server push技術(shù)的一種很好的實現(xiàn)刺啦。
原生WebSocket API使用起來不太方便,我們使用Socket.io纠脾,它很好地封裝了webSocket接口玛瘸,提供了更簡單、靈活的接口苟蹈,也對不支持webSocket的瀏覽器提供了向下兼容糊渊。
1.)前端代碼:
<pre class="html hljs language-xml" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;"><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() {
// 監(jiān)聽服務(wù)端消息
socket.on('message', function(msg) {
console.log('data from server: ---> ' + msg);
});
// 監(jiān)聽服務(wù)端關(guān)閉
socket.on('disconnect', function() {
console.log('Server socket has closed.');
});
});
document.getElementsByTagName('input')[0].onblur = function() {
socket.send(this.value);
}; </script></pre>
2.)Nodejs socket后臺:
<pre class="js hljs language-javascript" style="box-sizing: border-box; font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; font-size: 14px; margin-top: 0px !important; margin-bottom: 1.25rem; overflow: auto; display: block; color: rgb(36, 41, 46); background: rgb(233, 236, 239); padding: 1rem; max-height: 35rem; line-height: 1.5;">var http = require('http');
var socket = require('socket.io');
// 啟http服務(wù)
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...');
// 監(jiān)聽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.');
});
});</pre>
</article>