探討跨域請求資源的幾種方式

[轉自:http://www.cnblogs.com/dojo-lzz/p/4265637.html]

  1. 什么是跨域
  2. JSONP
  3. proxy代理
  4. cors
  5. xdr

  由于瀏覽器同源策略,凡是發送請求url的協議、域名、端口三者之間任意一與當前頁面地址不同即為跨域。具體可以查看下表(來源)

  

  JSONP

  這種方式主要是通過動態插入一個script標簽。瀏覽器對script的資源引用沒有同源限制,同時資源加載到頁面后會立即執行(沒有阻塞的情況下)。

復制代碼
1 <script>
2       var _script = document.createElement('script');
3       _script.type = "text/javascript";
4       _script.src = "http://localhost:8888/jsonp?callback=f";
5       document.head.appendChild(_script);
6     </script>
復制代碼

  實際項目中JSONP通常用來獲取json格式數據,這時前后端通常約定一個參數callback,該參數的值,就是處理返回數據的函數名稱。

復制代碼
 1 <!doctype html>2 <html>3   <head>4     <meta charset="utf-8">5     <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">6     <title>jsonp_test</title>7 8     <script>9       var f = function(data){
10         alert(data.name);
11       }
12       /*var xhr = new XMLHttpRequest();
13       xhr.onload = function(){
14         alert(xhr.responseText);
15       };
16       xhr.open('POST', 'http://localhost:8888/cors', true);
17       xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
18       xhr.send("f=json");*/
19     </script>
20     
21     <script>
22       var _script = document.createElement('script');
23       _script.type = "text/javascript";
24       _script.src = "http://localhost:8888/jsonp?callback=f";
25       document.head.appendChild(_script);
26     </script>
27   </head>
復制代碼
View Code
復制代碼
 1 var query = _url.query;2         console.log(query);3         var params = qs.parse(query);4         console.log(params);5         var f = "";6     7         f = params.callback;8     9         res.writeHead(200, {"Content-Type": "text/javascript"});
10         res.write(f + "({name:'hello world'})");
11         res.end();
復制代碼
View Code

  

  缺點:

  1、這種方式無法發送post請求(這里)

  2、另外要確定jsonp的請求是否失敗并不容易,大多數框架的實現都是結合超時時間來判定。

?

  Proxy代理

  這種方式首先將請求發送給后臺服務器,通過服務器來發送請求,然后將請求的結果傳遞給前端。

 1 <!doctype html>2 <html>3   <head>4     <meta charset="utf-8">5     <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">6     <title>proxy_test</title>7 8     <script>9       var f = function(data){
10         alert(data.name);
11       }
12       var xhr = new XMLHttpRequest();
13       xhr.onload = function(){
14         alert(xhr.responseText);
15       };
16       xhr.open('POST', 'http://localhost:8888/proxy?http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer', true);
17       xhr.send("f=json");
18     </script>
19   </head>
20   
21   <body>
22   </body>
23 </html>
View Code
 1 var proxyUrl = "";2       if (req.url.indexOf('?') > -1) {3           proxyUrl = req.url.substr(req.url.indexOf('?') + 1);4           console.log(proxyUrl);5       }6       if (req.method === 'GET') {7           request.get(proxyUrl).pipe(res);8       } else if (req.method === 'POST') {9           var post = '';     //定義了一個post變量,用于暫存請求體的信息
10 
11         req.on('data', function(chunk){    //通過req的data事件監聽函數,每當接受到請求體的數據,就累加到post變量中
12             post += chunk;
13         });
14     
15         req.on('end', function(){    //在end事件觸發后,通過querystring.parse將post解析為真正的POST請求格式,然后向客戶端返回。
16             post = qs.parse(post);
17             request({
18                       method: 'POST',
19                       url: proxyUrl,
20                       form: post
21                   }).pipe(res);
22         });
23       }
View Code

 

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

  

  

  還需要注意一點,對于同一請求瀏覽器通常會從緩存中讀取數據,我們有時候不想從緩存中讀取,所以會加一個preventCache參數,這個時候請求url變成:url?preventCache=12345567....;這本身沒有什么問題,問題出在當使用某些前端框架(比如jquery)發送proxy代理請求時,請求url為proxy?url,同時設置preventCache:true,框架不能正確處理這個參數,結果發出去的請求變成proxy?url&preventCache=123456(正長應為proxy?url?preventCache=12356);后端截取后發送的請求為url&preventCache=123456,根本沒有這個地址,所以你得不到正確結果。

