探討跨域請求資源的幾種方式(總結(jié))
跨域請求資源的幾種方式,具體如下:
1.什么是跨域
2.JSONP
3.proxy代理
4.cors
5.xdr
由于瀏覽器同源策略,凡是發(fā)送請求url的協(xié)議、域名、端口三者之間任意一與當(dāng)前頁面地址不同即為跨域。具體可以查看下表

JSONP
這種方式主要是通過動態(tài)插入一個(gè)script標(biāo)簽。瀏覽器對script的資源引用沒有同源限制,同時(shí)資源加載到頁面后會立即執(zhí)行(沒有阻塞的情況下)。
<script>
var _script = document.createElement('script');
_script.type = "text/javascript";
_script.src = "http://localhost:8888/jsonp?callback=f";
document.head.appendChild(_script);
</script>
實(shí)際項(xiàng)目中JSONP通常用來獲取json格式數(shù)據(jù),這時(shí)前后端通常約定一個(gè)參數(shù)callback,該參數(shù)的值,就是處理返回?cái)?shù)據(jù)的函數(shù)名稱。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>jsonp_test</title>
<script>
var f = function(data){
alert(data.name);
}
/*var xhr = new XMLHttpRequest();
xhr.onload = function(){
alert(xhr.responseText);
};
xhr.open('POST', 'http://localhost:8888/cors', true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("f=json");*/
</script>
<script>
var _script = document.createElement('script');
_script.type = "text/javascript";
_script.src = "http://localhost:8888/jsonp?callback=f";
document.head.appendChild(_script);
</script>
</head>
var query = _url.query;
console.log(query);
var params = qs.parse(query);
console.log(params);
var f = "";
f = params.callback;
res.writeHead(200, {"Content-Type": "text/javascript"});
res.write(f + "({name:'hello world'})");
res.end();

缺點(diǎn):
1、這種方式無法發(fā)送post請求(這里)
2、另外要確定jsonp的請求是否失敗并不容易,大多數(shù)框架的實(shí)現(xiàn)都是結(jié)合超時(shí)時(shí)間來判定。
Proxy代理
這種方式首先將請求發(fā)送給后臺服務(wù)器,通過服務(wù)器來發(fā)送請求,然后將請求的結(jié)果傳遞給前端。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>proxy_test</title>
<script>
var f = function(data){
alert(data.name);
}
var xhr = new XMLHttpRequest();
xhr.onload = function(){
alert(xhr.responseText);
};
xhr.open('POST', 'http://localhost:8888/proxy?http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer', true);
xhr.send("f=json");
</script>
</head>
<body>
</body>
</html>
var proxyUrl = "";
if (req.url.indexOf('?') > -1) {
proxyUrl = req.url.substr(req.url.indexOf('?') + 1);
console.log(proxyUrl);
}
if (req.method === 'GET') {
request.get(proxyUrl).pipe(res);
} else if (req.method === 'POST') {
var post = ''; //定義了一個(gè)post變量,用于暫存請求體的信息
req.on('data', function(chunk){ //通過req的data事件監(jiān)聽函數(shù),每當(dāng)接受到請求體的數(shù)據(jù),就累加到post變量中
post += chunk;
});
req.on('end', function(){ //在end事件觸發(fā)后,通過querystring.parse將post解析為真正的POST請求格式,然后向客戶端返回。
post = qs.parse(post);
request({
method: 'POST',
url: proxyUrl,
form: post
}).pipe(res);
});
}

需要注意的是如果你代理的是https協(xié)議的請求,那么你的proxy首先需要信任該證書(尤其是自定義證書)或者忽略證書檢查,否則你的請求無法成功。12306就提供了一個(gè)鮮活的例子。


