A
連接、重定向、表單提交<link>
、<script>
、<img>
、<frame>
等dom
標籤,還有樣式中background:url()
、@font-face()
等文件外鏈js
發起的ajax
請求、dom
和js
對象的跨域操做等其實咱們一般所說的跨域是狹義的,是由瀏覽器同源策略限制的一類請求場景。javascript
同源策略,SOP(Same origin policy)
是一種約定,由Netscape
公司1995年引入瀏覽器,它是瀏覽器最核心也最基本的安全功能,若是缺乏了同源策略,瀏覽器很容易受到XSS
、CSFR
等攻擊。所謂同源是指"協議+域名+端口"
三者相同,即使兩個不一樣的域名指向同一個ip地址,也非同源。 同源策略限制如下幾種行爲:css
Cookie
、LocalStorage
和 IndexDB
沒法讀取DOM
和 Js
對象沒法得到AJAX
請求不能發送http://www.domain.com/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
不一樣域名 不容許http://www.domain.com/lab/c.js
、http://www.domain.com:8000/a.js
、http://www.domain.com/b.js
同一域名,不一樣端口 不容許jsonp
跨域 +document.domain + iframe
跨域location.hash + iframe
window.name + iframe
跨域postMessage
跨域(CORS)
nginx
代理跨域nodejs
中間件代理跨域WebSocket
協議跨域一般爲了減輕web
服務器的負載,咱們把js
、css
,img
等靜態資源分離到另外一臺獨立域名的服務器上,在html
頁面中再經過相應的標籤從不一樣域名下加載靜態資源,而被瀏覽器容許,基於此原理,咱們能夠經過動態建立script
,再請求一個帶參網址實現跨域通訊。html
<script>
var script = document.createElement('script');
script.type = 'text/javascript';
// 傳參並指定回調執行函數爲onBack
script.src = 'http://www.domain2.com:8080/login?user=admin&callback=onBack';
document.head.appendChild(script);
// 回調執行函數
function onBack(res) {
alert(JSON.stringify(res));
}
</script>
複製代碼
服務端返回以下(返回時即執行全局函數): onBack({"status": true, "user": "admin"})
前端
jquery ajax
:$.ajax({
url: 'http://www.domain2.com:8080/login',
type: 'get',
dataType: 'jsonp', // 請求方式爲jsonp
jsonpCallback: "onBack", // 自定義回調函數名
data: {}
});
複製代碼
vue.js
:this.$http.jsonp('http://www.domain2.com:8080/login', {
params: {},
jsonp: 'onBack'
}).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 = 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('8080');
console.log('Server is running at port 8080...');
複製代碼
jsonp缺點:只能實現get一種請求vue
此方案僅限主域相同,子域不一樣的跨域應用場景。 實現原理:兩個頁面都經過js強制設置document.domain爲基礎主域,就實現了同域。html5
(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/b.html)
<script>
document.domain = 'domain.com';
// 獲取父窗口中變量
alert('get js data from parent ---> ' + window.parent.user);
</script>
複製代碼
實現原理: a
欲與b
跨域相互通訊,經過中間頁c
來實現。 三個頁面,不一樣域之間利用iframe
的location.hash
傳值,相同域之間直接js
訪問來通訊。java
具體實現:A域:a.html -> B域:b.html -> A域:c.html
,a
與b
不一樣域只能經過hash
值單向通訊,b
與c
也不一樣域也只能單向通訊,但c
與a
同域,因此c
可經過parent.parent
訪問a
頁面全部對象。node
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>
複製代碼
2.b.html:(www.domain2.com/b.html)
jquery
<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>
複製代碼
window.name
屬性的獨特之處:name
值在不一樣的頁面(甚至不一樣域名)加載後依舊存在,而且能夠支持很是長的 name
值(2MB)。webpack
a.html:(www.domain1.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.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);
});
複製代碼
2.proxy.html:(www.domain1.com/proxy....
中間代理頁,與··a.htm··l同域,內容爲空便可。
b.html:(www.domain2.com/b.html)
<script>
window.name = 'This is domain2 data!';
</script>
複製代碼
總結:經過 iframe
的 src
屬性由外域轉向本地域,跨域數據即由iframe
的window.name
從外域傳遞到本地域。這個就巧妙地繞過了瀏覽器的跨域訪問限制,但同時它又是安全操做。
postMessage
是HTML5 XMLHttpRequest Level 2
中的API
,且是爲數很少能夠跨域操做的 window
屬性之一,它可用於解決如下方面的問題:
iframe
消息傳遞用法:postMessage(data,origin)
方法接受兩個參數 data: html5
規範支持任意基本類型或可複製的對象,但部分瀏覽器只支持字符串,因此傳參時最好用JSON.stringify()
序列化。 origin: 協議+主機+端口號
,也能夠設置爲"*"
,表示能夠傳遞給任意窗口,若是要指定和當前窗口同源的話設置爲"/"
。
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>
複製代碼
普通跨域請求:只服務端設置Access-Control-Allow-Origin
便可,前端無須設置。 帶cookie請求:先後端都須要設置字段,所帶cookie
爲跨域請求接口所在域的cookie
,而非當前頁。 目前,全部瀏覽器都支持該功能(IE8+
:IE8/9
須要使用XDomainRequest
對象來支持CORS
)),CORS
也已經成爲主流的跨域解決方案。
ajax
// 前端設置是否帶cookie
xhr.withCredentials = true;
示例代碼:
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
...
});
複製代碼
vue
框架在vue-resource
封裝的ajax
組件中加入如下代碼:Vue.http.options.credentials = true
複製代碼
/* * 導入包:import javax.servlet.http.HttpServletResponse; * 接口參數中定義:HttpServletResponse response */
response.setHeader("Access-Control-Allow-Origin", "http://www.domain1.com"); // 如有端口需寫全(協議+域名+端口)
response.setHeader("Access-Control-Allow-Credentials", "true");
複製代碼
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.domain1.com', // 容許訪問的域(協議+域名+端口)
'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' // HttpOnly:腳本沒法讀取cookie
});
res.write(JSON.stringify(postData));
res.end();
});
});
server.listen('8080');
console.log('Server is running at port 8080...');
複製代碼
js、css、img
等常規靜態資源被同源策略許可,但 iconfont
字體文件(eot|otf|ttf|woff|svg)
例外,此時可在nginx
的靜態資源服務器中加入如下配置。location / {
add_header Access-Control-Allow-Origin *;
}
複製代碼
HTTP
協議的一部分。服務器端調用HTTP
接口只是使用HTTP
協議,不會執行JS
腳本,不須要同源策略,也就不存在跨越問題。實現思路:經過nginx
配置一個代理服務器(域名與domain1
相同,端口不一樣)作跳板機,反向代理訪問domain2
接口,而且能夠順便修改cookie
中domain
信息,方便當前域cookie
寫入,實現跨域登陸。
#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;
}
}
複製代碼
var xhr = new XMLHttpRequest();
// 前端開關:瀏覽器是否讀寫cookie
xhr.withCredentials = true;
// 訪問nginx中的代理服務器
xhr.open('get', 'http://www.domain1.com:81/?user=admin', true);
xhr.send();
複製代碼
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...');
複製代碼
node
中間件實現跨域代理,原理大體與nginx
相同,都是經過啓一個代理服務器,實現數據的轉發。
vue
框架的跨域(2次跨域) 利用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...');
複製代碼
Nodejs
後臺同上面的nginx
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.domain2.com:8080', // 代理跨域目標接口
changeOrigin: true,
cookieDomainRewrite: 'www.domain1.com' // 能夠爲false,表示不修改
}],
noInfo: true
}
}
複製代碼
WebSocket protocol
是HTML5
一種新的協議。它實現了瀏覽器與服務器全雙工通訊,同時容許跨域通信,是server push
技術的一種很好的實現。原生WebSocket API
使用起來不太方便,咱們使用Socket.io
,它很好地封裝了webSocket
接口,提供了更簡單、靈活的接口,也對不支持webSocket
的瀏覽器提供了向下兼容。
<div>user input:<input type="text"></div>
<script src="./socket.io.js"></script>
<script> var socket = io('http://www.domain2.com: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>
複製代碼
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.');
});
});
複製代碼