?

  CORS

  這是現代瀏覽器支持跨域資源請求的一種方式。

  

  當你使用XMLHttpRequest發送請求時,瀏覽器發現該請求不符合同源策略,會給該請求加一個請求頭:Origin,后臺進行一系列處理,如果確定接受請求則在返回結果中加入一個響應頭:Access-Control-Allow-Origin;瀏覽器判斷該相應頭中是否包含Origin的值,如果有則瀏覽器會處理響應,我們就可以拿到響應數據,如果不包含瀏覽器直接駁回,這時我們無法拿到響應數據。

復制代碼
 1 <!doctype html>2 <html>3   <head>4     <meta charset="utf-8">5     <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">6     <title>jsonp_test</title>7 8     <script>9       /*var f = function(data){
10         alert(data.name);
11       }*/
12       var xhr = new XMLHttpRequest();
13       xhr.onload = function(){
14         alert(xhr.responseText);
15       };
16       xhr.open('POST', 'http://localhost:8888/cors', true);
17       xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
18       xhr.send("f=json");
19     </script>
20     
21     <script>
22      /* var _script = document.createElement('script');
23       _script.type = "text/javascript";
24       _script.src = "http://localhost:8888/jsonp?callback=f";
25       document.head.appendChild(_script);*/
26     </script>
27   </head>
28   
29   <body>
30   </body>
31 </html>
復制代碼
前端cors

  

復制代碼
 1 if (req.headers.origin) {2 3             res.writeHead(200, {4                 "Content-Type": "text/html; charset=UTF-8",5                 "Access-Control-Allow-Origin":'http://localhost'/*,6                 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',7                 'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type'*/8             });9             res.write('cors');
10             res.end();
11         }
復制代碼
匹配

  

  如果我們把Access-Control-Allow-Origin去掉,瀏覽器會駁回響應,我們也就拿不到數據。

  

  需要注意的一點是Preflighted Request的透明服務器驗證機制支持開發人員使用自定義的頭部、GET或POST之外的方法,以及不同類型的主題內容。總結如如:

  1、非GET 、POST請求

  2、POST請求的content-type不是常規的三個:application/x- www-form-urlencoded(使用 HTTP 的 POST 方法提交的表單)、multipart/form-data(同上,但主要用于表單提交時伴隨文件上傳的場合)、text/plain(純文本)

  3、POST請求的payload為text/html

  4、設置自定義頭部

  OPTIONS請求頭部中會包含以下頭部:Origin、Access-Control-Request-Method、Access-Control-Request-Headers,發送這個請求后,服務器可以設置如下頭部與瀏覽器溝通來判斷是否允許這個請求。

  Access-Control-Allow-Origin、Access-Control-Allow-Method、Access-Control-Allow-Headers

