以上就是我在实际项目中遇到的跨域请求资源的情况,有一种跨域需要特别注意就是在https协议下发送https请求,除了使用proxy代理外其他方法都无解,会被浏览器直接block掉。如果哪位道友知道解决方法,麻烦你告诉我一声。
最后附上完整的测试demo
iss中:
<!doctype html> <html> <head> <meta charset="utf-8"> <meta 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 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 = ''; //定义了一个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); }); } } 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);