跨域请求资源几种方式
来源:互联网 发布:黄石爱康医院网络预约 编辑:程序博客网 时间:2024/06/06 01:02
- 什么是跨域
- JSONP
- proxy代理
- cors
- 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;
5document.head.appendChild(_script);
6 </script>
然而,实际项目中JSONP通常用来获取json格式数据,这时前后端通常约定一个参数callback,该参数的值,就是处理返回数据的函数名称。
<!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){
10alert(data.name);
11}
12/*var xhr = new XMLHttpRequest();
13xhr.onload = function(){
14alert(xhr.responseText);
15};
16xhr.open('POST', 'http://localhost:8888/cors', true);
17xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
18xhr.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
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();
缺点: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>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 = ''; //定义了一个post变量,用于暂存请求体的信息req.on('data', function(chunk){ //通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
post += chunk;
});
req.on('end', function(){ //在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
post = qs.parse(post);
request({
method: 'POST',
url: proxyUrl,
form: post
}).pipe(res);
});
}需要注意的是如果你代理的是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的值,如果有则浏览器会处理响应,我们就可以拿到响应数据,如果不包含浏览器直接驳回,这时我们无法拿到响应数据。
<!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>
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去掉,浏览器会驳回响应,我们也就拿不到数据。
需要注意的一点是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");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 }
以上就是我在实际项目中遇到的跨域请求资源的情况,有一种跨域需要特别注意就是在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>
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: post42 }).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);
- 跨域请求资源几种方式
- 探讨跨域请求资源的几种方式
- 探讨跨域请求资源的几种方式
- 探讨跨域请求资源的几种方式
- 探讨跨域请求资源的几种方式
- 探讨跨域请求资源的几种方式
- 探讨跨域请求资源的几种方式
- 探讨跨域请求资源的几种方式
- 探讨跨域请求资源的几种方式
- 探讨跨域请求资源的几种方式
- 探讨跨域请求资源的几种方式
- 探讨跨域请求资源的几种方式
- 跨域请求的几种方式
- android网络请求的几种方式,android怎么请求服务器资源
- jsonp跨域请求的几种方式
- 跨域请求的几种实现方式
- 跨域请求的几种实现方式
- 获取url资源的几种方式
- 关于Eclipes的Logcat无法打印消息的解决办法
- makefile 之=
- java 常见的面试题技巧(框架)
- linux文件读取
- swt/jface 自定义 Dialog
- 跨域请求资源几种方式
- Android Studio动态模板
- 内网一键生成 LetsEncrypt HTTPS证书 - 1
- OGNL表达式语言以及在Structs中的运用
- &运算和|运算
- bzoj 4581: [Usaco2016 Open]Field Reduction (dfs)
- android 属性动画
- PullToRefreshLayout实现上下拉刷新
- 深入Android databinding的使用和原理分析