1 var xhr = new XMLHttpRequest();
2       xhr.onload = function(){
3         alert(xhr.responseText);
4       };
5       xhr.open('POST', 'http://localhost:8888/cors', true);
6       xhr.setRequestHeader("Content-Type", "text/html");
7       xhr.send("f=json");
View Code
 1 if (req.headers.origin) {2 3             res.writeHead(200, {4                 "Content-Type": "text/html; charset=UTF-8",5                 "Access-Control-Allow-Origin":'http://localhost',6                 'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',7                 'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type'/**/8             });9             res.write('cors');
10             res.end();
11         }
View Code

  

  如果你在調試狀態,你會發現后臺代碼執行了兩遍,說明發送了兩次請求。注意一下我們的onload代碼只執行了一次,所以說OPTIONS請求對程序來說是透明的,他的請求結果會被緩存起來。

  如果我們修改一下后臺代碼,把Content-Type去掉,你會發現OPTIONS請求失敗。

  

  通過setRequestHeader('X-Request-With', null)可以避免瀏覽器發送OPTIONS請求。

  根據我的測試,當使用cors發送跨域請求時失敗時,后臺是接收到了這次請求,后臺可能也執行了數據查詢操作,只是響應頭部不合符要求,瀏覽器阻斷了這次請求。

?

  XDR

  這是IE8、IE9提供的一種跨域解決方案,功能較弱只支持get跟post請求,而且對于協議不同的跨域是無能為力的,比如在http協議下發送https請求。看一下微軟自己的例子就行

復制代碼
 1 <!DOCTYPE html>2 3 <html>4 <body>5   <h2>XDomainRequest</h2>6   <input type="text" id="tbURL" value="http://www.contoso.com/xdr.txt" style="width: 300px"><br>7   <input type="text" id="tbTO" value="10000"><br>8   <input type="button" οnclick="mytest()" value="Get">&nbsp;&nbsp;&nbsp;9     <input type="button" οnclick="stopdata()" value="Stop">&nbsp;&nbsp;&nbsp;
10     <input type="button" οnclick="readdata()" value="Read">
11   <br>
12   <div id="dResponse"></div>
13   <script>
14     var xdr;
15     function readdata()
16     {
17       var dRes = document.getElementById('dResponse');
18       dRes.innerText = xdr.responseText;
19       alert("Content-type: " + xdr.contentType);
20       alert("Length: " + xdr.responseText.length);
21     }
22     
23     function err()
24     {
25       alert("XDR onerror");
26     }
27 
28     function timeo()
29     {
30       alert("XDR ontimeout");
31     }
32 
33     function loadd()
34     {
35       alert("XDR onload");
36       alert("Got: " + xdr.responseText);
37     }
38 
39     function progres()
40     {
41       alert("XDR onprogress");
42       alert("Got: " + xdr.responseText);
43     }
44 
45     function stopdata()
46     {
47       xdr.abort();
48     }
49 
50     function mytest()
51     {
52       var url = document.getElementById('tbURL');
53       var timeout = document.getElementById('tbTO');
54       if (window.XDomainRequest)
55       {
56         xdr = new XDomainRequest();
57         if (xdr)
58         {
59           xdr.onerror = err;
60           xdr.ontimeout = timeo;
61           xdr.onprogress = progres;
62           xdr.onload = loadd;
63           xdr.timeout = tbTO.value;
64           xdr.open("get", tbURL.value);
65           xdr.send();
66         }
67         else
68         {
69           alert("Failed to create");
70         }
71       }
72       else
73       {
74         alert("XDR doesn't exist");
75       }
76     }
77   </script>
78 </body>
79 </html>
復制代碼
View Code

?

  以上就是我在實際項目中遇到的跨域請求資源的情況,有一種跨域需要特別注意就是在https協議下發送https請求,除了使用proxy代理外其他方法都無解,會被瀏覽器直接block掉。如果哪位道友知道解決方法,麻煩你告訴我一聲。

  最后附上完整的測試demo

  iss中:

 1 <!doctype html>2 <html>3   <head>4     <meta charset="utf-8">5     <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">6     <title>jsonp_test</title>7 8     <script>9       /*var f = function(data){
10         alert(data.name);
11       }*/
12       var xhr = new XMLHttpRequest();
13       xhr.onload = function(){
14         alert(xhr.responseText);
15       };
16       xhr.open('POST', 'http://localhost:8888/cors', true);
17       xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
18       xhr.setRequestHeader("aaaa","b");
19       xhr.send("f=json");
20     </script>
21     
22     <script>
23      /* var _script = document.createElement('script');
24       _script.type = "text/javascript";
25       _script.src = "http://localhost:8888/jsonp?callback=f";
26       document.head.appendChild(_script);*/
27     </script>
28   </head>
29   
30   <body>
31   </body>
32 </html>
View Code

  node-html

