什么是跨域?
跨域是指一個域下的文檔或腳本試圖去請求另一個域下的資源,這里跨域是廣義的。愛掏網 - it200.com
廣義的跨域:
1.) 資源跳轉: A鏈接、重定向、表單提交
2.) 資源嵌入: 、
等dom標簽,
還有樣式中background:url()、
@font-face()等文件外鏈
3.) 腳本請求: js發起的ajax請求、dom和js對象的跨域操作等
其實我們通常所說的跨域是狹義的,是由瀏覽器同源策略限制的一類請求場景。愛掏網 - it200.com
什么是同源策略?
同源策略/SOP(Same origin policy)是一種約定,由Netscape公司1995年引入瀏覽器,它是瀏覽器最核心也最基本的安全功能,如果缺少了同源策略,瀏覽器很容易受到XSS、CSFR等攻擊。愛掏網 - it200.com所謂同源是指"協議+域名+端口"三者相同,即便兩個不同的域名指向同一個ip地址,也非同源。愛掏網 - it200.com
同源策略限制以下幾種行為:
1.) Cookie、LocalStorage 和 IndexDB 無法讀取
2.) DOM 和 Js對象無法獲得
3.) AJAX 請求不能發送
常見跨域場景
跨域解決方案
1、 通過jsonp跨域
2、 document.domain + iframe跨域
3、 location.hash + iframe
4、 window.name + iframe跨域
5、 postMessage跨域
6、 跨域資源共享(CORS)
7、 nginx代理跨域
8、 nodejs中間件代理跨域
9、 WebSocket協議跨域
一、 通過jsonp跨域
通常為了減輕web服務器的負載,我們把js、css,img等靜態資源分離到另一臺獨立域名的服務器上,在html頁面中再通過相應的標簽從不同域名下加載靜態資源,而被瀏覽器允許,基于此原理,我們可以通過動態創建script,再請求一個帶參網址實現跨域通信。愛掏網 - it200.com
1)原生實現:
login?user=admin&callback=onBack';
document.head.appendChild(script);
// 回調執行函數
function onBack(res) {
alert(JSON.stringify(res));
}
服務端返回如下(返回時即執行全局函數):
onBack({"status": true, "user": "admin"})
2)jquery ajax:
$.ajax({
url: 'http://www.domain2.com:8080/login',
type: 'get', dataType: 'jsonp',
// 請求方式為jsonp
jsonpCallback: "onBack",
// 自定義回調函數名
data: {}
});
3)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一種請求。愛掏網 - it200.com
二、 document.domain + iframe跨域
此方案僅限主域相同,子域不同的跨域應用場景。愛掏網 - it200.com
實現原理:兩個頁面都通過js強制設置document.domain為基礎主域,就實現了同域。愛掏網 - it200.com
1)父窗口(http://www.domain.com/a.html)
src="http://child.domain.com/b.html">
2)子窗口(http://child.domain.com/b.html)
- window.parent.user);
三、 location.hash + iframe跨域
實現原理: a欲與b跨域相互通信,通過中間頁c來實現。愛掏網 - it200.com 三個頁面,不同域之間利用iframe的location.hash傳值,相同域之間直接js訪問來通信。愛掏網 - it200.com
具體實現:A域:a.html -> B域:b.html -> A域:c.html,a與b不同域只能通過hash值單向通信,b與c也不同域也只能單向通信,但c與a同域,所以c可通過parent.parent訪問a頁面所有對象。愛掏網 - it200.com
1)a.html:(http://www.domain1.com/a.html)
src="http://www.domain2.com/b.html"
style="display:none;">
2)b.html:(http://www.domain2.com/b.html)
src="http://www.domain1.com/c.html"
style="display:none;">
3)c.html:(http://www.domain1.com/c.html)
- location.hash.replace('#user=', ''));
};
四、 window.name + iframe跨域
window.name屬性的獨特之處:name值在不同的頁面(甚至不同域名)加載后依舊存在,并且可以支持非常長的 name 值(2MB)。愛掏網 - it200.com
1)a.html:(http://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:(http://www.domain1.com/proxy....
中間代理頁,與a.html同域,內容為空即可。愛掏網 - it200.com
3)b.html:(http://www.domain2.com/b.html)
總結:通過iframe的src屬性由外域轉向本地域,跨域數據即由iframe的window.name從外域傳遞到本地域。愛掏網 - it200.com這個就巧妙地繞過了瀏覽器的跨域訪問限制,但同時它又是安全操作。愛掏網 - it200.com
五、 postMessage跨域
postMessage是HTML5 XMLHttpRequest Level 2中的API,且是為數不多可以跨域操作的window屬性之一,它可用于解決以下方面的問題:
a.) 頁面和其打開的新窗口的數據傳遞
b.) 多窗口之間消息傳遞
c.) 頁面與嵌套的iframe消息傳遞
d.) 上面三個場景的跨域數據傳遞
用法:postMessage(data,origin)方法接受兩個參數
data: html5規范支持任意基本類型或可復制的對象,但部分瀏覽器只支持字符串,所以傳參時最好用JSON.stringify()序列化。愛掏網 - it200.com
origin: 協議+主機+端口號,也可以設置為"*",表示可以傳遞給任意窗口,如果要指定和當前窗口同源的話設置為"/"。愛掏網 - it200.com
1)a.html:(http://www.domain1.com/a.html)
src="http://www.domain2.com/b.html"
style="display:none;">
};
// 向domain2傳送跨域數據
iframe.contentWindow.postMessage
(JSON.stringify(data),
'http://www.domain2.com');
};
// 接受domain2返回數據
window.addEventListener
('message', function(e) {
alert('data from domain2 ---> ' + e.data);
},
false);
2)b.html:(http://www.domain2.com/b.html)
data.number = 16;
// 處理后再發回domain1
window.parent.postMessage(JSON.stringify(data),
'http://www.domain1.com');
}
}, false);
六、 跨域資源共享(CORS)
普通跨域請求:只服務端設置Access-Control-Allow-Origin即可,前端無須設置,若要帶cookie請求:前后端都需要設置。愛掏網 - it200.com
需注意的是:由于同源策略的限制,所讀取的cookie為跨域請求接口所在域的cookie,而非當前頁。愛掏網 - it200.com如果想實現當前頁cookie的寫入,可參考下文:七、nginx反向代理中設置proxy_cookie_domain 和 八、NodeJs中間件代理中cookieDomainRewrite參數的設置。愛掏網 - it200.com
目前,所有瀏覽器都支持該功能(IE8+:IE8/9需要使用XDomainRequest對象來支持CORS)),CORS也已經成為主流的跨域解決方案。愛掏網 - it200.com
1、 前端設置:
1)原生ajax
// 前端設置是否帶
cookiexhr.withCredentials = true;
示例代碼:
var xhr = new XMLHttpRequest();
// IE8/9需用
window.XDomainRequest兼容
// 前端設置是否帶
cookiexhr.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);
}
};
2)jQuery ajax
$.ajax({
...
xhrFields: {
withCredentials: true
// 前端設置是否帶cookie
},
crossDomain: true,
// 會讓請求頭中包含跨域的額外信息,
但不會含cookie
...
});
3)vue框架
在vue-resource封裝的ajax組件中加入以下代碼:
Vue.http.options.credentials = true
2、 服務端設置:
若后端設置成功,前端瀏覽器控制臺則不會出現跨域報錯信息,反之,說明沒設成功。愛掏網 - it200.com
1.)Java后臺:
/*
- 導入包:
import javax.servlet.http.HttpServletResponse; - 接口參數中定義:
HttpServletResponse response
*/response.setHeader
("Access-Control-Allow-Origin",
"http://www.domain1.com");
// 若有端口需寫全(協議+域名+端口)
response.setHeader
("Access-Control-Allow-Credentials", "true");
2.)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.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...');
七、 nginx代理跨域
1、 nginx配置解決iconfont跨域
瀏覽器跨域訪問js、css、img等常規靜態資源被同源策略許可,但iconfont字體文件(eot|otf|ttf|woff|svg)例外,此時可在nginx的靜態資源服務器中加入以下配置。愛掏網 - it200.com
location / {
add_header
Access-Control-Allow-Origin *;
}
2、 nginx反向代理接口跨域
跨域原理: 同源策略是瀏覽器的安全策略,不是HTTP協議的一部分。愛掏網 - it200.com服務器端調用HTTP接口只是使用HTTP協議,不會執行JS腳本,不需要同源策略,也就不存在跨越問題。愛掏網 - it200.com
實現思路:通過nginx配置一個代理服務器(域名與domain1相同,端口不同)做跳板機,反向代理訪問domain2接口,并且可以順便修改cookie中domain信息,方便當前域cookie寫入,實現跨域登錄。愛掏網 - it200.com
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;
}
}
1) 前端代碼示例:
var xhr = new XMLHttpRequest();
// 前端開關:
瀏覽器是否讀寫cookiexhr.withCredentials = true;
// 訪問nginx中的代理服務器
xhr.open('get',
'http://www.domain1.com:81/?user=admin', true);
xhr.send();
2) 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.domain2.com;HttpOnly'
// HttpOnly:腳本無法讀取
});
res.write(JSON.stringify(params));
res.end();
});
server.listen('8080');
console.log('Server is running at port 8080...');
八、 Nodejs中間件代理跨域
node中間件實現跨域代理,原理大致與nginx相同,都是通過啟一個代理服務器,實現數據的轉發,也可以通過設置cookieDomainRewrite參數修改響應頭中cookie中域名,實現當前域的cookie寫入,方便接口登錄認證。愛掏網 - it200.com
1、 非vue框架的跨域(2次跨域)
利用node + express + http-proxy-middleware搭建一個proxy服務器。愛掏網 - it200.com
1)前端代碼示例:
var xhr = new XMLHttpRequest();
// 前端開關:
瀏覽器是否讀寫cookiexhr.withCredentials = true;
// 訪問http-proxy-middleware代理服務器
xhr.open('get', '
http://www.domain1.com:3000/login?
user=admin', true);
xhr.send();
2)中間件服務器:
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...');
3.)Nodejs后臺同(六:nginx)
2、 vue框架的跨域(1次跨域)
利用node + webpack + webpack-dev-server代理接口跨域。愛掏網 - it200.com在開發環境下,由于vue渲染服務和接口代理服務都是webpack-dev-server同一個,所以頁面與代理接口之間不再跨域,無須設置headers跨域信息了。愛掏網 - it200.com
webpack.config.js部分配置:
module.exports = {
entry: {},
module: {},
...
devServer: {
historyApiFallback: true,
proxy: [{
context: '/login',
target: 'http://www.domain2.com:8080',
// 代理跨域目標接口
changeOrigin: true,
secure: false,
// 當代理某些https服務報錯時用
cookieDomainRewrite: 'www.domain1.com'
// 可以為false,表示不修改
}],
noInfo: true
}
}
九、 WebSocket協議跨域
WebSocket protocol是HTML5一種新的協議。愛掏網 - it200.com它實現了瀏覽器與服務器全雙工通信,同時允許跨域通訊,是server push技術的一種很好的實現。愛掏網 - it200.com
原生WebSocket API使用起來不太方便,我們使用Socket.io,它很好地封裝了webSocket接口,提供了更簡單、靈活的接口,也對不支持webSocket的瀏覽器提供了向下兼容。愛掏網 - it200.com
1)前端代碼:
user input:2)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('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.');
});
});
原文發布時間為:2024-06-29
本文作者:安靜de沉淀
本文來自和通數據庫合作伙伴“Web項目聚集地”,了解相關信息可以關注“Web項目聚集地”。愛掏網 - it200.com