探讨跨域请求资源的几种方式

[转自: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.mzph.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系统电脑查看共享文件夹时不显…