復制代碼
 1 <!doctype html>2 <html>3   <head>4     <meta charset="utf-8">5     <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">6     <title>proxy_test</title>7 8     <script>9       var f = function(data){
10         alert(data.name);
11       }
12       var xhr = new XMLHttpRequest();
13       xhr.onload = function(){
14         alert(xhr.responseText);
15       };
16       xhr.open('POST', 'http://localhost:8888/proxy?https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer', true);
17       xhr.send("f=json");
18     </script>
19   </head>
20   
21   <body>
22   </body>
23 </html>
復制代碼
View Code

  node-server

復制代碼
 1 var http = require('http');2 var url = require('url');3 var fs = require('fs');4 var qs = require('querystring');5 var request = require('request');6 7 http.createServer(function(req, res){8     var _url = url.parse(req.url);9     if (_url.pathname === '/jsonp') {
10         var query = _url.query;
11         console.log(query);
12         var params = qs.parse(query);
13         console.log(params);
14         var f = "";
15     
16         f = params.callback;
17     
18         res.writeHead(200, {"Content-Type": "text/javascript"});
19         res.write(f + "({name:'hello world'})");
20         res.end();
21     } else if (_url.pathname === '/proxy') {
22       var proxyUrl = "";
23       if (req.url.indexOf('?') > -1) {
24           proxyUrl = req.url.substr(req.url.indexOf('?') + 1);
25           console.log(proxyUrl);
26       }
27       if (req.method === 'GET') {
28           request.get(proxyUrl).pipe(res);
29       } else if (req.method === 'POST') {
30           var post = '';     //定義了一個post變量,用于暫存請求體的信息
31 
32         req.on('data', function(chunk){    //通過req的data事件監聽函數,每當接受到請求體的數據,就累加到post變量中
33             post += chunk;
34         });
35     
36         req.on('end', function(){    //在end事件觸發后,通過querystring.parse將post解析為真正的POST請求格式,然后向客戶端返回。
37             post = qs.parse(post);
38             request({
39                       method: 'POST',
40                       url: proxyUrl,
41                       form: post
42                   }).pipe(res);
43         });
44       }
45     } else if (_url.pathname === '/index') {
46         fs.readFile('./index.html', function(err, data) {
47           res.writeHead(200, {"Content-Type": "text/html; charset=UTF-8"});
48             res.write(data);
49             res.end();
50         });
51     } else if (_url.pathname === '/cors') {
52         if (req.headers.origin) {
53 
54             res.writeHead(200, {
55                 "Content-Type": "text/html; charset=UTF-8",
56                 "Access-Control-Allow-Origin":'http://localhost',
57                 'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
58                 'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type,aaaa'/**/
59             });
60             res.write('cors');
61             res.end();
62         }
63     }
64     
65 }).listen(8888);
復制代碼
View Code

參考文獻:

javascript跨域資源總結與解決辦法

jsonp跨域原理解析

Ajax進行跨域資源方法詳解

Ajax POST&跨域 解決方案

HTTP access control

POST請求失敗,變成options請求

XDomainRequest - Restrictions, Limitations and Workarounds

XDomainRequest object

轉載于:https://www.cnblogs.com/kennyliu/p/6831089.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/392909.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392909.shtml
英文地址,請注明出處:http://en.pswp.cn/news/392909.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

算法訓練營 重編碼_編碼訓練營適合您嗎?

算法訓練營 重編碼by Joanna Gaudyn喬安娜高登(Joanna Gaudyn) 編碼訓練營適合您嗎&#xff1f; (Is a Coding Bootcamp something for you?) Coding bootcamps’ popularity is growing. It sounds like a perfect idea to fast-forward your career. But is it really some…

