接着上文
三、 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訪問1頁面所有對象。
1.a.html:(http://www.baidu1.com/a.html)
<iframe id="iframe" src="http://www.baidu2.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>
2.b.html:(http://www.baidu2.com/b.html)
<iframe id="iframe" src="http://www.baidu1.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>
3.c.html:(http://www.baidu1.com/c.html)
<script>
// 監聽b.html傳來的hash值
window.onhashchange = function () {
// 再通過操作同域a.html的js回調,將結果傳回
window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', ''));
};
</script>
四、 window.name + iframe跨域
window.name屬性的獨特之處:name值在不同的頁面(甚至不同域名)加載後依舊存在,並且可以支持非常長的 name 值。
1.a.html:(http://www.baidu1.com/a.html)
var proxy = function(url, callback) {
var state = 0;
var iframe = document.createElement('iframe');
// 加載跨域頁面
iframe.src = url;
// onload事件會觸發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.baidu2.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.baidu2.com/b.html', function(data){
alert(data);
});
2.proxy.html:(http://www.baidu1.com/proxy…
中間代理頁,與a.html同域,內容爲空。
3.b.html:(http://www.baidu2.com/b.html)
<script>
window.name = 'This is baidu2 data!';
</script>
通過iframe的src屬性由外域轉向本地域,跨域數據即由iframe的window.name從外域傳遞到本地域。這個就巧妙地繞過了瀏覽器的跨域訪問限制,但同時它又是安全操作。
五、 跨域資源共享(CORS)
普通跨域請求:只服務端設置Access-Control-Allow-Origin即可,前端無須設置,若要帶cookie請求:前後端都需要設置。
瀏覽器將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字段。
Origin字段用來說明,本次請求來自哪個源(協議 + 域名 + 端口)。服務器根據這個值,決定是否同意這次請求。
CORS請求設置的響應頭字段,都以 Access-Control-開頭:
1)Access-Control-Allow-Origin:必選
它的值要麼是請求時Origin字段的值,要麼是一個*,表示接受任意域名的請求。
2)Access-Control-Allow-Credentials:可選
它的值是一個布爾值,表示是否允許發送Cookie。默認情況下,Cookie不包括在CORS請求之中。設爲true,即表示服務器明確許可,Cookie可以包含在請求中,一起發給服務器。這個值也只能設爲true,如果服務器不要瀏覽器發送Cookie,刪除該字段即可。
3)Access-Control-Expose-Headers:可選
CORS請求時,XMLHttpRequest對象的getResponseHeader()方法只能拿到6個基本字段:Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma。如果想拿到其他字段,就必須在Access-Control-Expose-Headers裏面指定。
非簡單請求
非簡單請求是那種對服務器有特殊要求的請求,比如請求方法是PUT或DELETE,或者Content-Type字段的類型是application/json。
非簡單請求的CORS請求,會在正式通信之前,增加一次HTTP查詢請求,稱爲"預檢"請求(preflight)。
預檢請求
預檢"請求用的請求方法是OPTIONS,表示這個請求是用來詢問的。請求頭信息裏面,關鍵字段是Origin,表示請求來自哪個源。除了Origin字段,"預檢"請求的頭信息包括兩個特殊字段。
1)Access-Control-Request-Method:必選
用來列出瀏覽器的CORS請求會用到哪些HTTP方法
2)Access-Control-Request-Headers:可選
該字段是一個逗號分隔的字符串,指定瀏覽器CORS請求會額外發送的頭信息字段
前端設置
原生
var xhr = new XMLHttpRequest();
// 前端設置是否帶cookie
xhr.withCredentials = true;
xhr.open('post', 'http://www.baidu2.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
...
});
vue框架
axios設置:
axios.defaults.withCredentials = true
vue-resource設置:
Vue.http.options.credentials = true
後端設置
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.baidu1.com', // 允許訪問的域(協議+域名+端口)
/*
* 此處設置的cookie還是baidu2的而非baidu1,因爲後端也不能跨域寫cookie(nginx反向代理可以實現),
* 但只要baidu2中寫入一次cookie認證,後面的跨域接口都能從baidu2中獲取cookie,從而實現所有的接口都能跨域訪問
*/
'Set-Cookie': 'l=a123456;Path=/;Domain=www.baidu2.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的靜態資源服務器中加入以下配置。
location / {
add_header Access-Control-Allow-Origin *;
}
2、 nginx反向代理接口跨域
跨域原理: 同源策略是瀏覽器的安全策略,不是HTTP協議的一部分。服務器端調用HTTP接口只是使用HTTP協議,不會執行JS腳本,不需要同源策略,也就不存在跨越問題。
實現思路:通過nginx配置一個代理服務器(域名與baidu1相同,端口不同)做跳板機,反向代理訪問baidu2接口,並且可以順便修改cookie中baidu信息,方便當前域cookie寫入,實現跨域登錄。
nginx具體配置:
#proxy服務器
server {
listen 81;
server_name www.domain1.com;
location / {
proxy_pass http://www.baidu2.com:8081; #反向代理
proxy_cookie_domain www.baidu2.com www.baidu1.com; #修改cookie裏域名
index index.html index.htm;
# 當用webpack-dev-server等中間件代理接口訪問nignx時,此時無瀏覽器參與,故沒有同源限制,下面的跨域配置可不啓用
add_header Access-Control-Allow-Origin http://www.baidu1.com; #當前端只跨域不帶cookie時,可爲*
add_header Access-Control-Allow-Credentials true;
}
}
前端代碼:
var xhr = new XMLHttpRequest();
// 前端開關:瀏覽器是否讀寫cookie
xhr.withCredentials = true;
// 訪問nginx中的代理服務器
xhr.open('get', 'http://www.baidu1.com:81/?user=admin', true);
xhr.send();
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.substring(2));
// 向前臺寫cookie
res.writeHead(200, {
'Set-Cookie': 'l=a123456;Path=/;Domain=www.baidu2.com;HttpOnly' // HttpOnly:腳本無法讀取
});
res.write(JSON.stringify(params));
res.end();
});
server.listen('8081');
console.log('Server is running at port 8081...');
七、 Nodejs中間件代理跨域
node中間件實現跨域代理,原理大致與nginx相同,都是通過啓一個代理服務器,實現數據的轉發,
也可以通過設置cookieDomainRewrite參數修改響應頭中cookie中域名,實現當前域的cookie寫入,方便接口登錄認證。
1、 非vue框架的跨域(2次跨域)
利用node + express + http-proxy-middleware搭建一個proxy服務器。
前端代碼:
var xhr = new XMLHttpRequest();
// 前端開關:瀏覽器是否讀寫cookie
xhr.withCredentials = true;
// 訪問http-proxy-middleware代理服務器
xhr.open('get', 'http://www.baidu1.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.baidu2.com:8081',
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.baidu1.com' // 可以爲false,表示不修改
}));
app.listen(3000);
console.log('Proxy server is listen at port 3000...');
Nodejs後臺同(五:nginx)
2、 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.baidu.com:8081', // 代理跨域目標接口
changeOrigin: true,
secure: false, // 當代理某些https服務報錯時用
cookieDomainRewrite: 'www.baidu1.com' // 可以爲false,表示不修改
}],
noInfo: true
}
}
八、 WebSocket協議跨域
WebSocket protocol是HTML5一種新的協議。它實現了瀏覽器與服務器全雙工通信,同時允許跨域通訊,是server push技術的一種很好的實現。
原生WebSocket API使用起來不太方便,我們使用Socket.io,它很好地封裝了webSocket接口,提供了更簡單、靈活的接口,也對不支持webSocket的瀏覽器提供了向下兼容。
前端代碼:
<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.baidu2.com:8081');
// 連接成功處理
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>
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('8081');
console.log('Server is running at port 8081...');
// 監聽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.');
});
});