還需要注意一點(diǎn),對于同一請求瀏覽器通常會從緩存中讀取數(shù)據(jù),我們有時(shí)候不想從緩存中讀取,所以會加一個(gè)preventCache參數(shù),這個(gè)時(shí)候請求url變成:url?preventCache=12345567....;這本身沒有什么問題,問題出在當(dāng)使用某些前端框架(比如jquery)發(fā)送proxy代理請求時(shí),請求url為proxy?url,同時(shí)設(shè)置preventCache:true,框架不能正確處理這個(gè)參數(shù),結(jié)果發(fā)出去的請求變成proxy?url&preventCache=123456(正長應(yīng)為proxy?url?preventCache=12356);后端截取后發(fā)送的請求為url&preventCache=123456,根本沒有這個(gè)地址,所以你得不到正確結(jié)果。
CORS
這是現(xiàn)代瀏覽器支持跨域資源請求的一種方式。

當(dāng)你使用XMLHttpRequest發(fā)送請求時(shí),瀏覽器發(fā)現(xiàn)該請求不符合同源策略,會給該請求加一個(gè)請求頭:Origin,后臺進(jìn)行一系列處理,如果確定接受請求則在返回結(jié)果中加入一個(gè)響應(yīng)頭:Access-Control-Allow-Origin;瀏覽器判斷該相應(yīng)頭中是否包含Origin的值,如果有則瀏覽器會處理響應(yīng),我們就可以拿到響應(yīng)數(shù)據(jù),如果不包含瀏覽器直接駁回,這時(shí)我們無法拿到響應(yīng)數(shù)據(jù)。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>jsonp_test</title>
<script>
/*var f = function(data){
alert(data.name);
}*/
var xhr = new XMLHttpRequest();
xhr.onload = function(){
alert(xhr.responseText);
};
xhr.open('POST', 'http://localhost:8888/cors', true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("f=json");
</script>
<script>
/* var _script = document.createElement('script');
_script.type = "text/javascript";
_script.src = "http://localhost:8888/jsonp?callback=f";
document.head.appendChild(_script);*/
</script>
</head>
<body>
</body>
</html>
前端cors
if (req.headers.origin) {
res.writeHead(200, {
"Content-Type": "text/html; charset=UTF-8",
"Access-Control-Allow-Origin":'http://localhost'/*,
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type'*/
});
res.write('cors');
res.end();
}

如果我們把Access-Control-Allow-Origin去掉,瀏覽器會駁回響應(yīng),我們也就拿不到數(shù)據(jù)。

需要注意的一點(diǎn)是Preflighted Request的透明服務(wù)器驗(yàn)證機(jī)制支持開發(fā)人員使用自定義的頭部、GET或POST之外的方法,以及不同類型的主題內(nèi)容。總結(jié)如如:
1、非GET 、POST請求
2、POST請求的content-type不是常規(guī)的三個(gè):application/x- www-form-urlencoded(使用 HTTP 的 POST 方法提交的表單)、multipart/form-data(同上,但主要用于表單提交時(shí)伴隨文件上傳的場合)、text/plain(純文本)
3、POST請求的payload為text/html
4、設(shè)置自定義頭部
OPTIONS請求頭部中會包含以下頭部:Origin、Access-Control-Request-Method、Access-Control-Request-Headers,發(fā)送這個(gè)請求后,服務(wù)器可以設(shè)置如下頭部與瀏覽器溝通來判斷是否允許這個(gè)請求。
Access-Control-Allow-Origin、Access-Control-Allow-Method、Access-Control-Allow-Headers
var xhr = new XMLHttpRequest();
xhr.onload = function(){
alert(xhr.responseText);
};
xhr.open('POST', 'http://localhost:8888/cors', true);
xhr.setRequestHeader("Content-Type", "text/html");
xhr.send("f=json");
if (req.headers.origin) {
res.writeHead(200, {
"Content-Type": "text/html; charset=UTF-8",
"Access-Control-Allow-Origin":'http://localhost',
'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type'/**/
});
res.write('cors');
res.end();
}

如果你在調(diào)試狀態(tài),你會發(fā)現(xiàn)后臺代碼執(zhí)行了兩遍,說明發(fā)送了兩次請求。注意一下我們的onload代碼只執(zhí)行了一次,所以說OPTIONS請求對程序來說是透明的,他的請求結(jié)果會被緩存起來。
如果我們修改一下后臺代碼,把Content-Type去掉,你會發(fā)現(xiàn)OPTIONS請求失敗。


通過setRequestHeader('X-Request-With', null)可以避免瀏覽器發(fā)送OPTIONS請求。
根據(jù)我的測試,當(dāng)使用cors發(fā)送跨域請求時(shí)失敗時(shí),后臺是接收到了這次請求,后臺可能也執(zhí)行了數(shù)據(jù)查詢操作,只是響應(yīng)頭部不合符要求,瀏覽器阻斷了這次請求。
XDR
這是IE8、IE9提供的一種跨域解決方案,功能較弱只支持get跟post請求,而且對于協(xié)議不同的跨域是無能為力的,比如在http協(xié)議下發(fā)送https請求??匆幌挛④涀约旱睦泳托?br />
<!DOCTYPE html>
<html>
<body>
<h2>XDomainRequest</h2>
<input type="text" id="tbURL" value="http://www.contoso.com/xdr.txt" style="width: 300px"><br>
<input type="text" id="tbTO" value="10000"><br>
<input type="button" onclick="mytest()" value="Get">
<input type="button" onclick="stopdata()" value="Stop">
<input type="button" onclick="readdata()" value="Read">
<br>
<div id="dResponse"></div>
<script>
var xdr;
function readdata()
{
var dRes = document.getElementById('dResponse');
dRes.innerText = xdr.responseText;
alert("Content-type: " + xdr.contentType);
alert("Length: " + xdr.responseText.length);
}
function err()
{
alert("XDR onerror");
}
function timeo()
{
alert("XDR ontimeout");
}
function loadd()
{
alert("XDR onload");
alert("Got: " + xdr.responseText);
}
function progres()
{
alert("XDR onprogress");
alert("Got: " + xdr.responseText);
}
function stopdata()
{
xdr.abort();
}
function mytest()
{
var url = document.getElementById('tbURL');
var timeout = document.getElementById('tbTO');
if (window.XDomainRequest)
{
xdr = new XDomainRequest();
if (xdr)
{
xdr.onerror = err;
xdr.ontimeout = timeo;
xdr.onprogress = progres;
xdr.onload = loadd;
xdr.timeout = tbTO.value;
xdr.open("get", tbURL.value);
xdr.send();
}
else
{
alert("Failed to create");
}
}
else
{
alert("XDR doesn't exist");
}
}
</script>
</body>
</html>
以上就是我在實(shí)際項(xiàng)目中遇到的跨域請求資源的情況,有一種跨域需要特別注意就是在https協(xié)議下發(fā)送https請求,除了使用proxy代理外其他方法都無解,會被瀏覽器直接block掉。如果哪位道友知道解決方法,麻煩你告訴我一聲。
最后附上完整的測試demo
iss中:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>jsonp_test</title>
<script>
/*var f = function(data){
alert(data.name);
}*/
var xhr = new XMLHttpRequest();
xhr.onload = function(){
alert(xhr.responseText);
};
xhr.open('POST', 'http://localhost:8888/cors', true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("aaaa","b");
xhr.send("f=json");
</script>
<script>
/* var _script = document.createElement('script');
_script.type = "text/javascript";
_script.src = "http://localhost:8888/jsonp?callback=f";
document.head.appendChild(_script);*/
</script>
</head>
<body>
</body>
</html>
node-html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>proxy_test</title>
<script>
var f = function(data){
alert(data.name);
}
var xhr = new XMLHttpRequest();
xhr.onload = function(){
alert(xhr.responseText);
};
xhr.open('POST', 'http://localhost:8888/proxy?https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer', true);
xhr.send("f=json");
</script>
</head>
<body>
</body>
</html>
node-server
var http = require('http');
var url = require('url');
var fs = require('fs');
var qs = require('querystring');
var request = require('request');
http.createServer(function(req, res){
var _url = url.parse(req.url);
if (_url.pathname === '/jsonp') {
var query = _url.query;
console.log(query);
var params = qs.parse(query);
console.log(params);
var f = "";
f = params.callback;
res.writeHead(200, {"Content-Type": "text/javascript"});
res.write(f + "({name:'hello world'})");
res.end();
} else if (_url.pathname === '/proxy') {
var proxyUrl = "";
if (req.url.indexOf('?') > -1) {
proxyUrl = req.url.substr(req.url.indexOf('?') + 1);
console.log(proxyUrl);
}
if (req.method === 'GET') {
request.get(proxyUrl).pipe(res);
} else if (req.method === 'POST') {
var post = ''; //定義了一個(gè)post變量,用于暫存請求體的信息
req.on('data', function(chunk){ //通過req的data事件監(jiān)聽函數(shù),每當(dāng)接受到請求體的數(shù)據(jù),就累加到post變量中
post += chunk;
});
req.on('end', function(){ //在end事件觸發(fā)后,通過querystring.parse將post解析為真正的POST請求格式,然后向客戶端返回。
post = qs.parse(post);
request({
method: 'POST',
url: proxyUrl,
form: post
}).pipe(res);
});
}
} else if (_url.pathname === '/index') {
fs.readFile('./index.html', function(err, data) {
res.writeHead(200, {"Content-Type": "text/html; charset=UTF-8"});
res.write(data);
res.end();
});
} else if (_url.pathname === '/cors') {
if (req.headers.origin) {
res.writeHead(200, {
"Content-Type": "text/html; charset=UTF-8",
"Access-Control-Allow-Origin":'http://localhost',
'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type,aaaa'/**/
});
res.write('cors');
res.end();
}
}
}).listen(8888);
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript中的finally()方法和Filter()方法詳解
finally是 JavaScript 構(gòu)造中使用的方法try-catch,Filter() 是 JavaScript 中的一種方法,可以通過處理數(shù)組輕松提供過濾后的輸出數(shù)據(jù),本文就給大家詳細(xì)的介紹一下JavaScript中的finally()方法和Filter()方法,需要的朋友可以參考下2023-08-08
js的for in循環(huán)和java里foreach循環(huán)的區(qū)別分析
這篇文章主要介紹了js的for in循環(huán)和java里foreach循環(huán)的區(qū)別,實(shí)例分析了js的for in循環(huán)使用技巧并說明了與Java中foreach循環(huán)的使用區(qū)別,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-01-01
JS+CSS實(shí)現(xiàn)自動切換的網(wǎng)頁滑動門菜單效果代碼
這篇文章主要介紹了JS+CSS實(shí)現(xiàn)自動切換的網(wǎng)頁滑動門菜單效果代碼,涉及JavaScript基于時(shí)間函數(shù)動態(tài)變換頁面tab樣式的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-09-09
Display SQL Server Version Information
Display SQL Server Version Information...2007-06-06
小程序開發(fā)中如何使用async-await并封裝公共異步請求的方法
在平常的項(xiàng)目開發(fā)中肯定會遇到同步異步執(zhí)行的問題,這篇文章主要介紹了小程序開發(fā)中如何使用async-await并封裝公共異步請求的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01
javascript動態(tài)創(chuàng)建表格及添加數(shù)據(jù)實(shí)例詳解
這篇文章主要介紹了javascript動態(tài)創(chuàng)建表格及添加數(shù)據(jù),以實(shí)例形式分析了javascript動態(tài)創(chuàng)建表格的常用方法,包括不兼容IE6與兼容IE6的實(shí)現(xiàn)方法,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-05-05
微信小程序中target和currentTarget的區(qū)別小結(jié)
這篇文章主要給大家介紹了關(guān)于微信小程序中target和currentTarget區(qū)別的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11