leetcode 771. 寶石與石頭(set)

給定字符串J 代表石頭中寶石的類型&#xff0c;和字符串 S代表你擁有的石頭。 S 中每個字符代表了一種你擁有的石頭的類型&#xff0c;你想知道你擁有的石頭中有多少是寶石。 J 中的字母不重復&#xff0c;J 和 S中的所有字符都是字母。字母區分大小寫&#xff0c;因此"a…

用ntdsutil命令中的restore object 更新版本號

備份域控建立好后&#xff0c;備份域信息&#xff0c;用目錄還 原模式&#xff0c;還原域信息&#xff0c;用ntdsutil命令&#xff0c;中的 restore ob ject 更新版本號 本文轉自9pc9com博客&#xff0c;原文鏈接&#xff1a; http://blog.51cto.com/215363/783334 如需…

python處理excel文件(xls和xlsx)

一、xlrd和xlwt 使用之前需要需要先安裝&#xff0c;windows上如果直接在cmd中運行python則需要先執行pip3 install xlrd和pip3 install xlwt&#xff0c;如果使用pycharm則需要在項目的解釋器中安裝這兩個模塊&#xff0c;File-Settings-Project:layout-Project Interpreter&a…

html塊中的內容垂直居中,css如何設置行內元素與塊級元素的內容垂直居中

首先我們先了解一下行內元素和塊級元素行內元素(內聯元素)&#xff1a;沒有自己的獨立空間&#xff0c;它是依附于其他塊級元素存在的&#xff0c;空間大小依附于內容多少。行內元素沒有度、寬度、內外邊距等屬性。塊級元素&#xff1a;占據獨立的空間&#xff0c;具有寬度&…

Mina、Netty、Twisted一起學(五):整合protobuf

protobuf是谷歌的Protocol Buffers的簡稱&#xff0c;用于結構化數據和字節碼之間互相轉換&#xff08;序列化、反序列化&#xff09;&#xff0c;一般應用于網絡傳輸&#xff0c;可支持多種編程語言。protobuf怎樣使用這里不再介紹&#xff0c;本文主要介紹在MINA、Netty、Twi…

leetcode 1. 兩數之和(map)

給定一個整數數組 nums 和一個目標值 target&#xff0c;請你在該數組中找出和為目標值的那 兩個 整數&#xff0c;并返回他們的數組下標。 你可以假設每種輸入只會對應一個答案。但是&#xff0c;數組中同一個元素不能使用兩遍。 示例: 給定 nums [2, 7, 11, 15], target …

Redis 3.0.1 安裝和配置

一、下載&#xff0c;解壓和編譯Redis 12345# cd /tmp # wget http://download.redis.io/releases/redis-3.0.1.tar.gz # tar xzf redis-3.0.1.tar.gz # cd redis-3.0.1 # make二、下載、安裝tclsh 測試編譯&#xff1a; 1# make test得到如下錯誤信息&#xff1a; …

2021年南寧二中高考成績查詢,2021廣西高考圓滿結束,6月23日可查詢成績

6月8日下午&#xff0c;2021年高考統考圓滿結束。今年廣西參加高考統考考生人數40.05萬余人&#xff0c;比2020年增加了2.2萬人。我區預計6月23日可查詢高考成績&#xff0c;6月24日起可陸續填報志愿&#xff0c;我區的網上咨詢會將于6月25日至27日舉辦。▲高考結束&#xff0c…

29 Python - 字符與編碼

字符與編碼 01 字符串本質 Python字符串相關概念 字符串 str 字節 bytes 字節數組 bytearray 電腦字符串存儲機制 字符庫&#xff1a;A、B每個字符有一個代碼點如A是65 B為66&#xff0c;這種是方便人類讀寫的形式&#xff0c;但是最終需要存入計算機的CPU和內存&…

Linux 內存管理與系統架構設計

Linux 提供各種模式&#xff08;比如&#xff0c;消息隊列&#xff09;&#xff0c;但是最著名的是 POSIX 共享內存&#xff08;shmem&#xff0c;shared memory&#xff09;。 Linux provides a variety of schemes (such as message queues), but most notable is POSIX shar…

如何正確使用Node.js中的事件

by Usama Ashraf通過Usama Ashraf 如何正確使用Node.js中的事件 (How to use events in Node.js the right way) Before event-driven programming became popular, the standard way to communicate between different parts of an application was pretty straightforward: …

你的成功有章可循

讀書筆記 作者 海軍 海天裝飾董事長 自我修煉是基礎。通過自我學習&#xff0c;在預定目標的指引下&#xff0c;將獲取的知識轉化為個人能力&#xff0c;形成自我規律&#xff0c;不斷循環&#xff0c;實現成功。 尋找和掌握規律&#xff0c;并熟練運用于實踐&#xff0c;是成功…

98k用計算機圖片,98K (HandClap)_譜友園地_中國曲譜網

《98K》文本歌詞98K之歌-HandClap-抖音 制譜&#xff1a;孫世彥這首《HandClap》是Fitz&TheTantrums樂隊演唱的一首歌曲&#xff0c;同時也是絕地求生中囂張BGM&#xff0c;是一首吃雞戰歌&#xff01;這首歌譜曲者和填詞者都是三個人&#xff1a;JeremyRuzumna&#xff0c…

qt之旅-1純手寫Qt界面

通過手寫qt代碼來認識qt程序的構成&#xff0c;以及特性。設計一個查找對話框。以下是設計過程1 新建一個empty qt project2 配置pro文件HEADERS \Find.h QT widgetsSOURCES \Find.cpp \main.cpp3 編寫對話框的類代碼例如以下&#xff1a;//Find.h #ifndef FIND_H #define F…

【隨筆】寫在2014年的第一天

想想好像就在不久前還和大家異常興奮地討論著世界末日的事&#xff0c;結果一晃也是一年前的事了。大四這一年&#xff0c;或者說整個2013年都是場搖擺不定的戲劇&#xff0c;去過的地方比前三年加起來還多的多&#xff0c;有時候也會恍惚地不知道自己現在在哪。簡單記幾筆&…

設計沖刺下載_如何運行成功的設計沖刺

設計沖刺下載by George Krasadakis通過喬治克拉薩達基斯(George Krasadakis) Design Sprints can generate remarkable output for your company — such as a backlog of impactful ideas, functional prototypes, learning and key insights from customers along with real…

leetcode 18. 四數之和(雙指針)

給定一個包含 n 個整數的數組 nums 和一個目標值 target&#xff0c;判斷 nums 中是否存在四個元素 a&#xff0c;b&#xff0c;c 和 d &#xff0c;使得 a b c d 的值與 target 相等&#xff1f;找出所有滿足條件且不重復的四元組。 注意&#xff1a; 答案中不可以包含重…

WPF:從WPF Diagram Designer Part 4學習分組、對齊、排序、序列化和常用功能

在前面三篇文章中我們介紹了如何給圖形設計器增加移動、選擇、改變大小及面板、縮略圖、框線選擇和工具箱和連接等功能&#xff0c;本篇是這個圖形設計器系列的最后一篇&#xff0c;將和大家一起來學習一下如何給圖形設計器增加分組、對齊、排序、序列化等功能。 WPF Diagram D…

win7如何看計算機用戶名和密碼怎么辦,win7系統電腦查看共享文件夾時不顯示用戶名和密碼輸入窗口的解決方法...

win7系統使用久了&#xff0c;好多網友反饋說win7系統電腦查看共享文件夾時不顯示用戶名和密碼輸入窗口的問題&#xff0c;非常不方便。有什么辦法可以永久解決win7系統電腦查看共享文件夾時不顯示用戶名和密碼輸入窗口的問題&#xff0c;面對win7系統電腦查看共享文件夾時不顯…